1/*! For license information please see 9515.9d3000cd.chunk.js.LICENSE.txt */ 2"use strict";(self.webpackChunkwhatsapp_dashboard=self.webpackChunkwhatsapp_dashboard||[]).push([[9515,5975,480],{66102:(e,t,a)=>{a.d(t,{$G:()=>d,AV:()=>n,EB:()=>l,It:()=>o,Ou:()=>c,iC:()=>r});var i=a(68166),s=a(6192);const n=function(){return"".concat(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").concat((0,i.Z)())},o=e=>{var t;const a=null===e||void 0===e||null===(t=e.response)||void 0===t?void 0:t.status,i=r(e);return 400===a&&"string"===typeof i&&(/reached the limit of\s*\d+\s*flows/i.test(i)||/reached the limit/i.test(i)&&/flow/i.test(i))},r=function(e){var t;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const i=null===e||void 0===e||null===(t=e.response)||void 0===t?void 0:t.data;return"string"===typeof i?i:(null===i||void 0===i?void 0:i.message)||a},l=e=>{let{id:t,agents:a,assistantId:i}=e;if(!t)return"";const n=a?a[t]:{};return n?n.displayName||"":((0,s.Sj)(i,!0),"")},d=(e,t)=>(e||"").length>t?e.substring(0,t)+"..":e,c=(e,t,a)=>{const i=Number(e);return""!==e&&Number.isFinite(i)?String(Math.min(a,Math.max(t,Math.floor(i)))):""}},40480:(e,t,a)=>{a.r(t),a.d(t,{default:()=>T});var i=a(47313),s=a(73908),n=a(57009),o=a(72728),r=a(84747),l=a(21144),d=a(34882),c=a(20337),p=a(11652),u=a(61809),h=a(95939),m=a(54070),g=a(78371),x=a(52376),v=a(88012),y=a(65681),f=a(63830),A=a(45788),b=a(58889),S=a(81766),I=a(70089),j=a(1805),C=a(98873),w=a(46417);class k extends i.Component{constructor(e){super(e),this.updateAmount=e=>{this.setState({amount:e.target.value.replace(/[^0-9]+/,"")})},this.createOrderOneTimeOnRazorpay=async()=>{this.props.isFromAdsMediaSection&&this.props.closeDialog&&this.props.closeDialog(),this.setState({isMacLoading:!0});const{assistantId:e,currency:t,assistantName:a,billingAddress:i}=this.props.assistantDetails,{name:s,email:n,contact:o,id:r}=this.props.login,l=this.state.amount,d={assistantId:e,currency:t,clientId:r,name:(null===i||void 0===i?void 0:i.firstName)+(null!==i&&void 0!==i&&i.lastName?" ".concat(null===i||void 0===i?void 0:i.lastName):"")||s,email:(null===i||void 0===i?void 0:i.email)||n,contact:(null===i||void 0===i?void 0:i.phone)||o,amount:l,assistantName:a,purpose:"AI-CREDIT"};I.Z.post(j.URL+"/payment/create-order-one-time-charge",d).then((e=>{const t=e.data,{order:a,publicToken:i}=t,{id:s,amount_due:n}=a;this.setState({orderId:s,amountToPay:n,publicToken:i},(()=>{this.razorpay()}))})).catch((e=>{var t,a;this.setState({isMacLoading:!1});const i=null===e||void 0===e||null===(t=e.response)||void 0===t||null===(a=t.data)||void 0===a?void 0:a.message;this.props.showSnackbar({alertOpen:!0,alertMsg:i||"Failed to Collect Payment, please contact support!",severity:"error"})}))},this.razorpay=()=>{const{assistantDetails:e}=this.props,{partner:t,assistantName:a,billingAddress:i,assistantId:s}=e,{brandFullLogo:n,brandName:o}=t||{},{publicToken:r,orderId:l,amountToPay:d}=this.state,{name:c,email:p,contact:u,id:h}=this.props.login,m=((null===i||void 0===i?void 0:i.firstName)||"")+(null!==i&&void 0!==i&&i.lastName?"".concat(i.lastName):"")||c,g={...r?{key:r}:{},amount:d,currency:"INR",name:o||"AiSensy",description:"Purchase ".concat(d," AI Credits for AI-powered content creation"),image:n||C,order_id:l,prefill:{name:m,email:(null===i||void 0===i?void 0:i.email)||p,contact:(null===i||void 0===i?void 0:i.phone)||u},theme:{color:"#3399cc"},redirect:!1,remember_customer:!0,modal:{backdropclose:!1,escape:!1,handleback:!0,animation:!0,confirm_close:!0,ondismiss:()=>{this.setState({isWccLoading:!1})}},retry:{enabled:!0},readonly:{contact:!0,email:!0,name:!0},handler:e=>{this.onSuccess(e)}},x=new window.Razorpay(g);x.on("payment.failed",(e=>{this.onFailure(e)})),x.open()},this.onFailure=e=>{e.orderId=this.state.orderId,I.Z.post(j.URL+"/payment/update-failed-order",{...e,assistantId:this.props.assistantDetails.assistantId}).then((e=>{this.props.showSnackbar({alertOpen:!0,alertMsg:"AI Credits purchase failed. Please try again!",severity:"error"}),this.setState({isWccLoading:!1})})).catch((e=>{this.props.showSnackbar({alertOpen:!0,alertMsg:"Unable to update failed AI Credits payment from razorpay!",severity:"error"}),this.setState({isWccLoading:!1})}
2))},this.onSuccess=e=>{e.orderId=this.state.orderId,I.Z.post(j.URL+"/payment/verify-payment",{...e,assistantId:this.props.assistantDetails.assistantId}).then((e=>{this.props.showSnackbar({alertOpen:!0,alertMsg:"AI Credits purchased successfully! Please wait...",severity:"success"}),window.location.reload()})).catch((e=>{this.props.showSnackbar({alertOpen:!0,alertMsg:"Unable to verify AI Credits payment from razorpay!",severity:"error"}),this.setState({isWccLoading:!1})}))},this.state={amount:1500,wccPaymentDialog:!1,planPaymentUrl:"",isMacLoading:!1}}componentDidMount(){const{currency:e}=this.props.assistantDetails;this.setState({amount:"USD"===e?30:1500});const t=document.createElement("script");return t.src="https://checkout.razorpay.com/v1/checkout.js",t.async=!0,document.body.appendChild(t),()=>{document.body.removeChild(t)}}render(){var e,t,a,i,x,f,A,S,C,k,Z,T,D,P,B,E;const{classes:N,match:L,assistantDetails:F,showSnackbar:M,closeDialog:R}=this.props,O=window.innerWidth<767,{currency:U,aiCredit:z}=F,_=L.params.projectId,{amount:W}=this.state,H="INR"==U?1500:30;return(0,w.jsxs)("div",{className:N.root,children:[(0,w.jsxs)(s.Z,{border:"1px solid lightgrey",p:3,borderRadius:8,children:[(0,w.jsx)(n.Z,{variant:"h4",children:"Enter AI Credit Amount"}),(0,w.jsx)(n.Z,{variant:"body2",color:"textSecondary",style:{padding:"8px 0"},children:"Minimum purchase of ".concat("USD"===U?"$30":"\u20b91500"," AI credits is required")}),(0,w.jsx)(o.Z,{fullWidth:!0,placeholder:"Enter AI credit amount here",value:W,type:"number",onChange:this.updateAmount,InputProps:{startAdornment:(0,w.jsx)(r.Z,{position:"start",children:"USD"===U?"$":"\u20b9"})}}),z<0&&(0,w.jsx)(n.Z,{variant:"body2",color:"error",style:{margin:"8px 0 0px 4px"},children:"Purchase AI credits higher than due amount to resume AI services."}),(0,w.jsxs)(l.Z,{container:!0,style:{marginTop:12},children:[localStorage.getItem("creditInCache")&&(0,w.jsx)(d.ZP,{title:"Repeat previous recharge",children:(0,w.jsx)(c.Z,{style:{border:"1px solid #0a474c",color:"#0a474c",marginRight:8,marginBottom:8},variant:"outlined",color:"blue",onClick:()=>{const e=localStorage.getItem("creditInCache");this.setState({amount:Number(e)})},startIcon:(0,w.jsx)(v.Z,{style:{fontSize:16}}),children:localStorage.getItem("creditInCache")})}),(0,w.jsxs)(c.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+2500/("USD"==U?100:1)})},children:["+",2500/("USD"==U?100:1)]}),(0,w.jsxs)(c.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+5e3/("USD"==U?100:1)})},children:["+",5e3/("USD"==U?100:1)]}),(0,w.jsxs)(c.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+1e4/("USD"==U?100:1)})},children:["+",1e4/("USD"==U?100:1)]}),(0,w.jsxs)(c.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+5e4/("USD"==U?100:1)})},children:["+",5e4/("USD"==U?100:1)]})]}),(0,w.jsx)(l.Z,{container:!0,style:{display:"flex",flexDirection:"INR"!==this.props.assistantDetails.currency?"row-reverse":"inherit",justifyContent:"INR"!==this.props.assistantDetails.currency?"flex-end":"flex-start",gap:"14px"},children:(0,w.jsx)(l.Z,{item:!0,md:12,children:(0,w.jsx)(d.ZP,{interactive:!0,title:null!==(e=this.props.assistantDetails)&&void 0!==e&&null!==(t=e.billingAddress)&&void 0!==t&&t.country&&null!==(a=this.props.assistantDetails)&&void 0!==a&&null!==(i=a.billingAddress)&&void 0!==i&&i.state?W<H?(0,w.jsxs)(n.Z,{variant:"body2",children:["Minimum purchase of ","USD"===U?"$30":"\u20b91500"," ","AI credits is required"]}):"":(0,w.jsx)(p.Z,{href:"/projects/".concat(this.props.match.params.projectId,"/manage/billings"),color:"primary",size:"small",children:(0,w.jsx)(n.Z,{variant:"body2",children:"Add billing address first \u2192"})}),children:(0,w.jsx)("div",{children:(0,w.jsx)(c.Z,{fullWidth:!0,variant:"contained",className:N.confirmButton,style:{background:W<H||null===(x=this.props.assistantDetails)||void 0===x||null===(f=x.billingAddress)||void 0===f||!f.country||null===(A=this.props.assistantDetails)||void 0===A||null===(S=A.billingAddress)||void 0===S||!S.state?"#0000001f":"#42B864",color:W<H||null===(C=this.props.assistantDetails)||void 0===C||null===(k=C.billingAddress)||void 0===k||!k.country||null===(Z=this.props.assistantDetails)||void 0===Z||null===(T=Z.billingAddress)||void 0===T||!T.state?"#00000042":"white"},disabled:W<H||!(null!==(D=this.props.assistantDetails)&&void 0!==D&&null!==(P=D.billingAddress)&&void 0!==P&&P.country)||!(null!==(B=this.props.assistantDetails)&&void 0!==B&&null!==(E=B.billingAddress)&&void 0!==E&&E.state),onClick:()=>{this.props.isFromAdsMediaSection&&this.props.closeDialog&&this.props.closeDialog(),"INR"==U?this.createOrderOneTimeOnRazorpay():(0,b.wP)({assistantId:_,currency:U,amount:W,showSnackbar:M,onSuccess:()=>{const e={type:"AI-CREDIT",process:"purchase",amount:W};this.props.updateAssistantStore({ongoingBillingProcess:e}),I.Z.post(j.URL+"/payment/update-ongoing-process",{ongoingBillingProcess:e,assistantId:_}).then((e=>{localStorage.setItem("creditInCache",W)}))},onClose:R})},children:(0,w.jsx)("div",{children:(0,w.jsx)("h4",{style:{margin:0,fontWeight:300},children:"Purchase AI Credits"})})})})})})})]}),(0,w.jsxs)(u.Z,{open:this.state.wccPaymentDialog,onClose:this.toggleFormOpen,style:{width:O?"320":"500"},fullScreen:!!O,disableBackdropClick:!0,children:[(0,w.jsx)(h.Z,{style:{paddingRight:"0px",paddingTop:"0px",paddingBottom:"0px"},children:(0,w.jsx)(l.Z,{style:{display:"flex",alignItems:"center",float:"right"},children:(0,w.jsx)(m.Z,{onClick:()=>this.setState({wccPaymentDialog:!this.state.wccPaymentDialog}),className:N.formCloseButton,children:(0,w.jsx)(y.Z,{})})})}),(0,w.jsx)(g.Z,{className:N.formDialog,children:(0,w.jsx)("iframe",{src:this.state.planPaymentUrl,width:O?"312":"372",he
2ight:O?"609":"700"})})]})]})}}const Z=(0,A.connect)((e=>({assistantDetails:e.assistantDetails.data,login:e.login.user})),{updateAssistantStore:S.sJ})(k),T=(0,x.Z)((e=>({root:{width:"100%"},formDialog:{paddingLeft:"0px",paddingRight:"0px",paddingTop:"0px",paddingBottom:"0px"},confirmButton:{padding:"6px 12px",color:"white",width:"100%",fontWeight:"bold",fontSize:"14px",marginTop:8,background:"#42B864","&:hover":{background:"#42B864"}}})))((0,f.withRouter)(Z))},5975:(e,t,a)=>{a.r(t),a.d(t,{default:()=>B});var i=a(47313),s=a(83061),n=a(73908),o=a(57009),r=a(54070),l=a(52376),d=a(65681),c=(a(24841),a(56569),a(68914),a(72728)),p=a(84747),u=a(21144),h=a(34882),m=a(20337),g=a(11652),x=a(61809),v=a(95939),y=a(78371),f=a(88012),A=a(63830),b=a(45788),S=a(58889),I=a(81766),j=a(70089),C=a(1805),w=(a(59017),a(46417));class k extends i.Component{constructor(e){super(e),this.updateAmount=e=>{this.setState({amount:e.target.value.replace(/[^0-9]+/,"")})},this.purchaseViaRazorpay=()=>{this.setState({isMacLoading:!0});const{assistantId:e,currency:t,assistantName:a,billingAddress:i}=this.props.assistantDetails,{name:s,email:n,contact:o,id:r}=this.props.login,l=this.state.amount,d={assistantId:e,currency:t,clientId:r,name:(null===i||void 0===i?void 0:i.first_name)+(null!==i&&void 0!==i&&i.last_name?" ".concat(null===i||void 0===i?void 0:i.last_name):"")||s,email:(null===i||void 0===i?void 0:i.email)||n,contact:(null===i||void 0===i?void 0:i.phone)||o,amount:l,assistantName:a};j.Z.post(C.URL+"/payment/meta-ads-credit-via-razorpay",d).then((e=>{this.setState({isMacLoading:!1});const t=e.data.ongoingBillingProcess;window.open(e.data.createLink.short_url,"_blank"),this.props.updateAssistantStore({ongoingBillingProcess:t}),this.props.closeDialog()})).catch((e=>{this.setState({isMacLoading:!1}),this.props.showSnackbar({alertOpen:!0,alertMsg:"Failed to Collect Payment",severity:"error"})}))},this.zohoPlan=async()=>{let{partnerId:e,subscriptionId:t,placeOfSupply:a,planDuration:i,temporarySubs:s,partner:n}=this.props.assistantDetails;const{amount:o}=this.state,{assistantId:r,clientId:l,currency:d}=this.props.assistantDetails;(i&&i<15||null!==n&&void 0!==n&&n.isZohoEnabled&&!t)&&(t=s.subForCredit);const c={partnerId:e,amount:o,subscriptionId:t,assistantId:r,placeOfSupply:a,clientId:l,currency:d};await j.Z.post(C.URL+"/payment/create/wcc-checkout-url",c).then((e=>{this.setState({planPaymentUrl:e.data.paymentPage},(()=>{this.setState({wccPaymentDialog:!0})}))})).catch((e=>{var t,a,i,s;this.props.showSnackbar({alertOpen:!0,alertMsg:["NONE","None"].includes(null===(t=this.props.assistantDetails)||void 0===t?void 0:t.activePlan)||null===(a=this.props.assistantDetails)||void 0===a||!a.activePlan?"Buy a plan first":(null===e||void 0===e||null===(i=e.response)||void 0===i||null===(s=i.data)||void 0===s?void 0:s.message)||"Something went wrong",severity:"error"})}))},this.state={amount:1500,wccPaymentDialog:!1,planPaymentUrl:"",isMacLoading:!1}}componentDidMount(){const{currency:e}=this.props.assistantDetails;this.setState({amount:"USD"===e?30:1500});const t=document.createElement("script");return t.src="https://checkout.razorpay.com/v1/checkout.js",t.async=!0,document.body.appendChild(t),()=>{document.body.removeChild(t)}}render(){var e,t,a,i,s,l,A,b,I,j,C,k,Z,T,D,P;const{classes:B,match:E,assistantDetails:N,showSnackbar:L,closeDialog:F,updateAssistantStore:M}=this.props,R=window.innerWidth<767,{currency:O,metaAdsCredit:U,pendingInvoices:z,partnerId:_,prospectId:W}=N,{amount:H}=(E.params.projectId,this.state),G="INR"==O?1500:30;return(0,w.jsxs)("div",{className:B.root,children:[(0,w.jsxs)(n.Z,{border:"1px solid lightgrey",p:3,borderRadius:8,children:[(0,w.jsx)(o.Z,{variant:"h4",children:"Enter Amount"}),(0,w.jsx)(o.Z,{variant:"body2",color:"textSecondary",style:{padding:"8px 0"},children:"Minimum purchase of ".concat("USD"===O?"$30":"\u20b91500"," credits is allowed")}),(0,w.jsx)(c.Z,{fullWidth:!0,placeholder:"Enter credit amount here",value:H,type:"number",onChange:this.updateAmount,InputProps:{startAdornment:(0,w.jsx)(p.Z,{position:"start",children:"USD"===O?"$"
2:"\u20b9"})}}),U<0&&(0,w.jsx)(o.Z,{variant:"body2",color:"error",style:{margin:"8px 0 0px 4px"},children:"Purchase credit higher then due amount to resume services."}),(0,w.jsxs)(u.Z,{container:!0,style:{marginTop:12},children:[localStorage.getItem("creditInCache")&&(0,w.jsx)(h.ZP,{title:"Repeat previous recharge",children:(0,w.jsx)(m.Z,{style:{border:"1px solid #0a474c",color:"#0a474c",marginRight:8,marginBottom:8},variant:"outlined",color:"blue",onClick:()=>{const e=localStorage.getItem("creditInCache");this.setState({amount:Number(e)})},startIcon:(0,w.jsx)(f.Z,{style:{fontSize:16}}),children:localStorage.getItem("creditInCache")})}),(0,w.jsxs)(m.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+2500/("USD"==O?100:1)})},children:["+",2500/("USD"==O?100:1)]}),(0,w.jsxs)(m.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+5e3/("USD"==O?100:1)})},children:["+",5e3/("USD"==O?100:1)]}),(0,w.jsxs)(m.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+1e4/("USD"==O?100:1)})},children:["+",1e4/("USD"==O?100:1)]}),(0,w.jsxs)(m.Z,{style:{marginRight:8,marginBottom:8},variant:"outlined",onClick:()=>{this.setState({amount:Number(this.state.amount)+5e4/("USD"==O?100:1)})},children:["+",5e4/("USD"==O?100:1)]})]}),(0,w.jsx)(u.Z,{container:!0,style:{display:"flex",flexDirection:"INR"!==this.props.assistantDetails.currency?"row-reverse":"inherit",justifyContent:"INR"!==this.props.assistantDetails.currency?"flex-end":"flex-start",gap:"14px"},children:(0,w.jsx)(u.Z,{item:!0,md:12,children:(0,w.jsx)(h.ZP,{interactive:!0,title:null!==(e=this.props.assistantDetails)&&void 0!==e&&null!==(t=e.billingAddress)&&void 0!==t&&t.country&&null!==(a=this.props.assistantDetails)&&void 0!==a&&null!==(i=a.billingAddress)&&void 0!==i&&i.state?H<G?(0,w.jsxs)(o.Z,{variant:"body2",children:["Minimum purchase of ","USD"===O?"$30":"\u20b91500"," ","credits is allowed"]}):"":(0,w.jsx)(g.Z,{href:"/projects/".concat(this.props.match.params.projectId,"/manage/billings"),color:"primary",size:"small",children:(0,w.jsx)(o.Z,{variant:"body2",children:"Add billing address first \u2192"})}),children:(0,w.jsx)("div",{children:(0,w.jsx)(m.Z,{fullWidth:!0,variant:"contained",className:B.confirmButton,style:{background:H<G||null===(s=this.props.assistantDetails)||void 0===s||null===(l=s.billingAddress)||void 0===l||!l.country||null===(A=this.props.assistantDetails)||void 0===A||null===(b=A.billingAddress)||void 0===b||!b.state?"#0000001f":"#42B864",color:H<G||null===(I=this.props.assistantDetails)||void 0===I||null===(j=I.billingAddress)||void 0===j||!j.country||null===(C=this.props.assistantDetails)||void 0===C||null===(k=C.billingAddress)||void 0===k||!k.state?"#00000042":"white"},disabled:H<G||!(null!==(Z=this.props.assistantDetails)&&void 0!==Z&&null!==(T=Z.billingAddress)&&void 0!==T&&T.country)||!(null!==(D=this.props.assistantDetails)&&void 0!==D&&null!==(P=D.billingAddress)&&void 0!==P&&P.state),onClick:()=>{"INR"===O&&this.setState({isMacLoading:!0}),(0,S.fu)({amount:H,assistantDetails:this.props.assistantDetails,login:this.props.login,updateAssistantStore:this.props.updateAssistantStore,showSnackbar:L,onClose:F,onCreateOrderError:()=>this.setState({isMacLoading:!1}),onPaymentSettled:()=>this.setState({isWccLoading:!1}),onDismiss:()=>this.setState({isWccLoading:!1})})},children:(0,w.jsx)("div",{children:(0,w.jsx)("h4",{style:{margin:0,fontWeight:300},children:"Purchase Now"})})})})})})})]}),(0,w.jsxs)(x.Z,{open:this.state.wccPaymentDialog,onClose:this.toggleFormOpen,style:{width:R?"320":"500"},fullScreen:!!R,disableBackdropClick:!0,children:[(0,w.jsx)(v.Z,{style:{paddingRight:"0px",paddingTop:"0px",paddingBottom:"0px"},children:(0,w.jsx)(u.Z,{style:{display:"flex",alignItems:"center",float:"right"},children:(0,w.jsx)(r.Z,{onClick:()=>this.setState({wccPaymentDialog:!this.state.wccPaymentDialog}),className:B.formCloseButton,children:(0,w.jsx)(d.Z,{})})})}),(0,w.jsx)(y.Z,{className:B.formDialog,children:(0,w.jsx)("iframe",{src:this.state.planPaymentUrl,width:R?"312":"372",he
2ight:R?"609":"700"})})]})]})}}const Z=(0,b.connect)((e=>({assistantDetails:e.assistantDetails.data,login:e.login.user})),{syncBillingAddress:I.L8,updateAssistantStore:I.sJ})(k),T=(0,l.Z)((e=>({root:{width:"100%"},formDialog:{paddingLeft:"0px",paddingRight:"0px",paddingTop:"0px",paddingBottom:"0px"},confirmButton:{padding:"6px 12px",color:"white",width:"100%",fontWeight:"bold",fontSize:"14px",marginTop:8,background:"#42B864","&:hover":{background:"#42B864"}}})))((0,A.withRouter)(Z));var D=a(9841);class P extends i.Component{constructor(e){super(e),this.onSnackbarClose=()=>{this.setState({alertOpen:!1})},this.showSnackbar=e=>{this.setState(e)},this.closeOpenDialog=()=>{this.setState({openDialog:!1}),setTimeout((()=>{this.props.toggleTemplateCreditDialog()}),400)},this.state={openDialog:!1,alertOpen:!1,alertMsg:"",severity:""}}componentDidUpdate(e){!e.dialogOpen&&this.props.dialogOpen&&setTimeout((()=>{this.setState({openDialog:!0})}),0)}render(){const{classes:e,dialogOpen:t,assistantDetails:a}=this.props,{openDialog:i}=this.state;return(0,w.jsxs)("div",{className:e.root,children:[t&&(0,w.jsx)(n.Z,{className:e.backdrop,children:(0,w.jsx)(n.Z,{className:(0,s.Z)(e.dialogContainer,{[e.dialogContainerSlider]:i}),children:(0,w.jsxs)(n.Z,{className:e.dialogWrapper,children:[(0,w.jsx)(n.Z,{className:e.dialogTitle,children:(0,w.jsxs)(n.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[(0,w.jsx)(o.Z,{variant:"h4",children:"Purchase AiSensy Ads Credits"}),(0,w.jsx)(r.Z,{onClick:this.closeOpenDialog,children:(0,w.jsx)(d.Z,{})})]})}),(0,w.jsx)(n.Z,{style:{padding:"0px 24px",paddingTop:"12px"},children:(0,w.jsxs)(o.Z,{variant:"h6",style:{fontSize:"12px"},children:["These Ad credits can be utilized to create and run ads only from AiSensy's Ads Manager.",(0,w.jsx)("br",{}),"These Ads are run on facebook & instagram and land on whatsapp."]})}),(0,w.jsx)(n.Z,{className:e.dialogContent,children:(0,w.jsx)(T,{showSnackbar:this.showSnackbar,closeDialog:this.closeOpenDialog})})]})})}),(0,w.jsx)(D.A9,{open:this.state.alertOpen,anchorOrigin:{vertical:"top",horizontal:"center"},onClose:this.onSnackbarClose,severity:this.state.severity,message:this.state.alertMsg})]})}}const B=(0,l.Z)((e=>({root:{width:"100%"},snackbar:{zIndex:5e3},backdrop:{position:"fixed",width:"100%",top:0,left:0,height:"100vh",background:"#0000005e",display:"flex",flexDirection:"row-reverse",zIndex:1e3},dialogContainerSlider:{[e.breakpoints.down("md")]:{margin:"0 !important"},[e.breakpoints.up("md")]:{margin:"0 !important"}},dialogContainer:{padding:12,boxSizing:"border-box",transition:"margin 0.45s",maxWidth:600,[e.breakpoints.down("md")]:{width:"100%",margin:"0 -100% 0 0"},[e.breakpoints.up("md")]:{width:"50%",margin:"0 -50% 0 0"}},dialogWrapper:{height:"100%",borderRadius:"12px",background:"white",overflow:"scroll"},dialogTitle:{padding:"12px 12px 8px 24px",boxShadow:"0px 4px 8px #f3efef"},dialogContent:{padding:"24px 16px",background:"#f9f8f873",maxHeight:"calc(100vh - 140px)",overflowY:"auto"}})))(P)},29206:(e,t,a)=>{a.r(t),a.d(t,{CreateAds:()=>Ai,CreateAdsClass:()=>Ai,default:()=>Si});var i=a(70089),s=a(16031),n=a.n(s),o=a(45788),r=a(47313),l=a(63830),d=a(81463),c=a(87105),p=a(79880),u=a(82162),h=a(32724),m=a(5733),g=a(26670),x=a(88012),v=a(65681),y=a(49324),f=a(21144),A=a(73908),b=a(54070),S=a(11652),I=a(57009),j=a(34882),C=a(90431),w=a(20337),k=a(3873),Z=a(61809),T=a(95939),D=a(78371),P=a(38390),B=a(35154),E=a(66842),N=a(52376),L=a(72728),F=a(34960),M=a(91734),R=a(85616),O=a(16577),U=a(50835),z=a(74227),_=a.n(z),W=a(1805),H=a(5975),G=a(81601),V=a(39867),Q=a(92324),q=a(26395),Y=a(98677),K=a(46417);const J=(e,t)=>{const{changeState:a,classes:i,parentState:s}=e,[n,o]=(0,r.useState)(s.selectedCells),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(!1),[m,g]=(0,r.useState)(!1),[x,v]=(0,r.useState)(new Set);(0,r.useEffect)((()=>{a("selectedCells",n)}),[n]),(0,r.useEffect)((()=>{if(l&&c){const e=new Set(n),[t,i]=[Math.min(l.row,c.row),Math.max(l.row,c.row)],[s,o]=[Math.min(l.col,c.col),Math.max(l.col,c.col)];for(let a=t;a<=i;a++)for(let t=s;t<=o;t++){const i=y(a,t);m&&e.has(i)?e.delete(i):m||e.add(i)}const r=A(e);a("selectedSlotsCount",r)}}),[l,c]),(0,r.useImperativeHandle)(t,(()=>({clearAllSchedule:f})));const y=(e,t)=>"".concat(e,"-").concat(t),f=()=>{o(new Set)},A=e=>{let t=0;for(let a of e)"7"!==a[0]&&t++;return t},b=(e,t)=>{h(!0),e<=7&&(d({row:e,col:t}),p({row:e,col:t}),g(n.has(y(e,t))),v(new Set(n))),7===e&&(I(t),g(n.has(y(e,t))),d({row:0,col:t}),p({row:6,col:t}))},S=e=>{if(u&&l&&c){for(let t=0;t<7;t++){const[a,i]=[Math.min(l.row,c.row),Math.max(l.row,c.row)],[s,o]=[Math.min(l.col,c.col),Math.max(l.col,c.col)],r=t>=a&&t<=i&&e>=s&&e<=o;if(m&&r)return!1;if(!n.has(y(t,e))&&!r)return!1}return!0}for(let t=0;t<7;t++)if(!n.has(y(t,e)))return!1;return!0},I=e=>{o((t=>{const a=new Set(t),i=S(e);for(let s=0;s<7;s++){const t=y(s,e);i?a.delete(t):a.add(t)}return a}))},C=(e,t)=>{u&&l&&p({row:e,col:t})},w=()=>
2{if(l&&c){const e=new Set(n),[t,a]=[Math.min(l.row,c.row),Math.max(l.row,c.row)],[i,s]=[Math.min(l.col,c.col),Math.max(l.col,c.col)];for(let n=t;n<=a;n++)for(let t=i;t<=s;t++)if(7===n){for(let a=0;a<7;a++){const i=y(a,t);m?e.delete(i):e.add(i)}m?e.delete(y(7,t)):e.add(y(7,t))}else{const a=y(n,t);m?e.delete(a):e.add(a)}for(let n=0;n<24;n++)Array.from({length:7}).every(((t,a)=>e.has(y(a,n))))?e.add(y(7,n)):e.delete(y(7,n));o(e)}h(!1),d(null),p(null),v(new Set)},k=(e,t)=>{o((a=>{const i=y(e,t),s=new Set(a);return s.has(i)?s.delete(i):s.add(i),s}))},Z=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return(0,K.jsxs)("div",{style:{display:"flex",flexDirection:"row",gap:"8px"},children:[(0,K.jsxs)("div",{style:{display:"flex",flexDirection:"column",paddingTop:"20px",gap:"4px",position:"sticky",left:0,zIndex:1,paddingLeft:"20px",paddingRight:"5px",background:"#F9F9FB"},children:[Z.map((e=>(0,K.jsx)("div",{style:{height:"45px",paddingRight:"5px",fontSize:"12px",display:"flex",alignItems:"center",justifyContent:"flex-end",fontFamily:"Inter",fontWeight:600,lineHeight:"100%",fontFamily:"Inter, sans-serif"},children:e},e))),(0,K.jsx)("div",{style:{height:"45px",fontSize:"12px",display:"flex",alignItems:"center",justifyContent:"flex-end",marginTop:"4px",fontFamily:"Inter",fontWeight:600,lineHeight:"100%",fontFamily:"Inter, sans-serif",whiteSpace:"nowrap"},children:"Every day"})]}),(0,K.jsxs)("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",gap:"4px"},children:[(0,K.jsx)("div",{style:{display:"flex",gap:"6px",marginBottom:"4px"},children:Array.from({length:8}).map(((e,t)=>{const a=3*t%12||12,i=t>=4?"pm":"am";return(0,K.jsx)("div",{style:{width:"102px",color:"#1c1e21",fontSize:"12px",fontFamily:"Inter",fontWeight:400,lineHeight:"100%",fontFamily:"Inter, sans-serif"},children:"".concat(a," ").concat(i)},t)}))}),(0,K.jsx)("div",{style:{display:"flex",flexDirection:"column",width:"fit-content",gap:"4px"},onMouseUp:w,onMouseLeave:w,children:Array.from({length:7}).map(((e,t)=>(0,K.jsx)("div",{className:i.outerRow,children:Array.from({length:8}).map(((e,a)=>(0,K.jsx)("div",{className:i.outerCol,children:Array.from({length:3}).map(((e,s)=>{const o=3*a+s;let r=((e,t)=>{if(7===e)return Array.from({length:7}).every(((e,a)=>n.has(y(a,t))));if(!u||!l||!c)return n.has(y(e,t));const[a,i]=[Math.min(l.row,c.row),Math.max(l.row,c.row)],[s,o]=[Math.min(l.col,c.col),Math.max(l.col,c.col)],r=e>=a&&e<=i&&t>=s&&t<=o;return m?!r&&x.has(y(e,t)):!!r||x.has(y(e,t))})(t,o);const d=o%12||12,p=o>=12?"PM":"AM";return(0,K.jsx)(j.ZP,{title:"".concat(Z[t],", ").concat(d," ").concat(p),placement:"top",children:(0,K.jsx)("div",{className:i.innerCell,style:{backgroundColor:r?"#3C777C":"#E8E8ED"},onMouseDown:()=>b(t,o),onMouseMove:()=>C(t,o)})},s)}))},a)))},t)))}),(0,K.jsx)("div",{className:i.outerRow,onMouseUp:w,style:{marginTop:"8px"},children:Array.from({length:8}).map(((e,t)=>(0,K.jsx)("div",{className:i.outerCol,children:Array.from({length:3}).map(((e,a)=>{const s=3*t+a;let o=S(s);(o&&!n.has(y(7,s))||!o&&n.has(y(7,s)))&&k(7,s);const r=s%12||12,l=s>=12?"PM":"AM";return(0,K.jsx)(j.ZP,{title:"Every day, ".concat(r," ").concat(l),placement:"top",children:(0,K.jsx)("div",{className:i.innerCell,style:{backgroundColor:o?"#3C777C":"#E8E8ED"},onMouseDown:()=>b(7,s),onMouseMove:()=>C(7,s)})},a)}))},t)))})]})]})},X=(0,r.forwardRef)(J);class $ extends r.Component{constructor(e){var t,a;super(e),this.isEditAd=window.location.pathname.includes("edit")&&this.props.parentState.isLiveAD,this.timezoneOptions=[{label:"Use Viewer's time zone",value:"viewer"},{label:"Use this ad account's time zone",value:"ad_account"}],this.budgetOptions=[{label:"Lifetime Budget",value:"lifetime_budget"},{label:"Daily Budget",value:"daily_budget"}],this.isDuplicateAd=window.location.pathname.includes("duplicate"),this.isCreateAdPage=window.location.pathname.includes("create"),this.toggleTemplateCreditDialog=()=>{this.setState({templatedialogOpen:!this.state.templatedialogOpen})},this.toggleScheduledAd=()=>{"lifetime_budget"===this.props.parentState.selectedBudget.value&&this.props.changeState("isScheduledAd",!this.props.parentState.isScheduledAd)},this.getMinToDate=()=>{const{parentState:e}=this.props,t=e.adStatus,a=_()().startOf("day"),i=_()().startOf("day").add(1,"days"),s=_()(e.fromDate).startOf("day"),n=_()(e.toDate).startOf("day");_()(e.adjusttedOriginalEndDate).startOf("day");if(this.isCreateAdPage)return _()(e.fromDate).add(2,"days").toDate();if("DRAFT"===t)return a.isAfter(s)&&a.diff(n,"days")<=2?_()(a).add(2,"days").toDate():_()(s).add(2,"days").toDate();if(n.diff(s,"days")<=2)return _()(e.fromDate).add(2,"days").toDate();const o=s.add(2,"days").startOf("day");return o.isBefore(i)?i.toDate():o.toDate()},this.hasInSufficientCredits=()=>{const{selectedBudget:e,dailyBudget:t,lifetimeBudget:a}=this.props.parentState,{metaAdsCredit:i}=this.props.assistantDetails||{};return"daily_budget"===e.value?t&&+i-2*t<0:a&&+i-a<0},this.getMinBudget=()=>{var e;const{selectedBudget:t}=this.props.parentState,{assistantDetails:a,adAccountData:i}=this.props,{currency:s}=a||{},{currency:n}=i||{},o="INR"===((null===a||void 0===a||null===(e=a.adSetupDetails)||void 0===e?void 0:e.selectedMetaAdAccountId)==(null===i||void 0===i?void 0:i.accountId)?s:n);return"lifetime_budget"===(null===t||void 0===t?void 0:t.value)?o?2500:25:o?250:5},this.isBudgetBelowMinimum=()=>{const{selectedBudget:e,dailyBudget:t,lifetimeBudget:a}=this.props.parentState,i="lifetime_budget"===(null===e||void 0===e?void 0:e.value)?a:t;return Boolean(i)&&+i<this.getMinBudget()},this.CheckIcon=()=>(0,K.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,K.jsx)("circle",{cx:"8",cy:"8",r:"8",f
2ill:"#48465D"}),(0,K.jsx)("rect",{width:"9.14286",height:"9.14286",transform:"translate(3.42969 3.42871)",fill:"#48465D"}),(0,K.jsx)("path",{d:"M11.1823 5.72716C11.1383 5.68272 11.0858 5.64745 11.0281 5.62338C10.9703 5.59931 10.9083 5.58691 10.8457 5.58691C10.7831 5.58691 10.7212 5.59931 10.6634 5.62338C10.6056 5.64745 10.5532 5.68272 10.5091 5.72716L6.97697 9.26403L5.493 7.77532C5.44724 7.73111 5.39322 7.69635 5.33402 7.67302C5.27483 7.6497 5.21162 7.63826 5.148 7.63936C5.08438 7.64046 5.02161 7.65408 4.96325 7.67944C4.9049 7.7048 4.85211 7.74141 4.80791 7.78717C4.7637 7.83293 4.72894 7.88695 4.70562 7.94615C4.68229 8.00534 4.67085 8.06855 4.67195 8.13217C4.67305 8.19579 4.68667 8.25856 4.71203 8.31692C4.73739 8.37527 4.774 8.42806 4.81976 8.47226L6.64035 10.2928C6.68442 10.3373 6.73686 10.3726 6.79464 10.3966C6.85241 10.4207 6.91438 10.4331 6.97697 10.4331C7.03956 10.4331 7.10153 10.4207 7.1593 10.3966C7.21708 10.3726 7.26951 10.3373 7.31359 10.2928L11.1823 6.4241C11.2305 6.3797 11.2689 6.32582 11.2951 6.26584C11.3214 6.20587 11.335 6.1411 11.335 6.07563C11.335 6.01015 11.3214 5.94539 11.2951 5.88541C11.2689 5.82544 11.2305 5.77155 11.1823 5.72716Z",fill:"white"})]}),this.getSelectedSlotsCount=()=>{let e=0;for(let t of this.props.parentState.selectedCells)"7"!==t[0]&&e++;return e},this.state={currency:(null===(t=this.props)||void 0===t||null===(a=t.adAccountData)||void 0===a?void 0:a.currency)||"INR",templatedialogOpen:!1,isBudgetDropdownOpen:!1},this.schedulerRef=r.createRef()}componentDidMount(){const e=this.getSelectedSlotsCount();this.setState({selectedCount:e})}validateTimeSlotsAgainstDateRange(){var e;const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=null===(e=this.props.parentState.adAccountData)||void 0===e?void 0:e.timezone,{fromDate:i,toDate:s,selectedCells:n,startDateError:o,endDateError:r}=this.props.parentState;if(o)return{invalidSlots:[""],message:"Invalid Ad Start Date"};if(r)return{invalidSlots:[""],message:"Invalid Ad End Date"};if(!s)return{invalidSlots:[]};const l=new Set;let d=_().tz(i,a).startOf("day");const c=_().tz(s,a).endOf("day");if(c.diff(d,"days")>=6)return{invalidSlots:[]};for(;d.isSameOrBefore(c);)l.add(d.day()),d.add(1,"day");const p=[],u=new Set;for(const h of n){const[e]=h.split("-");if("7"===e)continue;const t=parseInt(e,10);l.has(t)||(p.push(h),u.add(t))}if(p.length>0){const e=[...u].map((e=>t[e])).join(", "),s=[];for(d=_().tz(i,a);d.isSameOrBefore(c);)s.push(t[d.day()]),d.add(1,"day");const n=[...new Set(s)],o=1===n.length?n[0]:"".concat(n[0]," to ").concat(n[n.length-1]);return{invalidSlots:p,message:"You have scheduled this ad set to run on ".concat(e,". But the selected date range only includes ").concat(o,". Please change your date range or schedule.")}}return{invalidSlots:[]}}render(){var e,t;const{classes:a,assistantDetails:i,adAccountData:s,agent:n,parentState:o,isLiveAD:l}=this.props,{power:d}=n,{currency:c}=s||{},{metaAdsCredit:p,ongoingBillingProcess:u,cbpType:h,allowPurchase:m,pendingInvoices:g,partnerId:x,currency:v}=i||{},y=(null===i||void 0===i||null===(e=i.adSetupDetails)||void 0===e?void 0:e.selectedMetaAdAccountId)==(null===s||void 0===s?void 0:s.accountId)?v:c,{dailyBudget:b,lifetimeBudget:S,duration:C,isEndDate:k,toDate:Z,fromDate:T,keyThird:D,selectedBudget:P,isScheduledAd:B,originalDuration:E,adEffectiveStatus:N}=o,{invalidSlots:R,message:O}=this.validateTimeSlotsAgainstDateRange();return(0,K.jsxs)(f.Z,{container:!0,style:{display:"flex"},children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,md:12,style:{display:"flex",flexDirection:"column",justifyContent:"center",marginBottom:"20px"},children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,style:{marginBottom:"2em"},children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Select per day budget"}),(0,K.jsx)(A.Z,{position:"relative",children:(0,K.jsx)(q.ZP,{disableClearable:!0,options:this.budgetOptions,onOpen:()=>{this.isEditAd||this.setState({isBudgetDropdownOpen:!0})},onClose:()=>{this.setState({isBudgetDropdownOpen:!1})},open:this.state.isBudgetDropdownOpen,onChange:(e,t)=>
2{"daily_budget"===t.value&&(this.props.changeState("isScheduledAd",!1),b||this.props.changeState("dailyBudget","INR"===y?500:5)),"lifetime_budget"===t.value&&(this.props.changeState("isEndDate",!0),S||this.props.changeState("lifetimeBudget","INR"===y?2500:25)),this.props.changeState("selectedBudget",t)},getOptionLabel:e=>null!==e&&void 0!==e&&e.label?e.label:"",value:this.props.parentState.selectedBudget,name:"budgetType",renderInput:e=>{var t;return(0,K.jsx)(L.Z,{...e,placeholder:"Type",variant:"outlined",classes:{root:a.codeTextFieldRoot},style:{width:"150px",paddingLeft:"10px",backgroundColor:"#E9E9E9",paddingTop:"1px",borderTopRightRadius:0,borderBottomRightRadius:0,paddingRight:"5px","& .MuiAutocomplete-popupIndicator":{borderRadius:"4px"}},InputProps:{...e.InputProps,endAdornment:this.isEditAd?null:e.InputProps.endAdornment},value:null===(t=this.props.parentState.selectedBudget)||void 0===t?void 0:t.label})}})}),(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:a.TextFieldRoot},style:{paddingLeft:"80px"},onChange:e=>{let t=e.target.value;""!==t?(t=t.replace(/[^0-9]/g,""),t=t.replace(/^0+(?=\d)/,""),"lifetime_budget"===(null===P||void 0===P?void 0:P.value)?this.props.changeState("lifetimeBudget",t):this.props.changeState("dailyBudget",t)):"lifetime_budget"===(null===P||void 0===P?void 0:P.value)?this.props.changeState("lifetimeBudget",t):this.props.changeState("dailyBudget",t)},error:this.isBudgetBelowMinimum(),value:"lifetime_budget"===(null===P||void 0===P?void 0:P.value)?S||"":b||"",placeholder:"lifetime_budget"===(null===P||void 0===P?void 0:P.value)?"USD"===y?"$25":"\u20b92500":"USD"===y?"$5":"\u20b9500",name:"budget",type:"number"}),this.isBudgetBelowMinimum()&&(0,K.jsx)(I.Z,{variant:"body2",style:{color:"#f44336",marginTop:"6px"},children:"Minimum ".concat("lifetime_budget"===(null===P||void 0===P?void 0:P.value)?"lifetime":"daily"," budget is ").concat("USD"===y?"$":"\u20b9").concat(this.getMinBudget().toLocaleString())})]}),(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Select Advertisement Duration"}),(0,K.jsx)(f.Z,{style:{display:"flex",flexDirection:"column",marginTop:"0.6em",marginBottom:"30px"},children:(0,K.jsxs)(f.Z,{container:!0,spacing:2,style:{display:"flex"},children:[(0,K.jsx)(G.M,{utils:Q.Z,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,md:6,children:[(0,K.jsx)(f.Z,{style:{display:"flex",alignItems:"center",height:"42px"},children:(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,style:{color:"#000000",marginTop:"8px"},children:"Select Start Date"})}),(0,K.jsx)(V.e,{style:{marginTop:"0px",width:"100%"},className:a.paddingControl,disableToolbar:!0,minDate:l&&!this.isDuplicateAd?T:new Date,minDateMessage:"The date cannot be earlier than today",maxDate:new Date((new Date).setDate((new Date).getDate()+60)),format:"dd/MM/yyyy",margin:"normal",id:"date-picker-inline",disabled:l&&!this.isDuplicateAd,value:T,onChange:this.props.handleFromDateChange,KeyboardButtonProps:{"aria-label":"change date"},onError:e=>{this.props.parentState.startDateError!==e&&this.props.changeState("startDateError",e)}}),l&&!this.isDuplicateAd&&(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,className:a.helperText,children:"You cannot edit the start date of published AD"})]})}),(0,K.jsx)(G.M,{utils:Q.Z,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,md:6,children:[(0,K.jsxs)(f.Z,{style:{display:"flex",alignItems:"center",height:"42px"},children:["daily_budget"===P.value&&(0,K.jsx)(F.Z,{color:"primary",style:{paddingLeft:0},checked:k,onChange:(e,t)=>
2{this.props.changeState("isEndDate",t)}}),"daily_budget"===P.value&&(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,style:{color:"#000000",marginTop:"8px"},children:"Select End Date"})]}),k&&(0,K.jsx)(V.e,{style:{marginTop:"0px",width:"100%"},className:a.paddingControl,disableToolbar:!0,minDate:this.getMinToDate(),minDateMessage:"The date cannot be earlier than ".concat(_()(this.getMinToDate()).format("DD/MM/YYYY")),format:"dd/MM/yyyy",margin:"normal",id:"date-picker-inline",value:Z,onError:e=>{this.props.parentState.endDateError!==e&&this.props.changeState("endDateError",e)},onChange:this.props.handleToDateChange,KeyboardButtonProps:{"aria-label":"change date"}})]})})]})})]}),(0,K.jsx)(f.Z,{item:!0,xs:12,children:(0,K.jsxs)(A.Z,{style:{display:"flex",flexDirection:"column"},children:[(0,K.jsxs)(A.Z,{style:{backgroundColor:"#F0F0F0",paddingLeft:"20px",borderRadius:"8px",borderTopRightRadius:"12px",borderBottomRightRadius:"12px",display:"flex",alignItems:"center",gap:"16px",marginBottom:"10px",justifyContent:"space-between",height:"60px",boxSizing:"border-box"},children:[(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"16px"},children:[(0,K.jsx)(j.ZP,{title:"lifetime_budget"!==P.value?"Ad scheduling is only available when you use lifetime budget":"",placement:"top",children:(0,K.jsx)("span",{style:{display:"inline-flex"},children:(0,K.jsx)(ae,{checked:B,onChange:this.toggleScheduledAd})})}),(0,K.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",flexDirection:"column",justifyContent:"center",gap:"4px"},children:[(0,K.jsx)(I.Z,{style:{fontFamily:"Inter",fontWeight:500,fontSize:"14px",lineHeight:"140%",color:"#24232F",letterSpacing:0},children:"Run Ads on a Custom Schedule"}),(0,K.jsx)(I.Z,{style:{fontFamily:"Inter",fontWeight:400,fontSize:"10px",lineHeight:"100%",letterSpacing:0,color:"#48465D"},children:"Select when your ads should run during the week. Click and drag to select time blocks."})]})]}),(0,K.jsx)(j.ZP,{title:"lifetime_budget"!==(null===P||void 0===P?void 0:P.value)?"Ad scheduling is only available when you use lifetime budget":"",placement:"top",children:(0,K.jsx)(q.ZP,{className:a.displayNone_1200,value:this.props.parentState.selectedTimezone,onChange:(e,t)=>
2{this.props.changeState("selectedTimezone",t)},disabled:"lifetime_budget"!==P.value,options:this.timezoneOptions,getOptionLabel:e=>e.label,popupIcon:(0,K.jsx)(ie,{}),disableClearable:!0,style:{height:"100%"},PopperComponent:te,ListboxProps:{style:{padding:0,margin:0},className:a.noHoverBg},renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",InputProps:{...e.InputProps,style:{height:"100%",fontSize:"14px",fontWeight:500,lineHeight:"140%",fontFamily:"Inter",color:"#48465D"}},style:{width:"250px",height:"100%",paddingTop:0,paddingBottom:0,background:"#E9E9E9",borderBottomLeftRadius:0,borderTopLeftRadius:0,paddingRight:0,paddingLeft:"5.5px","& .MuiOutlinedInput-root":{"& fieldset":{border:"none"},"&:hover fieldset":{border:"none"},"&.Mui-focused fieldset":{border:"none"},height:"100%",borderRadius:"0px"},"& .MuiInputBase-input":{height:"100%",padding:"8px"}}}),renderOption:(e,t)=>(console.log(t,e),(0,r.createElement)(A.Z,{component:"li",...e,key:e.value,style:{display:"flex",alignItems:"center",padding:0,height:"36px",margin:0,width:"400px"}},(0,K.jsx)(M.Z,{checked:this.props.parentState.selectedTimezone.value===e.value,color:"primary",value:this.props.parentState.selectedTimezone,tabIndex:-1,size:"small",style:{marginRight:"8px",marginTop:0,padding:0}}),(0,K.jsx)(I.Z,{style:{padding:0,margin:0},children:e.label})))})})]}),B&&(0,K.jsx)(q.ZP,{className:a.display_1200,disableClearable:!0,autoHighlight:!0,options:this.timezoneOptions,getOptionLabel:e=>e.label,onChange:(e,t)=>
2{this.props.changeState("selectedTimezone",t)},value:this.props.parentState.selectedTimezone,renderInput:e=>{var t;return(0,K.jsx)(L.Z,{...e,variant:"outlined",classes:{root:a.textFieldRoot},InputProps:{...e.InputProps},placeholder:"Select Timezone",name:"timezone",value:null===(t=this.props.parentState.selectedTimezone)||void 0===t?void 0:t.label})},classes:{inputRoot:a.inputRoot}}),B&&(0,K.jsx)(A.Z,{style:{display:"flex",flexDirection:"column"},children:(0,K.jsx)(A.Z,{className:a.schedulerOuterDiv,children:(0,K.jsx)(A.Z,{className:a.schedulerInnerDiv,style:{display:"flex"},children:(0,K.jsx)(X,{parentState:this.props.parentState,changeState:this.props.changeState,classes:a,ref:this.schedulerRef})})})})]})}),(0,K.jsx)(f.Z,{item:!0,xs:12,style:{marginTop:"19px"},children:(0,K.jsxs)(A.Z,{className:a.adBudgetFooter,children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"flex-start",flexDirection:"column"},children:[(0,K.jsx)(I.Z,{variant:"h5",children:"".concat(k?"Total Estimated":"Daily"," Budget : ").concat("USD"===y?"$":"\u20b9"," ").concat(("daily_budget"===P.value?k?b*C||0:b||0:S||0).toLocaleString())}),k&&(0,K.jsxs)(I.Z,{variant:"body2",gutterBottom:!0,className:a.helperText,style:{marginBottom:"0"},children:["Estimated Budget From"," ",_()(T).isBefore(_()())?_()().format("DD/MM/YYYY"):_()(T).format("DD/MM/YYYY")," ","to ",_()(Z).format("DD/MM/YYYY")]})]}),B&&(0,K.jsxs)(A.Z,{className:a.timeSlotCountDiv,children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)(this.CheckIcon,{}),(0,K.jsxs)(I.Z,{style:{fontFamily:"Inter",fontWeight:500,fontSize:"14px",lineHeight:"140%",marginLeft:"8px",color:"#24232F"},children:[this.props.parentState.selectedSlotsCount," Time slots selected"]})]}),(0,K.jsx)(I.Z,{style:{fontFamily:"Inter",fontWeight:600,fontSize:"16px",lineHeight:"140%",color:"#0A474C",marginLeft:"25px",cursor:"pointer"},onClick:()=>{var e;this.props.changeState("selectedCells",new Set),this.props.changeState("selectedSlotsCount",0),null===(e=this.schedulerRef.current)||void 0===e||e.clearAllSchedule()},children:"Clear All"})]})]})}),"lifetime_budget"===(null===(t=this.props.parentState)||void 0===t?void 0:t.selectedBudget.value)&&B&&R.length>0&&(0,K.jsxs)(f.Z,{item:!0,xs:12,style:{marginTop:"20px",backgroundColor:"#FFE5E6",color:"#EC0004",display:"flex",padding:"20px",paddingLeft:"24px",gap:"8px",borderRadius:"8px",alignItems:"flex-start"},children:[(0,K.jsx)(ee,{}),(0,K.jsx)(I.Z,{style:{fontFamily:"Inter",fontWeight:500,fontSize:"14px",lineHeight:"140%",marginTop:"-2px"},children:O})]}),(0,K.jsxs)(A.Z,{style:{gap:"10px",display:"flex",flexDirection:"column",marginTop:"20px"},children:[this.hasInSufficientCredits()&&"You don't have sufficient credit to run this ad. Add more credit to run this ad",this.hasInSufficientCredits()&&d>=2&&!x&&("ENTERPRISE"!==h||m)&&(0,K.jsx)(w.Z,{onClick:()=>{this.toggleTemplateCreditDialog()},variant:"outlined",color:"primary",style:{padding:"4px 10px",fontSize:"0.8125rem"},children:"Buy Credits"})]})]}),(0,K.jsx)(H.default,{dialogOpen:this.state.templatedialogOpen,toggleTemplateCreditDialog:this.toggleTemplateCreditDialog,assistantDetails:this.props.assistantDetails})]},D)}}const ee=()=>(0,K.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,K.jsx)("g",{"clip-path":"url(#clip0_652_5104)",children:(0,K.jsx)("path",{d:"M8 16C12.418 16 16 12.418 16 8C16 3.582 12.418 0 8 0C3.582 0 0 3.582 0 8C0 12.418 3.582 16 8 16ZM9 9C9 9.26522 8.89464 9.51957 8.70711 9.70711C8.51957 9.89464 8.26522 10 8 10C7.73478 10 7.48043 9.89464 7.29289 9.70711C7.10536 9.51957 7 9.26522 7 9V4C7 3.73478 7.10536 3.48043 7.29289 3.29289C7.48043 3.10536 7.73478 3 8 3C8.26522 3 8.51957 3.10536 8.70711 3.29289C8.89464 3.48043 9 3.73478 9 4V9ZM8 10.984C8.13135 10.984 8.26142 11.0099 8.38276 11.0602C8.5041 11.1105 8.61435 11.1842 8.70721 11.2771C8.80007 11.37 8.87372 11.4803 8.92396 11.6017C8.97419 11.7231 9.00003 11.8531 9 11.9845C8.99997 12.1159 8.97406 12.2459 8.92377 12.3673C8.87347 12.4886 8.79976 12.5989 8.70686 12.6917C8.61395 12.7846 8.50367 12.8582 8.3823 12.9085C8.26093 12.9587 8.13085 12.9845 7.9995 12.9845C7.73422 12.9844 7.47983 12.879 7.29229 12.6914C7.10475 12.5037 6.99943 12.2493 6.9995 11.984C6.99957 11.7187 7.10501 11.4643 7.29264 11.2768C7.48027 11.0893 7.73472 10.9839 8 10.984Z",fill:"#EC0004"})}),(0,K.jsx)("defs",{children:(0,K.jsx)("clipPath",{id:"clip0_652_5104",children:(0,K.jsx)("rect",{width:"16",height:"16",fill:"white"})})})]});function te(e){return(0,K.jsx)(R.Z,{...e,style:{width:398,zIndex:1300},placement:"bottom-end"})}const ae=(0,O.Z)((e=>(0,K.jsx)(C.Z,{focusVisibleClassName:".Mui-focusVisible",disableRipple:!0,...e})))((e=>{let{theme:t}=e;
2return{width:42,height:26,padding:0,"& .MuiSwitch-switchBase":{padding:0,margin:2,transitionDuration:"300ms","&.Mui-checked":{transform:"translateX(16px)",color:"#fff","& + .MuiSwitch-track":{backgroundColor:"#65C466",opacity:1,border:0},"&.Mui-disabled + .MuiSwitch-track":{backgroundColor:"#B5E0B5",opacity:.5}},"&.Mui-focusVisible .MuiSwitch-thumb":{color:"#33cf4d",border:"6px solid #fff"},"&.Mui-disabled .MuiSwitch-thumb":{color:t.palette.grey[300]},"&.Mui-disabled + .MuiSwitch-track":{backgroundColor:t.palette.grey[300],opacity:1}},"& .MuiSwitch-thumb":{boxSizing:"border-box",width:22,height:22},"& .MuiSwitch-track":{borderRadius:13,backgroundColor:"#78788029",opacity:1,transition:t.transitions.create(["background-color"],{duration:500})}}}));function ie(e){return(0,K.jsx)(U.Z,{...e,viewBox:"0 0 25 24",children:(0,K.jsx)("path",{d:"M17.4662 9.51758L12.5007 14.4831L7.53516 9.51758",stroke:"#48465D",strokeWidth:"1.5",strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})})}const se=(0,o.connect)((e=>({assistantDetails:e.assistantDetails.data,agent:e.login.user})),{})($),ne=(0,N.Z)((e=>({root:{width:"100%",padding:"20px 10px"},bottomMargin:{marginBottom:e.spacing(4)},filterTypeContainer:{borderRadius:"5px",minHeight:100},inputPadding:{padding:"12px 10px"},inputRoot:{'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-input':{padding:12},'&&[class*="MuiOutlinedInput-root"]':{padding:0}},snackbar:{zIndex:5e3},codeTextFieldRoot:{width:"60px",height:"43px",padding:"0 0 0 30px",position:"absolute",zIndex:1,margin:"5px 0 0 0px","& .MuiAutocomplete-popupIndicator":{backgroundColor:"#E9E9E9",borderTopRightRadius:0,borderBottomRightRadius:0,"&:hover":{backgroundColor:"#E9E9E9"}},"& input":{padding:"12px 0 !important"},"& button":{width:"12px",position:"relative",left:"7px",background:"rgb(240,240,240)",borderRadius:0,"&:hover":{background:"rgb(240,240,240)"}},"& div":{paddingRight:"0px !important"}},ad:{display:"flex",marginTop:"1.35em",marginBottom:"2em",justifyContent:"center",[e.breakpoints.up("md")]:{minWidth:"315px"}},TextFieldRoot:{width:"100%",padding:"2px 20px",marginTop:"4px","& input":{width:"calc(100% - 80px)",marginLeft:"80px"},background:"rgb(240,240,240)"},paddingControl:{"& .MuiIconButton-root":{padding:0},"& .MuiFormHelperText-root":{position:"absolute !important",top:"42px !important"}},helperText:{color:"#000000",fontSize:"11px",marginBottom:"30px"},inputRoot:{'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-input':{padding:12},'&&[class*="MuiOutlinedInput-root"]':{padding:0},'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-inputRoot':{paddingRight:"0 !important",paddingLeft:"0 !important"}},textFieldRoot:{backgroundColor:"rgb(240,240,240)",outline:"none",border:"none",borderRadius:"8px",width:"100%",padding:"0",boxShadow:"none",boxSizing:"border-box",fontFamily:"Roboto, sans-serif",fontSize:"15px",fontWeight:500,maxHeight:"12em",overflow:"auto","&::-webkit-scrollbar":{width:"4px"}},outerRow:{display:"flex",gap:"6px","&:last-child":{borderBottom:"none"}},outerCol:{display:"flex",height:"45px",width:"102px",justifyContent:"space-between",position:"relative",gap:"6px",boxSizing:"border-box"},innerCell:{height:"100%",width:"100%",background:"#eaf4fe",display:"flex",justifyContent:"space-between",alignItems:"center",position:"relative",borderRadius:"4px",boxSizing:"border-box","&:hover":{background:"#9cd5e5"}},indicator:{position:"absolute",width:"3px",height:"100%",backgroundColor:"#39afd5",borderRadius:"3px"},schedulerOuterDiv:{backgroundColor:"#F9F9FB",marginTop:"16px",borderRadius:"12px",overflowX:"hidden",paddingTop:"20px",paddingBottom:"20px",paddingRight:"20px",[e.breakpoints.down(1600)]:{overflowX:"scroll"}},schedulerInnerDiv:{maxWidth:"100%",justifyContent:"center",[e.breakpoints.down(1600)]:{maxWidth:"52vw",justifyContent:"normal"},[e.breakpoints.down(1300)]:{maxWidth:"43vw",justifyContent:"normal"}},displayNone_1200:{display:"flex",[e.breakpoints.down(1200)]:{display:"none"}},display_1200:{display:"none",[e.breakpoints.down(1200)]:{display:"flex"}},adBudgetFooter:{display:"flex",justifyContent:"space-between",alignItems:"center",flexDirection:"row",width:"100%",flexWrap:"wrap-reverse"}
2,timeSlotCountDiv:{display:"flex",alignItems:"center",justifyContent:"flex-end",[e.breakpoints.down(1100)]:{justifyContent:"space-between",width:"100%",marginBottom:"20px"}},noHoverBg:{"& .MuiAutocomplete-option[aria-selected='true']":{backgroundColor:"transparent !important"}}})))(se);var oe=a(47735),re=a(31385),le=a(45282),de=a(14636),ce=a(94459),pe=a(56165),ue=a(47537),he=a(47495),me=a(95538),ge=a(58849);const xe=(0,ge.Z)("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),ve=(0,ge.Z)("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);var ye=a(16362),fe=a(22877),Ae=a(88045),be=a(81766),Se=a(97241),Ie=a(5088),je=a(16757),Ce=a(84747),we=a(6885);const ke=(0,ge.Z)("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),Ze=(0,ge.Z)("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]),Te=(0,ge.Z)("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]),De=(0,ge.Z)("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]]),Pe=(0,ge.Z)("Ratio",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);var Be=a(61316);const Ee=(0,ge.Z)("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),Ne=(0,ge.Z)("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);var Le=a(19700);const Fe=(0,ge.Z)("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]),Me=(0,ge.Z)("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);var Re=a(9475),Oe=a(46952),Ue=a(22752),ze=a(39648),_e=a(76317),We=a(77736),He=a(83766),Ge=a(85839),Ve=a(75875),Qe=a(39745),qe=a(73069);const Ye=(0,ge.Z)("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]),Ke=(0,ge.Z)("Aperture",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14.31 8 5.74 9.94",key:"1y6ab4"}],["path",{d:"M9.69 8h11.48",key:"1wxppr"}],["path",{d:"m7.38 12 5.74-9.94",key:"1grp0k"}],["path",{d:"M9.69 16 3.95 6.06",key:"libnyf"}],["path",{d:"M14.31 16H2.83",key:"x5fava"}],["path",{d:"m16.62 12-5.74 9.94",key:"1vwawt"}]]),Je=(0,ge.Z)("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",ke
2y:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]),Xe=(0,ge.Z)("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]),$e=(0,ge.Z)("Origami",[["path",{d:"M12 12V4a1 1 0 0 1 1-1h6.297a1 1 0 0 1 .651 1.759l-4.696 4.025",key:"1bx4vc"}],["path",{d:"m12 21-7.414-7.414A2 2 0 0 1 4 12.172V6.415a1.002 1.002 0 0 1 1.707-.707L20 20.009",key:"1h3km6"}],["path",{d:"m12.214 3.381 8.414 14.966a1 1 0 0 1-.167 1.199l-1.168 1.163a1 1 0 0 1-.706.291H6.351a1 1 0 0 1-.625-.219L3.25 18.8a1 1 0 0 1 .631-1.781l4.165.027",key:"1hj4wg"}]]);var et=a(93927);const tt=(0,Se.Z)((e=>({promptContainer:{padding:e.spacing(2),borderBottom:"1px solid ".concat(e.palette.divider),transition:"all 0.2s ease",backgroundColor:e.palette.background.paper,"&:hover":{backgroundColor:"#f8f9fa"},"&:last-child":{borderBottom:"none"}},promptContent:{flex:1,minWidth:0,paddingRight:e.spacing(1)},iconButtonContainer:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:e.spacing(1),minWidth:"fit-content"}}))),at=e=>{var t,a;let{prompt:i,imageCount:s=0,styleType:n,aspectRatio:o,styles:r=[],mainResolutions:l=[],children:d,mediaType:c="image"}=e;const p=tt(),u=(0,re.Z)();return(0,K.jsxs)(A.Z,{className:p.promptContainer,children:[(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"16px"},children:[(0,K.jsxs)(A.Z,{className:p.promptContent,children:[(0,K.jsx)(I.Z,{variant:"body2",style:{marginBottom:"8px",fontWeight:500,fontSize:"14px",lineHeight:"20px",color:"#333"},children:i.length>120?i.slice(0,120)+"...":i}),(0,K.jsxs)(I.Z,{variant:"caption",style:{color:"#666",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[(e=>{switch(e){case"AUTO":return(0,K.jsx)(qe.Z,{size:14,color:"#404040",style:{verticalAlign:"middle"}});case"GENERAL":return(0,K.jsx)(Ye,{size:14,color:"#404040",style:{verticalAlign:"middle"}});case"REALISTIC":return(0,K.jsx)(Ke,{size:14,color:"#404040",style:{verticalAlign:"middle"}});case"DESIGN":return(0,K.jsx)(Je,{size:14,color:"#404040",style:{verticalAlign:"middle"}});case"RENDER_3D":return(0,K.jsx)(Xe,{size:14,color:"#404040",style:{verticalAlign:"middle"}});default:return(0,K.jsx)($e,{size:14,color:"#404040",style:{verticalAlign:"middle"}})}})(n)," ",null===(t=r.find((e=>e.value===n)))||void 0===t?void 0:t.label," ","\u2022"," ",o?null===(a=l.find((e=>e.value===o)))||void 0===a?void 0:a.label:""]})]}),(0,K.jsxs)(A.Z,{className:p.iconButtonContainer,children:[(0,K.jsx)(w.Z,{size:"small",onClick:e=>{e.stopPropagation(),navigator.clipboard.writeText(i).then((()=>{})).catch((()=>{const e=document.createElement("textarea");e.value=i,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}))},style:{display:"flex",alignItems:"center",gap:"4px",minWidth:"auto"},children:(0,K.jsx)(et.Z,{size:14})}),(0,K.jsx)(I.Z,{variant:"caption",style:{color:"#666",fontSize:"12px",whiteSpace:"nowrap"},children:s>0?"".concat(s," ").concat("video"===c?"Video":"Image").concat(1!==s?"s":""):"No ".concat("video"===c?"videos":"images"," available")})]})]}),s>0&&(0,K.jsx)(A.Z,{style:{marginTop:u.spacing(2)},children:d})]})},it=(0,Se.Z)((e=>({historyImagePreviewContainer:{marginTop:0},imageContainer:{position:"relative",overflow:"hidden",borderRadius:"8px",display:"flex",flexDirection:"column",alignItems:"center",flex:"1 1 0",minWidth:"120px",maxWidth:"calc(33.333% - 8px)",[e.breakpoints.down("sm")]:{minWidth:"100px",maxWidth:"calc(50% - 6px)"}},imageWrapper:{position:"relative",width:"100%",height:"200px",borderRadius:"8px",overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f8f9fa",padding:"0px",boxSizing:"border-box"},image:{width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",objectFit:"contain",display:"block"},actionButtons:{position:"absolute",top:"4px",right:"4px",display:"flex",gap:"4px",opacity:.9,transition:"opacity 0.2s ease",zIndex:15,pointerEvents:"auto"},actionButton:{backgroundColor:"rgba(255, 255, 255, 0.95)",color:"#0a474c",width:"36px",height:"36px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",zIndex:20,pointerEvents:"auto","&:hover":{backgroundColor:"rgba(255, 255, 255, 1)",boxShadow:"0 4px 12px rgba(0,0,0,0.2)"}},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"8px",display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"transparent",transition:"background-color 0.2s ease",pointerEvents:"none",zIndex:5},mobileImageContainer:{position:"relative",borderRadius:"8px",width:"100%",height:"auto",overflow:"hidden",border:"1px solid #E8E8E8",backgroundColor:"#f8f9fa",display:"flex",justifyContent:"center",alignItems:"center",padding:"0px",boxSizing:"border-box"},mobileImage:{width:"100%",height:"auto",maxWidth:"100%",maxHeight:"400px",objectFit:"contain",display:"block"},mobileActionButtons:{position:"absolute",top:"4px",right:"4px",display:"flex",gap:"4px",opacity:.9,zIndex:15,pointerEvents:"auto"},selectedOverlay:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#258d3b1A",border:"2px s
2olid #0a474c",borderRadius:"6px",pointerEvents:"none"},desktopGrid:{display:"flex",gap:"12px",paddingTop:"8px",justifyContent:"flex-start",alignItems:"flex-start",flexWrap:"nowrap",width:"100%",overflowX:"auto",minHeight:"220px","&::-webkit-scrollbar":{height:"4px"},"&::-webkit-scrollbar-track":{backgroundColor:"#f1f1f1",borderRadius:"2px"},"&::-webkit-scrollbar-thumb":{backgroundColor:"#c1c1c1",borderRadius:"2px","&:hover":{backgroundColor:"#a8a8a8"}}},mobileCarouselContainer:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:"12px"}}))),st=e=>{let{images:t,promptId:a,onImageSelect:i,onImageModalOpen:s,onDownload:n,selectedIndex:o,onSelectedIndexChange:r,onHistoryDrawerToggle:l,prompt:d,timestamp:c,onPromptCopy:p,styleType:u,aspectRatio:h,styles:m=[],mainResolutions:g=[]}=e;const x=it(),v=((0,re.Z)(),(e,t)=>{e.preventDefault(),e.stopPropagation(),t()}),y=e=>{e.currentTarget.style.opacity=1},f=e=>{e.currentTarget.style.opacity=0},S=e=>{const t=e.currentTarget.querySelector("button");t&&(t.style.opacity=1),e.currentTarget.style.backgroundColor="#258d3b1A"},I=e=>{const t=e.currentTarget.querySelector("button");t&&(t.style.opacity=0),e.currentTarget.style.backgroundColor="transparent"},j=t&&t.length>0?t[0].type:"image";return t&&0!==t.length?(0,K.jsx)(at,{prompt:d,imageCount:(null===t||void 0===t?void 0:t.length)||0,styleType:u,aspectRatio:h,styles:m,mainResolutions:g,mediaType:j,children:window.innerWidth>426?(0,K.jsx)(A.Z,{className:x.desktopGrid,children:t.map(((e,a)=>(0,K.jsx)(A.Z,{className:x.imageContainer,children:(0,K.jsxs)(A.Z,{className:x.imageWrapper,children:["video"===e.type?(0,K.jsx)("video",{src:e.url,poster:e.thumbnail,className:x.image,muted:!0,controls:!0}):(0,K.jsx)("img",{src:e.url,alt:"Generated ".concat(e.type," ").concat(a+1),className:x.image}),"video"===e.type&&(0,K.jsx)(A.Z,{style:{position:"absolute",top:"8px",right:"8px",backgroundColor:"rgba(0, 0, 0, 0.7)",borderRadius:"4px",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10},children:(0,K.jsx)(ve,{size:16,color:"white"})}),(0,K.jsxs)(A.Z,{className:x.actionButtons,onMouseEnter:y,onMouseLeave:f,children:[(0,K.jsx)(b.Z,{size:"small",onClick:i=>v(i,(()=>{s(e.url,e.fileName||"Generated ".concat("video"===e.type?"Video":"Image"," ").concat(a+1),a,t.map((e=>e.url)))})),onMouseDown:e=>{e.stopPropagation()},className:x.actionButton,children:(0,K.jsx)(Fe,{size:16})}),(0,K.jsx)(b.Z,{size:"small",onClick:t=>v(t,(()=>{const t="video"===e.type?".mp4":".jpg",i="video"===e.type?"generated-video-".concat(a+1).concat(t):"generated-image-".concat(a+1).concat(t);n(e.url,i)})),onMouseDown:e=>{e.stopPropagation()},className:x.actionButton,children:(0,K.jsx)(Me,{size:16})})]}),(0,K.jsx)(A.Z,{className:x.overlay,onMouseEnter:S,onMouseLeave:I,children:(0,K.jsx)(w.Z,{variant:"contained",className:x.selectedButton,style:{opacity:0,transition:"opacity 0.2s",backgroundColor:"#0a474c",color:"white",fontWeight:500,padding:"8px 16px",borderRadius:"6px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",zIndex:25,pointerEvents:"auto"},onClick:()=>((e,t)=>{r(null),console.log("History drawer media selected:",e),i(e.url,e.type,e.thumbnail),l()})(e),children:"video"===e.type?"Use Video":"Use Image"})})]})},a)))}):(0,K.jsx)(Qe.Z,{slides:t.map(((e,a)=>(0,K.jsx)(A.Z,{className:x.mobileCarouselContainer,children:(0,K.jsxs)(A.Z,{className:x.mobileImageContainer,children:["video"===e.type?(0,K.jsx)("video",{src:e.url,poster:e.thumbnail,className:x.mobileImage,muted:!0,controls:!0}):(0,K.jsx)("img",{src:e.url,alt:"Generated ".concat(e.type," ").concat(a+1),className:x.mobileImage}),"video"===e.type&&(0,K.jsx)(A.Z,{style:{position:"absolute",top:"8px",right:"8px",backgroundColor:"rgba(0, 0, 0, 0.7)",borderRadius:"4px",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10},children:(0,K.jsx)(ve,{size:16,color:"white"})}),(0,K.jsxs)(A.Z,{className:x.mobileActionButtons,children:[(0,K.jsx)(b.Z,{size:"small",onClick:i=>v(i,(()=>{s(e.url,e.fileName||"Generated ".concat("video"===e.type?"Video":"Image"," ").concat(a+1),a,t.map((e=>e.url)))})),onMouseDown:e=>{e.stopPropagation()},className:x.actionButton,children:(0,K.jsx)(Fe,{size:16})}),(0,K.jsx)(b.Z,{size:"small",onClick:t=>v(t,(()=>{const t="video"===e.type?".mp4":".jpg",i="video"===e.type?"generated-video-".concat(a+1).concat(t):"generated-image-".concat(a+1).concat(t);n(e.url,i)})),onMouseDown:e=>{e.stopPropagation()},className:x.actionButton,children:(0,K.jsx)(Me,{size:16})})]}),(0,K.jsx)(w.Z,{variant:"contained",className:x.selectedButton,onClick:()=>((e,t)=>{r(null),console.log("Mobile history drawer media selected:",e),i(e.url,e.type,e.thumbnail),l()})(e),style:{position:"absolute",bottom:"12px",left:"50%",transform:"translateX(-50%)",opacity:.9,backgroundColor:"#0a474c",color:"white",fontWeight:500,padding:"8px 16px",borderRadius:"6px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:o===a?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ve.Z,{size:16,style:{marginRight:"8px"}}),"Selected"]}):"video"===e.type?"Use Video":"Use Image"})]})},a))),updateCurrentSlide:()=>{}})}):(0,K.jsx)(at,{prompt:d,imageCount:0,styleType:u,aspectRatio:h,styles:m,mainResolutions:g,mediaType:j})},nt=(0,Se.Z)((e=>({circularProgressContainer:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:5,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},circularProgressWrapper:{position:"relative",display:"inline-flex"},progressText:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"12px",fontWeight:600,color:e.palette.primary.main}}))),ot=e=>{let{progress:t=0}=e;const a=nt();return(0,K.jsx)(A.Z,{className:a.circularProgressContainer,children:(0,K.jsxs)(A.Z,{className:a.circularProgressWrapper,children:[(0,K.jsx)(k.Z,{variant:"determinate",value:t,size:60,thickness:4}),(0,K.jsxs)(I.Z,{className:a.progressText,children:[Math.round(t),"%"]})]})})};var rt=a(85497),lt=a.n(rt),dt=a(89434),ct=a(12599),pt=a(49998),ut=a(18845),ht=a(9841),mt=a(74813),gt=(a(7913),a(40480));const xt=async(e,t)=>{const a={...t,credentials:"include"};let i=await lt()(e,a);if(!i.ok&&401===i.status)try{await(0,mt.mt)(),i=await lt()(e,a)}catch(s){throw new Error("Authentication failed. Please try again.")}if(!i.ok){const e=await i.text();throw new Error("".concat(e))}return i},vt=[{value:"AUTO",label:"Auto"},{value:"GENERAL",label:"General"},{value:"REALISTIC",label:"Realistic"},{value:"DESIGN",label:"Design"},{value:"RENDER_3D",label:"3D Render"}],yt=[{value:"ASPECT_1_1",label:"1:1"},{value:"ASPECT_2_3",label:"2:3"},{value:"ASPECT_3_2",label:"3:2"},{value:"ASPECT_3_4",label:"3:4"},{value:"ASPECT_4_3",label:"4:3"},{value:"ASPECT_9_16",label:"9:16"},{value:"ASPECT_16_9",label:"16:9"}],ft=(0,Se.Z)((e=>({container:{backgroundColor:e.palette.background.paper,backdropFilter:"blur(8px)"},headerContainer:{marginBottom:e.spacing(3),display:"flex",alignItems:"flex-start",ga
2p:e.spacing(2),flexDirection:"column"},headerBadge:{borderRadius:"8px",padding:e.spacing(.75,1),display:"flex",alignItems:"center",gap:e.spacing(.5),flexWrap:"wrap"},sparklesIcon:{padding:e.spacing(.75,1),alignItems:"center",gap:e.spacing(.5),flexWrap:"wrap"},headerIcon:{color:e.palette.primary.main,animation:"pulse 2s infinite"},headerText:{fontSize:"0.875rem",fontWeight:600,color:e.palette.text.primary,paddingLeft:e.spacing(.5)},descriptionText:{color:e.palette.text.secondary},toggleContainer:{backgroundColor:"#f0f0f0",display:"flex",borderRadius:"8px",padding:"4px",width:"fit-content",minWidth:"200px",marginBottom:e.spacing(2)},toggleButton:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:e.spacing(.2),padding:e.spacing(.5,.5),borderRadius:"8px",border:"none",backgroundColor:"transparent",color:e.palette.text.secondary,fontSize:"0.7rem",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease"},toggleButtonActive:{backgroundColor:"white",color:"black",borderRadius:"8px",transition:"all 0.2s ease"},tabContent:{marginTop:e.spacing(1.5)},templateButton:{width:"100%",justifyContent:"flex-start",gap:e.spacing(.75),borderRadius:"8px",border:"1px solid ".concat(e.palette.divider),backgroundColor:e.palette.background.paper,padding:e.spacing(2),fontSize:"0.875rem",fontWeight:500,transition:"all 0.2s",marginBottom:e.spacing(1)},historyButton:{alignSelf:"flex-end",marginBottom:e.spacing(1),minWidth:"120px",height:"40px",fontSize:"0.875rem",fontWeight:500,borderRadius:"8px",backgroundColor:e.palette.background.paper,padding:e.spacing(1,2),transition:"all 0.2s","&:hover":{borderColor:e.palette.primary.main,backgroundColor:e.palette.primary.light+"10"}},dialogTitle:{display:"flex",alignItems:"center",gap:e.spacing(.8)},templateGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))",gap:e.spacing(2),marginTop:e.spacing(2),alignItems:"start"},templateCard:{position:"relative",overflow:"hidden",borderRadius:"12px",border:"1px solid ".concat(e.palette.divider),backgroundColor:e.palette.background.paper,transition:"all 0.2s"},templateImage:{aspectRatio:"16/9",width:"100%",overflow:"hidden"},templateImageContent:{height:"100%",width:"100%",objectFit:"cover",transition:"transform 0.3s"},templateInfo:{padding:e.spacing(1)},templateTitle:{fontSize:"0.875rem",fontWeight:600,color:e.palette.text.primary},templateDescription:{marginTop:e.spacing(.5),fontSize:"0.8rem",color:e.palette.text.secondary,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},promptField:{minHeight:"120px",marginTop:e.spacing(2),marginBottom:e.spacing(1.5),backgroundColor:e.palette.background.paper,borderRadius:"8px",border:"1px solid ".concat(e.palette.divider)},controlsContainer:{display:"flex",gap:e.spacing(.3),flexWrap:"wrap",alignItems:"flex-start",marginTop:e.spacing(1.5),justifyContent:"flex-start",width:"100%",maxWidth:"100%",overflow:"hidden",boxSizing:"border-box","& > *":{flex:"0 0 auto",minWidth:"70px",maxWidth:"100%",height:"auto",display:"flex",alignItems:"center",boxSizing:"border-box"},[e.breakpoints.down("lg")]:{gap:e.spacing(.6),"& > *":{minWidth:"65px",maxWidth:"100%"}},[e.breakpoints.down("md")]:{gap:e.spacing(.5),justifyContent:"flex-start","& > *":{minWidth:"60px",maxWidth:"100%"}},[e.breakpoints.down("sm")]:{flexDirection:"column",alignItems:"stretch",gap:e.spacing(1.5),"& > *":{width:"100%",minWidth:"unset",maxWidth:"100%",height:"auto",flex:"none"}}},mediaButton:{display:"flex",alignItems:"center",justifyContent:"center",gap:e.spacing(.5),borderRadius:"8px",border:"1px dashed ".concat(e.palette.divider),backgroundColor:e.palette.background.paper,padding:e.spacing(2.5,2),transition:"all 0.2s",whiteSpace:"nowrap",fontSize:"0.8rem",minHeight:"40px",height:"40px",minWidth:"100px","&:hover":{borderColor:e.palette.primary.main,backgroundColor:e.palette.primary.light+"10"}},formControl:{display:"flex",flexDirection:"row",alignItems:"center",gap:e.spacing(.2),border:"1px solid ".concat(e.palette.divider),borderRadius:"8px",minWidth:"12px",padding:e.spacing(.6),cursor:"pointer",transition:"all 0.2s ease-in-out","&:hover":{backgroundColor:"#f8f9fa",borderColor:e.palette.primary.main},[e.breakpoints.down("sm")]:{width:"90% !important",minWidth:"unset !important",maxWidth:"100% !important",justifyContent:"space-between",padding:e.spacing(1),flex:"1 1 auto !important"},"& .MuiInputLabel-root":{fontSize:"0.75rem",color:e.palette.text.secondary,transform:"translate(14px, 9px) scale(1)","&.Mu
2iInputLabel-shrink":{transform:"translate(14px, -9px) scale(0.75)"}},"& .MuiSelect-root":{paddingRight:"27px !important",border:"none",outline:"none","&:before":{borderBottom:"none"},"&:after":{borderBottom:"none"},"&:hover:not(.Mui-disabled):before":{borderBottom:"none"},"& .MuiSelect-select":{paddingRight:"0px !important",padding:e.spacing(.5),minHeight:"auto"}},"& .MuiSelect-icon":{right:"8px",width:"16px",display:"none"},"& .MuiSelect-select":{paddingRight:"32px !important"}},mobileFormControl:{[e.breakpoints.down("sm")]:{flex:"1 1 auto",width:"90% !important",minWidth:"unset !important",maxWidth:"100% !important",paddingTop:"13px !important",paddingBottom:"13px !important"}},videoMobileFormControl:{[e.breakpoints.down("sm")]:{flex:"1 1 auto",width:"93% !important",minWidth:"unset !important",maxWidth:"100% !important",paddingTop:"13px !important",paddingBottom:"13px !important"}},iconButton:{width:"24px",height:"24px",padding:0,marginRight:e.spacing(1),flex:"0 0 auto",borderRadius:"6px","& svg":{width:"16px",height:"16px"},[e.breakpoints.down("sm")]:{marginRight:e.spacing(.5)}},aspectRatioBox:{borderRadius:"6px",backgroundColor:"transparent"},filePreviews:{display:"flex",flexWrap:"wrap",gap:e.spacing(1),marginTop:e.spacing(2),alignItems:"center",width:"100%",clear:"both"},generateButton:{width:"100%",gap:e.spacing(.75),cursor:"pointer",borderRadius:"8px",padding:e.spacing(1,2),fontSize:"0.875rem",fontWeight:500,backgroundColor:e.palette.primary.main,marginTop:e.spacing(2),color:"white",position:"relative",overflow:"hidden",height:"40px","&::before":{content:'""',position:"absolute",top:0,left:"-100%",width:"100%",height:"100%",background:"linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent)",animation:"shimmer 3s infinite"},"&:hover":{backgroundColor:e.palette.primary.main,color:"white"},"&:disabled":{backgroundColor:e.palette.primary.main,color:"white",boxShadow:"none"}},"@keyframes shimmer":{"0%":{left:"-100%"},"100%":{left:"100%"}},videoOverlay:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.2)"},videoIcon:{borderRadius:"50%",backgroundColor:e.palette.primary.main,padding:e.spacing(1.5),transition:"transform 0.2s"},mediaLibraryDialog:{padding:0,height:"80vh"},"@keyframes pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.5}},"@keyframes blink":{"0%, 50%, 100%":{opacity:1},"25%, 75%":{opacity:0}},historyDrawer:{"& .MuiDrawer-paper":{width:"400px",maxWidth:"90vw"}},historyDrawerHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:e.spacing(2),borderBottom:"1px solid ".concat(e.palette.divider)},historyDrawerContent:{padding:e.spacing(2),height:"100%",overflow:"auto"},historySearchBar:{marginBottom:e.spacing(2)},historyItem:{padding:e.spacing(2),border:"1px solid ".concat(e.palette.divider),borderRadius:"8px",marginBottom:e.spacing(1),cursor:"pointer",transition:"all 0.2s"},historyItemTitle:{fontWeight:600,marginBottom:e.spacing(.5)},historyItemDescription:{color:e.palette.text.secondary,fontSize:"0.875rem"},historyItemDate:{color:e.palette.text.hint,fontSize:"0.75rem",marginTop:e.spacing(.5)},customCtaInput:{marginTop:e.spacing(2),backgroundColor:e.palette.background.paper,borderRadius:"8px",border:"1px solid ".concat(e.palette.divider)},manualUploadContainer:{marginTop:e.spacing(3)},mediaUrlField:{marginBottom:e.spacing(2),display:"flex",gap:e.spacing(1),alignItems:"center",backgroundColor:"white",[e.breakpoints.down("sm")]:{flexDirection:"column",alignItems:"stretch",gap:e.spacing(1.5)}},mediaUrlFieldBox:{width:"100%",padding:"2px",marginTop:"4px","& input":{width:"calc(100% - 80px)"},background:"rgb(240,240,240)"},orDivider:{display:"flex",alignItems:"center",margin:e.spacing(2,0),"&::before, &::after":{content:'""',flex:1,height:"1px",backgroundColor:e.palette.divider},"&::before":{marginRight:e.spacing(2)},"&::after":{marginLeft:e.spacing(2)}},mediaUrlFieldText:{fontSize:"0.8rem",fontWeight:400,color:e.palette.text.primary,[e.breakpoints.down("sm")]:{textAlign:"center",margin:e.spacing(.5,0)}},"@keyframes spin":{"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}},"@keyframes pulse":{"0%, 100%":{opacity:1,transform:"scale(1)"},"50%":{opacity:.5,transform:"scale(0.8)"}},"@keyframes sparkle":{"0%":{opacity:1,transform:"scale(1) rotate(0deg)",filter:"brightness(1)"},"25%":{opacity:.9,transform:"scale(1.1) rotate(90deg)",filter:"brightness(1.2)"},"50%":{opacity:.7,transform:"scale(1.2) rotate(180deg)",filter:"brightness(1.4)"}
2,"75%":{opacity:.9,transform:"scale(1.1) rotate(270deg)",filter:"brightness(1.2)"},"100%":{opacity:1,transform:"scale(1) rotate(360deg)",filter:"brightness(1)"}},historyDrawerMainContainer:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:e.palette.background.paper},historySearchBarContainer:{padding:e.spacing(2),borderBottom:"1px solid ".concat(e.palette.divider),backgroundColor:"white"},historySearchField:{width:"100%"},dateRangeSelector:{display:"flex",alignItems:"center",gap:e.spacing(1),padding:e.spacing(1),backgroundColor:e.palette.background.paper,border:"1px solid ".concat(e.palette.divider),borderRadius:"8px",cursor:"pointer",transition:"all 0.2s ease",marginTop:e.spacing(1),"&:hover":{borderColor:e.palette.primary.main,backgroundColor:e.palette.primary.light+"05"}},historyLoadingContainer:{display:"flex",justifyContent:"center",alignItems:"center",padding:e.spacing(4),height:"200px"},historyContainer:{flex:1,overflow:"auto",padding:0},promptContainer:{padding:e.spacing(2),borderBottom:"1px solid ".concat(e.palette.divider),cursor:"pointer",transition:"all 0.2s ease",backgroundColor:e.palette.background.paper,"&:hover":{backgroundColor:"#f8f9fa"},"&:last-child":{borderBottom:"none"}},promptContent:{flex:1,minWidth:0,paddingRight:e.spacing(1)},iconButtonContainer:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:e.spacing(1),minWidth:"fit-content"},iconButton:{padding:e.spacing(.4),borderRadius:"6px",transition:"all 0.2s ease","&:hover":{backgroundColor:e.palette.primary.light+"20",color:e.palette.primary.main}},imageGenerationContainer:{marginTop:e.spacing(3)},imageGenerationGrid:{display:"flex",gap:e.spacing(2),justifyContent:"center",alignItems:"flex-start",flexWrap:"nowrap",width:"100%",borderRadius:"8px",overflowX:"auto",paddingBottom:e.spacing(1),[e.breakpoints.down("sm")]:{flexWrap:"wrap",overflowX:"visible",justifyContent:"center"}},imageGenerationItem:{flex:"0 0 auto",minWidth:"200px",maxWidth:"300px",position:"relative",borderRadius:"0px",overflow:"hidden",backgroundColor:"white",transition:"all 0.3s ease",display:"flex",flexDirection:"column",cursor:"pointer",[e.breakpoints.down("sm")]:{flex:"1 1 100%",minWidth:"unset",maxWidth:"100%",width:"100%"}},imageGenerationContent:{flex:"1",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",width:"100%",height:"100%",position:"relative"},imageGenerationActions:{position:"absolute",top:"8px",right:"8px",display:"flex",gap:"8px",opacity:0,transition:"opacity 0.2s ease",zIndex:10,padding:"4px",borderRadius:"4px"},imageGenerationActionButton:{backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#0a474c",width:"36px",height:"36px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)","&:hover":{backgroundColor:"rgba(255, 255, 255, 1)",boxShadow:"0 4px 8px rgba(0,0,0,0.2)"}},imageGenerationOverlay:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"8px",display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"transparent",opacity:0,transition:"all 0.3s ease",zIndex:2},imageGenerationUseButton:{backgroundColor:e.palette.primary.main,color:"white",borderRadius:"8px",padding:"8px 16px",fontSize:"0.8rem",fontWeight:500,textTransform:"none",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.2)","&:hover":{backgroundColor:e.palette.primary.main,color:"white",boxShadow:"none"}},streamingImageContainer:{position:"relative",width:"100%",height:"100%",overflow:"hidden"},streamingImage:{width:"100%",height:"100%",objectFit:"contain",filter:"brightness(0.9) contrast(0.95)",opacity:.8,transition:"all 0.3s ease",border:"6px solid ".concat(e.palette.divider),borderRadius:"8px"},streamingIndicator:{position:"absolute",bottom:"12px",right:"12px",backgroundColor:e.palette.primary.main,color:"white",padding:"6px 12px",borderRadius:"8px",display:"flex",alignItems:"center",gap:"6px",fontSize:"0.75rem",fontWeight:"500"},streamingDot:{width:"8px",height:"8px",backgroundColor:"white",borderRadius:"50%",animation:"pulse 1.5s ease-in-out infinite"},generatedImage:{width:"100%",height:"100%",objectFit:"contain",transition:"all 0.3s ease",borderRadius:"8px"},uploadButton:{paddingTop:"8px",paddingBottom:"8px",paddingLeft:"16px",paddingRight:"16px",minWidth:"auto",whiteSpace:"nowrap",[e.breakpoints.down("sm")]:{width:"100%",minWidth:"unset"}},responsiveWrapper:{display:"flex",alignItems:"center",height:"44px",paddingRight:"5px",gap:e.spacing(1),[e.breakpoints.down("sm")]:{width:"100%",flex:"1 1 100%"}}
2,responsiveWrapperDesktop:{display:{xs:"none",sm:"block"}},responsiveWrapperMobile:{[e.breakpoints.down("sm")]:{flex:"1 1 auto",width:"100% !important",minWidth:"unset !important",maxWidth:"100% !important",display:"block"},[e.breakpoints.up("sm")]:{display:"none"}}})));function At(e){let{imageFile:t,videoFile:a,thumbnailUrl:n,onImageFileChange:o,onVideoFileChange:l,onThumbnailUrlChange:d,onMediaSelect:c,assistantDetails:p,onImageGeneration:u,onVideoGeneration:h,uploadType:m,onUploadTypeChange:g,updateAssistantAdCredits:x,updateAssistantStore:v,isLoading:y=!1,onGenerationStateChange:f,mediaRecommendation:S,aiGeneratorOnly:C=!1,useButtonLabel:T,onUseGeneratedImage:D,hideTabToggle:P=!1}=e;const B=ft(),E=(0,re.Z)(),{showSnackbar:N}=(0,ht.Ds)(),{isAiSensy:F}=(0,Y.K)(),M=e=>{const t=(null===p||void 0===p?void 0:p.currency)||"INR",a=(null===p||void 0===p?void 0:p.aiAdCreativeCount)||0,i=Math.max(0,W.AI_AD_CREATIVE_FREE_GENERATIONS-a);if(i>0)return"".concat(i," free generations left");if("VIDEO"===e){const e=W.AI_GENERATION_PRICING.VIDEO_PER_SECOND[t]*te;return"".concat("USD"===t?"$":"\u20b9"," ").concat(e," Ad Credits")}const s=W.AI_GENERATION_PRICING[e][t];return"".concat("USD"===t?"$":"\u20b9"," ").concat(s," Ad Credits")},R=e=>{const t=(null===p||void 0===p?void 0:p.currency)||"INR";if("VIDEO"===e){return W.AI_GENERATION_PRICING.VIDEO_PER_SECOND[t]*te}return W.AI_GENERATION_PRICING[e][t]};r.useEffect((()=>{const e=document.createElement("style");return e.textContent="\n @keyframes blink {\n 0% { opacity: 1; }\n 50% { opacity: 0.4; }\n 100% { opacity: 1; }\n }\n ",document.head.appendChild(e),()=>document.head.removeChild(e)}),[]);const O=e=>"VIDEO_UPLOAD"===e?"video":"image",[U,z]=(0,r.useState)(O(m));r.useEffect((()=>{const e=O(m);e!==U&&("image"===e?(kt([null]),Tt([null]),Pt([null]),a&&l&&l(null),n&&d&&d(null)):(mt([null,null,null]),bt([null,null,null]),It([null,null,null]),t&&o&&o(null)),at(0),nt(null),Lt(""),Mt(""),Et(null),q(""),H(null),V(null),se("None"),le(""),Ke(!1),Xe(!1)),z(e)}),[m]);const[_,H]=(0,r.useState)(null),[G,V]=(0,r.useState)(null),[Q,q]=(0,r.useState)(""),[J,X]=(0,r.useState)("3:4"),[$,ee]=(0,r.useState)("9:16"),[te,ae]=(0,r.useState)(8),[ie,se]=(0,r.useState)("None"),[ne,le]=(0,r.useState)(""),[ce,pe]=(0,r.useState)(!1),[ue,he]=(0,r.useState)("product"),[me,ge]=(0,r.useState)(!1),[ye,fe]=(0,r.useState)(""),[Ae,be]=(0,r.useState)(!1),[Se,Ve]=(0,r.useState)(["IMAGE","VIDEO"]),[Qe,qe]=(0,r.useState)(!1),[Ye,Ke]=(0,r.useState)(!1),[Je,Xe]=(0,r.useState)(!1),[$e,et]=(0,r.useState)(!1),[tt,at]=(0,r.useState)(0),[it,nt]=(0,r.useState)(null),[rt,mt]=(0,r.useState)([null,null,null]),[At,bt]=(0,r.useState)([null,null,null]),[St,It]=(0,r.useState)([null,null,null]),[jt,Ct]=(0,r.useState)([null]),[wt,kt]=(0,r.useState)([null]),[Zt,Tt]=(0,r.useState)([null]),[Dt,Pt]=(0,r.useState)([null]),[Bt,Et]=(0,r.useState)(null),[Nt,Lt]=(0,r.useState)(""),[Ft,Mt]=(0,r.useState)(""),[Rt,Ot]=(0,r.useState)(!1),[Ut,zt]=(0,r.useState)(""),[_t,Wt]=(0,r.useState)(""),[Ht,Gt]=(0,r.useState)(0),[Vt,Qt]=(0,r.useState)([]),[qt,Yt]=(0,r.useState)({open:!1,message:""}),[Kt,Jt]=(0,r.useState)(!1),[Xt,$t]=(0,r.useState)([]),[ea,ta]=(0,r.useState)(0),[aa,ia]=(0,r.useState)(new Date(Date.now()-2592e6)),[sa,na]=(0,r.useState)(new Date),[oa,ra]=(0,r.useState)(1),[la,da]=(0,r.useState)(10),[ca,pa]=(0,r.useState)(null);(0,r.useEffect)((()=>{"AI_UPLOAD"===m&&(null!==t&&void 0!==t&&t.publicUrl?c&&c([{publicUrl:t.publicUrl,fileType:"IMAGE",fileName:t.fileName||"Image"}]):null!==a&&void 0!==a&&a.publicUrl&&c&&c([{publicUrl:a.publicUrl,fileType:"VIDEO",fileName:a.fileName||"Video"}]))}),[t,a,c,m]),(0,r.useEffect)((()=>
2{f&&f({isImageGenerating:Ye,isVideoGenerating:Je,isGenerating:Ye||Je})}),[Ye,Je,f]),(0,r.useEffect)((()=>{const e=e=>{if(Ye||Je){const t=Ye?"Image generation is in progress. If you refresh now, you will lose your progress. Are you sure you want to leave?":"Video generation is in progress. If you refresh now, you will lose your progress. Are you sure you want to leave?";return e.preventDefault(),e.returnValue=t,t}};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}),[Ye,Je]);const ua=e=>{he(e),Ve("IMAGE"),pe(!0)},ha=()=>{ra(1),da(10),$t([]),ta(0),ia(new Date(Date.now()-864e5)),na(new Date),ge(!me)},ma=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Generated Image",a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];zt(e),Wt(t),Gt(a),Qt(i.length>0?i:[e]),Ot(!0)},ga=()=>{Ot(!1),zt(""),Wt(""),Gt(0),Qt([])},xa=async(e,t)=>{try{Yt({open:!0,message:"Download initiated..."});const a=await lt()(e),i=await a.blob(),s=window.URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),window.URL.revokeObjectURL(s),Yt({open:!0,message:"Download completed!"})}catch(a){Yt({open:!0,message:"Download failed. Please try again."})}},va=(0,r.useMemo)((()=>(0,s.debounce)((()=>{(async()=>{try{if(null===p||void 0===p||!p.assistantId)return;Jt(!0);const e=e=>e?(0,dt.Z)(e,"dd-MM-yyyy"):null,t=e(aa),a=e(sa),{data:s}=await i.Z.post("".concat(W.URL,"/ai-ad-creative/fetch-ad-creative-prompts"),{assistantId:p.assistantId,startDate:t,endDate:a,prompt:ye,limit:la,page:oa}),n=(null===s||void 0===s?void 0:s.aiAdCreativePrompts)||[],o=(null===s||void 0===s?void 0:s.paggination)||{};ta(o.totalCreativeCount||0),$t(n)}catch(e){N("Failed to load prompt history","error")}finally{Jt(!1)}})()}),1e3)),[aa,sa,oa,la,ye]);(0,r.useEffect)((()=>{me&&va()}),[va,me]);const ya=e=>{"second"===e?(Ve("IMAGE"),qe(!0)):(Ve("image"===U?"IMAGE":"VIDEO"),qe(!1)),be(!Ae)},fa=e=>{let t=null;Array.isArray(e)&&e.length>0?t=e[0]:e&&!Array.isArray(e)&&(t=e),t&&(ce?("product"===ue?H(t):"logo"===ue&&V(t),pe(!1)):("image"===U?o&&o(t):l&&l(t),be(!1)))},Aa=(e,t)=>{if(h&&h({publicUrl:e,fileName:"Generated Video",fileType:"VIDEO"}),t&&d){d({publicUrl:t,fileName:"Generated Video Thumbnail",fileType:"IMAGE"})}},ba=e=>{o&&o(e)},Sa=e=>{l&&l(e)},Ia=e=>{const[t,a]=e.split(":").map(Number),i=t/a,s=180;return i>1?{width:Math.min(s*i,280),height:s}:{width:s,height:Math.min(s/i,320)}};return(0,K.jsxs)("div",{className:B.container,children:[!C&&!P&&(0,K.jsxs)("div",{className:B.toggleContainer,children:[(0,K.jsx)(j.ZP,{title:Je?"Video generation in progress":"",children:(0,K.jsxs)("button",{className:"".concat(B.toggleButton," ").concat("image"===U?B.toggleButtonActive:""),onClick:()=>{Je||g&&g("IMAGE_UPLOAD")},disabled:Je,style:{opacity:Je?.5:1,cursor:Je?"not-allowed":"pointer"},children:[(0,K.jsx)(xe,{size:17}),(0,K.jsx)(I.Z,{children:"Image"})]})}),(0,K.jsx)(j.ZP,{title:Ye?"Image generation in progress":"",children:(0,K.jsxs)("button",{className:"".concat(B.toggleButton," ").concat("video"===U?B.toggleButtonActive:""),onClick:()=>{Ye||g&&g("VIDEO_UPLOAD")},disabled:Ye,style:{opacity:Ye?.5:1,cursor:Ye?"not-allowed":"pointer"},children:[(0,K.jsx)(ve,{size:20}),(0,K.jsx)(I.Z,{children:"Video"})]})})]}),!C&&S&&(0,K.jsx)(pt.Z,{severity:"info",style:{marginTop:"12px",marginBottom:"4px"},children:S}),!C&&(0,K.jsx)(A.Z,{className:B.manualUploadContainer,children:"image"===U?(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(A.Z,{className:B.mediaUrlField,children:[y?(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,width:"100%",style:{borderRadius:"10px"}}):(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(L.Z,{variant:"outlined",className:B.mediaUrlFieldBox,placeholder:"Media URL",name:"url",value:(null===t||void 0===t?void 0:t.publicUrl)||"",onChange:e=>{const t=e.target.value;if(t){ba({publicUrl:t,fileName:"Image",fileType:"IMAGE"})}else ba(null)},fullWidth:!0})}),(0,K.jsx)(I.Z,{variant:"body2",className:B.mediaUrlFieldText,children:"OR"}),(0,K.jsx)(w.Z,{color:"primary",variant:"contained",onClick:()=>ya("first"),className:B.uploadButton,children:"Upload from Media Library"})]})}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(A.Z,{className:B.mediaUrlField,children:[y?(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,width:"100%",style:{borderRadius:"10px"}}):(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(L.Z,{variant:"outlined",className:B.mediaUrlFieldBox,placeholder:"Video URL",name:"url",value:(null===a||void 0===a?void 0:a.publicUrl)||"",onChange:e=>{const t=e.target.value;if(t){Sa({publicUrl:t,fileName:"Video",fileType:"VIDEO"})}else Sa(null)},fullWidth:!0})}),(0,K.jsx)(I.Z,{variant:"body2",className:B.mediaUrlFieldText,children:"OR"}),(0,K.jsx)(w.Z,{color:"primary",variant:"contained",onClick:()=>ya("first"),className:B.uploadButton,children:"Upload from Media Library"})]}),(0,K.jsx)(A.Z,{style:{marginTop:E.spacing(2)},children:(0,K.jsxs)(A.Z,{className:B.mediaUrlField,children:[y?(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,width:"100%",style:{borderRadius:"10px"}}):(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(L.Z,{variant:"outlined",className:B.mediaUrlFieldBox,placeholder:"Thumbn
2ail URL",name:"thumbnailUrl",value:(null===n||void 0===n?void 0:n.publicUrl)||"",onChange:e=>{const t=e.target.value;if(t){d&&d({publicUrl:t,fileName:"Thumbnail",fileType:"IMAGE"})}else d&&d(null)},fullWidth:!0})}),(0,K.jsx)(I.Z,{variant:"body2",className:B.mediaUrlFieldText,children:"OR"}),(0,K.jsx)(w.Z,{color:"primary",variant:"contained",onClick:()=>ya("second"),className:B.uploadButton,children:"Upload from Media Library"})]})})]})}),"image"===U&&F&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(I.Z,{variant:"h6",className:B.orDivider,children:["OR"," "]}),(0,K.jsx)("div",{className:B.headerContainer,children:(0,K.jsxs)("div",{className:B.headerBadge,children:[(0,K.jsx)(we.Z,{className:"".concat(B.sparklesIcon," ").concat(B.headerBadge," h-3 w-3 flex-shrink-0"),color:E.palette.primary.main}),(0,K.jsx)(I.Z,{variant:"body1",children:"Generate Your Creatives with AI"})]})})]}),"image"===U&&F&&(0,K.jsxs)(A.Z,{className:B.tabContent,children:[(0,K.jsx)(A.Z,{style:{display:"flex",flexDirection:window.innerWidth<768?"column":"row",justifyContent:window.innerWidth<768?"flex-start":"space-between",alignItems:window.innerWidth<768?"flex-start":"center",gap:window.innerWidth<768?E.spacing(1):0,marginBottom:E.spacing(1)},children:(0,K.jsx)(j.ZP,{title:"View History",children:(0,K.jsx)(w.Z,{onClick:ha,variant:"outlined",startIcon:(0,K.jsx)(ke,{size:18,style:{color:E.palette.primary.main}}),className:B.historyButton,children:"View History"})})}),(0,K.jsx)(L.Z,{value:Q,onChange:e=>{const t=e.target.value;t.length<=2048&&q(t)},placeholder:"Describe what you want to create...",multiline:!0,rows:4,variant:"outlined",fullWidth:!0,className:B.TextFieldRoot,inputProps:{maxLength:2048}}),Q.length>0&&Q.length<15&&(0,K.jsx)(I.Z,{variant:"caption",style:{color:E.palette.error.main,marginTop:E.spacing(.5),display:"block"},children:"Please enter at least 15 characters"}),Q.length>=15&&(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:E.spacing(.5)},children:[Q.length>=2048&&(0,K.jsx)(I.Z,{variant:"caption",style:{color:E.palette.error.main},children:"Maximum 2048 characters allowed. Please shorten your prompt."}),(0,K.jsxs)(I.Z,{variant:"caption",style:{color:Q.length>=2048?E.palette.error.main:E.palette.text.secondary,marginLeft:"auto"},children:[Q.length," / 2048 characters"]})]}),(0,K.jsxs)(A.Z,{className:B.controlsContainer,children:[(0,K.jsx)(j.ZP,{title:"Select Product Image",children:(0,K.jsx)(w.Z,{onClick:()=>ua("product"),variant:"outlined",startIcon:(0,K.jsx)(Ze,{size:20,style:{color:E.palette.primary.main}}),endIcon:(0,K.jsx)(Te,{size:20}),className:B.mediaButton,children:"Product"})}),(0,K.jsx)(j.ZP,{title:"Select Brand Logo",children:(0,K.jsx)(w.Z,{onClick:()=>ua("logo"),variant:"outlined",startIcon:(0,K.jsx)(De,{size:20,style:{color:E.palette.primary.main}}),endIcon:(0,K.jsx)(Te,{size:20}),className:B.mediaButton,children:"Logo"})}),(0,K.jsxs)(A.Z,{className:B.responsiveWrapper,style:{marginLeft:"6px"},children:[(0,K.jsx)(j.ZP,{title:"Select Image Aspect Ratio",children:(0,K.jsx)(b.Z,{style:{padding:"0px"},children:(0,K.jsx)(Pe,{size:20})})}),(0,K.jsx)(Ge.Z,{currentRatio:J,onRatioChange:X,style:{width:"100%",[E.breakpoints.down("sm")]:{width:"93%",flex:"1 1 auto"}},children:(0,K.jsxs)(A.Z,{size:"small",className:"".concat(B.formControl," ").concat(B.mobileFormControl),style:{cursor:"pointer",width:"100% !important",paddingLeft:"10px",paddingRight:"10px",paddingTop:"8px",paddingBottom:"8px",[E.breakpoints.down("sm")]:{flex:"1 1 auto",width:"100% !important",minWidth:"unset !important",maxWidth:"100% !important",paddingTop:"14px !important",paddingBottom:"14px !important"}},children:[(0,K.jsx)(I.Z,{style:{fontSize:"14px",color:E.palette.text.primary,pointerEvents:"none"},children:J}),(0,K.jsx)(Be.Z,{size:16,style:{marginLeft:"auto",color:E.palette.text.secondary,pointerEvents:"none",paddingLeft:"30px"}})]})})]}),(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:E.spacing(.6),[E.breakpoints.down("sm")]:{width:"100%",flex:"1 1 100%",paddingTop:"0px"}},children:[(0,K.jsx)(j.ZP,{title:"Select Target Audience",children:(0,K.jsx)(b.Z,{className:B.iconButton,children:(0,K.jsx)(Ee,{size:20,style:{backgroundColor:E.palette.primary.light+"20",borderRadius:"4px",paddingLeft:E.breakpoints.down("sm")?"0px":"15px"}})})}),(0,K.jsxs)(A.Z,{size:"small",className:B.formControl,style:{pointerEvents:"auto",[E.breakpoints.down("sm")]:{flex:"1 1 auto",width:"100%"}},children:[(0,K.jsxs)(Ie.Z,{defaultValue:"general",children:[(0,K.jsx)(de.Z,{value:"general",children:"General"}),(0,K.jsx)(de.Z,{value:"professional",children:"Professional"}),(0,K.jsx)(de.Z,{value:"creative",children:"Creative"}),(0,K.jsx)(de.Z,{value:"youth",children:"Youth"}),(0,K.jsx)(de.Z,{value:"family",children:"Family"})]}),(0,K.jsx)(Be.Z,{size:16,style:{marginLeft:"auto",color:E.palette.text.secondary,pointerEvents:"none"}})]})]}),(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)(j.ZP,{title:"Select Call To Action ",children:(0,K.jsx)(b.Z,{style:{padding:"0px"},className:B.iconButton,children:(0,K.jsx)(Ne,{size:20,style:{backgroundColor:E.palette.primary.light+"20",borderRadius:"4px",paddingLeft:E.breakpoints.down("sm")?"0px":"15px",paddingRight:"6px"}})})}),(0,K.jsxs)(A.Z,{size:"small",className:B.formControl,children:[(0,K.jsx)(Ie.Z,{value:ie,onChange:e=>se(e.target.value),children:[{value:"None",label:"None"},{value:"Shop now",label:"Shop Now"},{value:"Learn more",label:"Learn More"},{value:"Get started",label:"Get Started"},{value:"Buy now",label:"Buy Now"},{value:"Sign up",label:"Sign Up"},{value:"Download now",label:"Download Now"},{value:"Try free",label:"Try for Free"},{value:"Contact us",label:"Contact Us"},{value:"custom",label:"Custom..."}].map((e=>(0,K.jsx)(de.Z,{value:e.value,children:e.label},e.value)))}),(0,K.jsx)(Be.Z,{size:16,style:{marginLeft:"auto",color:E.palette.text.secondary,pointerEvents:"none"}})]})]}),"custom"===ie&&(0,K.jsx)(L.Z,{value:ne,onChange:e=>le(e.target.value),placeholder:"Enter your custom call-to-action text...",variant:"outlined",fullWidth:!0,className:B.mediaUrlFieldBox}),(_||G)&&(0,K.jsxs)(A.Z,{className:B.filePreviews,children:[_&&(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:E.spacing(1),padding:E.spacing(1),border:"1px solid ".concat(E.palette.divider),borderRadius:"8px",backgroundColor:E.palette.background.paper,maxWidth:"200px"},children:[(0,K.jsx)("img",{src:_.publicUrl||_.url||_.thumbnailUrl,alt:"Product Preview",style:{width:"40px",height:"40px",objectFit:"cover",borderRadius:"4px"}}),(0,K.jsxs)(A.Z,{style:{flex:1,minWidth:0},children:[(0,K.jsx)(I.Z,{variant:"caption",style:{fontSize:"10px",fontWeight:500,color:E.palette.text.primary,display:"block",marginBottom:"2px"},children:"Product"}),(0,K.jsx)(I.Z,{variant:"body2",style:{fontSize:"12px",color:E.palette.text.secondary,textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",maxWidth:"120px"},children:_.name||_.fileName||"Selected Media"})]}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>H(null),style:{padding:"4px"},children:(0,K.jsx)(Le.Z,{size:16})})]}),G&&(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:E.spacing(1),padding:E.spacing(1),border:"1px solid ".concat(E.palette.divider),borderRadius:"8px",backgroundColor:E.palette.background.paper,maxWidth:"200px"},children:[(0,K.jsx)("img",{src:G.publicUrl||G.url||G.thumbnailUrl,alt:"Logo Preview",style:{width:"40px",height:"40px",objectFit:"cover",borderRadius:"4px"}}),(0,K.jsxs)(A.Z,{style:{flex:1,minWidth:0},children:[(0,K.jsx)(I.Z,{variant:"caption",style:{fontSize:"10px",fontWeight:500,color:E.palette.text.primary,display:"block",marginBottom:"2px"},children:"Logo"}),(0,K.jsx)(I.Z,{variant:"body2",style:{fontSize:"12px",color:E.palette.text.secondary,textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",maxWidth:"120px"},children:G.name||G.fileName||"Selected Logo"})]}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>V(null),style:{padding:"4px"},children:(0,K.jsx)(Le.Z,{size:16})})]})]}),(0,K.jsx)(j.ZP,{title:Je?"Video generation in progress":Q.trim()?"":"Please enter a prompt for image generation",disableHoverListener:""!==Q.trim()&&!Je,children:(0,K.jsx)("span",{style:{display:"block",width:"100%"},children:(0,K.jsx)(w.Z,{size:"large",variant:"contained",className:B.generateButton,startIcon:(0,K.jsx)(we.Z,{size:20,style:{animation:"blink 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",WebkitAnimation:"blink 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),onClick:Ye||Je?null:async()=>
2{if(!Q.trim())return void N("Please enter a prompt for image generation","warning");if(null===p||void 0===p||!p.assistantId)return void N("Assistant details not available. Please refresh the page.","error");if(Je)return void N("Video generation is in progress. Please wait for it to complete.","warning");Ke(!0),at(0),nt("processing"),mt([null,null,null]),bt([null,null,null]),It([null,null,null]),Et(null),Lt(""),Mt("");try{const t=(await xt("".concat(W.URL,"/ai-ad-creative/generate-ad-creative"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:Q,aspectRatio:"1:1"===J?"ASPECT_1_1":"2:3"===J?"ASPECT_2_3":"3:2"===J?"ASPECT_3_2":"3:4"===J?"ASPECT_3_4":"4:3"===J?"ASPECT_4_3":"9:16"===J?"ASPECT_9_16":"16:9"===J?"ASPECT_16_9":"ASPECT_1_1",styleType:"AUTO",assistantId:null===p||void 0===p?void 0:p.assistantId,productImage:(null===_||void 0===_?void 0:_.publicUrl)||"",logoImage:(null===G||void 0===G?void 0:G.publicUrl)||"",character:!0,audience:"general",font:"default",cta:"custom"===ie?ne:"None"===ie?"":ie,productUrl:""})})).body.getReader(),a=new TextDecoder;let i=[null,null,null],s=[null,null,null],n=[null,null,null];for(;;){const{value:o,done:r}=await t.read();if(r)break;const l=a.decode(o).split("\n").filter((e=>e.trim()));for(const t of l){let a=t;if(t.startsWith("data: ")&&(a=t.substring(6)),a&&": ping"!==a)try{const e=JSON.parse(a);if(e.stage&&(Lt(e.stage),Mt(e.data||""),"start"===e.stage?at(10):"concepts"===e.stage?at(30):"images"===e.stage?at(50):"complete"===e.stage&&(at(100),nt("completed"))),"concept"===e.stage&&void 0!==e.concept_index&&(s[e.concept_index]=e.data,bt([...s])),"image_stream"===e.stage&&void 0!==e.image_index&&e.data&&(n[e.image_index]=e.data,It([...n])),"image_complete"===e.stage&&void 0!==e.image_index){i[e.image_index]=e.data,s[e.image_index]=e.concept,n[e.image_index]=null,mt([...i]),bt([...s]),It([...n]);const t=i.filter((e=>null!==e)).length;at(50+15*t)}if("complete"===e.type){const t=(null===p||void 0===p?void 0:p.aiAdCreativeCount)||0;if(Math.max(0,W.AI_AD_CREATIVE_FREE_GENERATIONS-t)<=0){const e=R("IMAGE"),t=(null===p||void 0===p?void 0:p.metaAdsCredit)||0;x(t-e)}v({aiAdCreativeCount:t+1}),nt("completed"),at(100),Mt(e.message||"Generation completed"),N("Image generation completed successfully!","success")}if("image_error"===e.stage){nt("failed");const t=e.error||e.message||"Image generation failed";N("Image generation failed: ".concat(t),"error")}"error"===e.type&&(nt("failed"),N(e.message||"Image generation failed","error"))}catch(e){console.error("Error parsing streaming data:",e)}}}}catch(t){nt("failed");const e=t.message||"Something went wrong during image generation";N(e,"error")}finally{Ke(!1)}},disabled:Ye||Je||!Q.trim()||Q.length<15,children:Ye?"Generating...":Je?"Video generation in progress...":"Generate Image (".concat(M("IMAGE"),")")})})}),"image"===U&&(rt.some((e=>null!==e))||St.some((e=>null!==e))||Ye)&&(0,K.jsx)(A.Z,{className:B.imageGenerationContainer,children:(0,K.jsx)(A.Z,{className:B.imageGenerationGrid,children:[0,1,2].map((e=>{const t=rt[e],a=St[e],i=null!==t,s=null!==a,n=Ye&&!t&&!a,r=Ia(J);return(0,K.jsx)(A.Z,{className:B.imageGenerationItem,style:{width:"".concat(r.width,"px"),height:"".concat(r.height,"px"),[E.breakpoints.down("sm")]:{width:"100%",height:"auto",aspectRatio:"".concat(r.width,"/").concat(r.height)}},onClick:()=>(i||s)&&Et(e),children:(0,K.jsx)(A.Z,{className:B.imageGenerationContent,children:s?(0,K.jsx)(A.Z,{className:B.streamingImageContainer,children:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)("img",{src:a,alt:"Generating ".concat(e+1),className:B.streamingImage}),(0,K.jsxs)(A.Z,{className:B.streamingIndicator,children:[(0,K.jsx)(A.Z,{className:B.streamingDot}),"Generating..."]}),(0,K.jsxs)(A.Z,{className:B.imageGenerationActions,onMouseEnter:e=>{e.currentTarget.style.opacity=1},onMouseLeave:e=>{e.currentTarget.style.opacity=0},children:[(0,K.jsx)(b.Z,{size:"small",onClick:t=>{t.preventDefault(),t.stopPropagation();const i=St.filter((e=>null!==e)).concat(rt.filter((e=>null!==e)));ma(a,"Generated Image ".concat(e+1),e,i)},className:B.imageGenerationActionButton,children:(0,K.jsx)(Fe,{size:18})}),(0,K.jsx)(b.Z,{size:"small",onClick:t=>{t.preventDefault(),t.stopPropagation(),xa(a,"generated-image-".concat(e+1,".jpg"))},className:B.imageGenerationActionButton,children:(0,K.jsx)(Me,{size:18})})]}),(0,K.jsx)(A.Z,{className:B.imageGenerationOverlay,onMouseEnter:e=>{e.currentTarget.style.opacity=1},onMouseLeave:e=>{e.currentTarget.style.opacity=0},children:(0,K.jsx)(w.Z,{onClick:()=>{Et(e),D?D(a):(u(a),o({publicUrl:a,fileName:"Generated Image",fileType:"IMAGE"}))},variant:"contained",className:B.imageGenerationUseButton,children:T||"Use this"})})]})}):i?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(A.Z,{className:B.imageGenerationActions,onMouseEnter:e=>{e.currentTarget.style.opacity=1},onMouseLeave:e=>{e.currentTarget.style.opacity=0},children:[(0,K.jsx)(b.Z,{size:"small",onClick:a=>{a.preventDefault(),a.stopPropagation();const i=St.filter((e=>null!==e)).concat(rt.filter((e=>null!==e)));ma(t,"Generated Image ".concat(e+1),e,i)},className:B.imageGenerationActionButton,children:(0,K.jsx)(Fe,{size:18})}),(0,K.jsx)(b.Z,{size:"small",onClick:a=>{a.preventDefault(),a.stopPropagation(),xa(t,"generated-image-".concat(e+1,".jpg"))},className:B.imageGenerationActionButton,children:(0,K.jsx)(Me,{size:18})})]}),(0,K.jsx)(A.Z,{className:B.imageGenerationOverlay,onMouseEnter:e=>{e.currentTarget.style.opacity=1,e.currentTarget.style.backgroundColor="rgba(0, 0, 0, 0.3)";const t=e.currentTarget.parentElement.querySelector(".".concat(B.imageGenerationActions));t&&(t.style.opacity=1)},onMouseLeave:e=>{e.currentTarget.style.opacity=0,e.currentTarget.style.backgroundColor="transparent";const t=e.currentTarget.parentElement.querySelector(".".concat(B.imageGenerationActions));t&&(t.style.opacity=0)},children:(0,K.jsx)(w.Z,{onClick:()=>{Et(e),D?D(t):(u(t),o({publicUrl:t,fileName:"Generated Image",fileType:"IMAGE"}))},variant:"contained",className:B.imageGenerationUseButton,children:T||"Use this"})}),(0,K.jsx)("img",{src:t,alt:"Generated ".concat(e+1),className:B.generatedImage})]}):n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(oe.Z,{variant:"rectangular",width:"100%",height:"100%",animation:"wave",style:{borderRadius:"0px",backgroundColor:"#f0f0f0",position:"absolute",top:0,left:0,right:0,bottom:0}}),(0,K.jsx)(ot,{progress:tt})]})})},e)}))})})]})]}),"video"===U&&F&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(I.Z,{variant:"h6",className:B.orDivider,children:["OR"," "]}),(0,K.jsx)("div",{className:B.headerContainer,children:(0,K.jsxs)("div",{className:B.headerBadge,children:[(0,K.jsx)(we.Z,{className:"".concat(B.sparklesIcon," ").concat(B.headerBadge," h-3 w-3 flex-shrink-0"),color:E.palette.primary.main}),(0,K.jsx)(I.Z,{variant:"body1",children:"Generate Your Video Creatives with AI"})]})})]}),"video"===U&&F&&(0,K.jsxs)(A.Z,{className:B.tabContent,children:[(0,K.jsx)(A.Z,{style:{display:"flex",flexDirection:window.innerWidth<768?"column":"row",justifyContent:window.innerWidth<768?"flex-start":"space-between",alignItems:window.innerWidth<768?"flex-start":"center",gap:window.innerWidth<768?E.spacing(1):0,marginBottom:E.spacing(1)},children:(0,K.jsx)(j.ZP,{title:"View History",children:(0,K.jsx)(w.Z,{onClick:ha,variant:"outlined",startIcon:(0,K.jsx)(ke,{size:18,style:{color:E.palette.primary.main}}),className:B.historyButton,children:"View History"})})}),(0,K.jsx)(L.Z,{value:Q,onChange:e=>{const t=e.target.value;t.length<=2048&&q(t)},placeholder:"Describe what you want to create...",multiline:!0,rows:4,variant:"outlined",fullWidth:!0,className:B.TextFieldRoot,inputProps:{maxLength:2048}}),Q.length>0&&Q.length<15&&(0,K.jsx)(I.Z,{variant:"caption",style:{color:E.palette.error.main,marginTop:E.spacing(.5),display:"block"},children:"Please enter at least 15 characters"}),Q.length>
2=15&&(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:E.spacing(.5)},children:[Q.length>=2048&&(0,K.jsx)(I.Z,{variant:"caption",style:{color:E.palette.error.main},children:"Maximum 2048 characters allowed. Please shorten your prompt."}),(0,K.jsxs)(I.Z,{variant:"caption",style:{color:Q.length>=2048?E.palette.error.main:E.palette.text.secondary,marginLeft:"auto"},children:[Q.length," / 2048 characters"]})]}),(0,K.jsxs)(A.Z,{className:B.controlsContainer,children:[(0,K.jsx)(j.ZP,{title:"Select Product Image",children:(0,K.jsx)(w.Z,{onClick:()=>ua("product"),variant:"outlined",startIcon:(0,K.jsx)(Ze,{size:20,style:{color:E.palette.primary.main}}),endIcon:(0,K.jsx)(Te,{size:20}),className:B.mediaButton,children:"Product"})}),(0,K.jsxs)(A.Z,{className:B.responsiveWrapper,style:{height:"43px"},children:[(0,K.jsx)(j.ZP,{style:{padding:"0px"},title:"Select Video Aspect Ratio",children:(0,K.jsx)(b.Z,{style:{padding:"0px"},children:(0,K.jsx)(Pe,{size:20})})}),(0,K.jsx)(Ge.Z,{currentRatio:$,onRatioChange:ee,style:{width:"100%",[E.breakpoints.down("sm")]:{width:"100%",flex:"1 1 auto"}},children:(0,K.jsxs)(A.Z,{size:"small",className:"".concat(B.formControl," ").concat(B.videoMobileFormControl),style:{cursor:"pointer",width:"100% !important",paddingLeft:"10px",paddingRight:"10px",paddingTop:"8px",paddingBottom:"8px",[E.breakpoints.down("sm")]:{flex:"1 1 auto",width:"100% !important",minWidth:"unset !important",maxWidth:"100% !important",paddingTop:"14px !important",paddingBottom:"14px !important"}},children:[(0,K.jsx)(I.Z,{style:{fontSize:"14px",color:E.palette.text.primary,pointerEvents:"none"},children:$}),(0,K.jsx)(Be.Z,{size:16,style:{marginLeft:"auto",color:E.palette.text.secondary,pointerEvents:"none",paddingLeft:"30px"}})]})})]}),(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)(j.ZP,{style:{padding:"0px"},title:"Select Target Audience",children:(0,K.jsx)(b.Z,{className:B.iconButton,children:(0,K.jsx)(Ee,{size:20,style:{backgroundColor:E.palette.primary.light+"20",borderRadius:"4px",paddingRight:"5px"}})})}),(0,K.jsxs)(A.Z,{size:"small",className:B.formControl,children:[(0,K.jsxs)(Ie.Z,{defaultValue:"general",children:[(0,K.jsx)(de.Z,{value:"general",children:"General"}),(0,K.jsx)(de.Z,{value:"professional",children:"Professional"}),(0,K.jsx)(de.Z,{value:"creative",children:"Creative"}),(0,K.jsx)(de.Z,{value:"youth",children:"Youth"}),(0,K.jsx)(de.Z,{value:"family",children:"Family"})]}),(0,K.jsx)(Be.Z,{size:16,style:{marginLeft:"auto",color:E.palette.text.secondary,pointerEvents:"none"}})]})]}),_&&(0,K.jsx)(A.Z,{className:B.filePreviews,children:_&&(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:E.spacing(1),padding:E.spacing(1),border:"1px solid ".concat(E.palette.divider),borderRadius:"8px",backgroundColor:E.palette.background.paper,maxWidth:"200px"},children:[(0,K.jsx)("img",{src:_.publicUrl||_.url||_.thumbnailUrl,alt:"Product Preview",style:{width:"40px",height:"40px",objectFit:"cover",borderRadius:"4px",border:"1px solid ".concat(E.palette.divider)}}),(0,K.jsxs)(A.Z,{style:{flex:1,minWidth:0},children:[(0,K.jsx)(I.Z,{variant:"caption",style:{display:"block",fontWeight:500,color:E.palette.text.primary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"Product"}),(0,K.jsx)(I.Z,{variant:"caption",style:{display:"block",color:E.palette.text.secondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_.name||_.fileName||"Selected Media"})]}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>{H(null)},style:{color:E.palette.text.secondary,padding:"4px"},children:(0,K.jsx)(Le.Z,{size:16})})]})}),(0,K.jsx)(j.ZP,{title:Ye?"Image generation in progress":Q.trim()?"":"Please enter a prompt for video generation",disableHoverListener:""!==Q.trim()&&!Ye,children:(0,K.jsx)("span",{style:{display:"block",width:"100%"},children:(0,K.jsx)(w.Z,{size:"large",variant:"contained",className:B.generateButton,startIcon:(0,K.jsx)(we.Z,{size:20,style:{animation:"blink 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",WebkitAnimation:"blink 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),onClick:Je||Ye?null:async()=>
2{if(Q.trim())if(null!==p&&void 0!==p&&p.assistantId)if(Ye)N("Image generation is in progress. Please wait for it to complete.","warning");else{Xe(!0),at(0),nt("processing"),Ct([null]),kt([null]),Tt([null]),Pt([null]);try{const n=(await xt("".concat(W.URL,"/ai-ad-creative/generate-ad-creative"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:Q,aspectRatio:"1:1"===$?"ASPECT_1_1":"2:3"===$?"ASPECT_2_3":"3:2"===$?"ASPECT_3_2":"3:4"===$?"ASPECT_3_4":"4:3"===$?"ASPECT_4_3":"9:16"===$?"ASPECT_9_16":"16:9"===$?"ASPECT_16_9":"ASPECT_9_16",assistantId:null===p||void 0===p?void 0:p.assistantId,productImage:(null===_||void 0===_?void 0:_.publicUrl)||"",productUrl:"",character:!0,audience:"general",font:"default",adType:"video",duration:te,adObjective:"awareness"})})).body.getReader(),o=new TextDecoder;for(;;){const{value:r,done:l}=await n.read();if(l)break;const d=o.decode(r).split("\n").filter((e=>e.trim()));for(const n of d){let o=n;if(n.startsWith("data: ")&&(o=n.substring(6)),o&&": ping"!==o)try{const s=JSON.parse(o);if(s.stage&&(Lt(s.stage),Mt(s.data||""),"start"===s.stage?at(10):"concepts"===s.stage?at(20):"concept"===s.stage?at(30):"videos"===s.stage?at(40):"video_complete"===s.stage?at(90):"complete"===s.stage&&(at(100),nt("completed"))),void 0===s.progress||s.stage||at(s.progress||0),"video_stream"===s.stage&&s.data){var e,t;const a=(null===(e=s.data)||void 0===e?void 0:e.video_url)||s.data,i=(null===(t=s.data)||void 0===t?void 0:t.first_frame_url)||null;kt([a]),Pt([i])}if("video_complete"===s.stage){var a,i;const e=(null===(a=s.data)||void 0===a?void 0:a.video_url)||s.data,t=(null===(i=s.data)||void 0===i?void 0:i.first_frame_url)||null;Ct([e]),Tt([t]),kt([null]),Pt([null])}if("final"===s.stage||"done"===s.stage||"complete"===s.stage||"video_complete"===s.stage){const e=(null===p||void 0===p?void 0:p.aiAdCreativeCount)||0;if(Math.max(0,W.AI_AD_CREATIVE_FREE_GENERATIONS-e)<=0){const e=R("VIDEO"),t=(null===p||void 0===p?void 0:p.metaAdsCredit)||0;x(t-e)}v({aiAdCreativeCount:e+1}),nt("completed"),at(100),N("Video generation completed successfully!","success")}"video_error"===s.stage&&(nt("failed"),N(s.error||s.message||"Video generation failed","error")),"error"===s.stage&&(nt("failed"),N(s.error||s.message||"Video generation failed due to internal checks, please try with a different prompt","error"))}catch(s){console.error("Error parsing streaming data:",s)}}}}catch(n){nt("failed"),"Video generation failed due to internal checks, please try with a different prompt"==n.message?N("Video generation failed due to internal checks, please try with a different prompt","error"):N(n.message||"Something went wrong during video generation","error")}finally{Xe(!1)}}else N("Assistant details not available. Please refresh the page.","error");else N("Please enter a prompt for video generation","warning")},disabled:Je||Ye||!Q.trim()||Q.length<15,children:Je?"Generating...":Ye?"Image generation in progress...":"Generate Video (".concat(M("VIDEO"),")")})})}),"video"===U&&(jt.some((e=>null!==e))||wt.some((e=>null!==e))||Je)&&(0,K.jsx)(A.Z,{className:B.imageGenerationContainer,children:(0,K.jsx)(A.Z,{className:B.imageGenerationGrid,children:[0].map((e=>{const t=jt[e],a=wt[e],i=Zt[e],s=Dt[e],n=null!==t,o=null!==a,r=Je&&!t&&!a,l=Ia($);return(0,K.jsx)(A.Z,{className:B.imageGenerationItem,style:{width:"".concat(l.width,"px"),height:"".concat(l.height,"px")},onClick:()=>(n||o)&&Et(e),children:(0,K.jsx)(A.Z,{className:B.imageGenerationContent,children:o?(0,K.jsxs)(A.Z,{className:B.streamingImageContainer,children:[(0,K.jsx)("video",{src:a,poster:s,className:B.streamingImage,muted:!0}),(0,K.jsxs)(A.Z,{className:B.streamingIndicator,children:[(0,K.jsx)(A.Z,{className:B.streamingDot}),"Generating..."]}),(0,K.jsxs)(A.Z,{className:B.imageGenerationActions,onMouseEnter:e=>{e.currentTarget.style.opacity=1},onMouseLeave:e=>{e.currentTarget.style.opacity=0},children:[(0,K.jsx)(b.Z,{size:"small",onClick:e=>{e.preventDefault(),e.stopPropagation(),zt(a),Wt("Generated Video"),Ot(!0)},className:B.imageGenerationActionButton,children:(0,K.jsx)(Fe,{size:16})}),(0,K.jsx)(b.Z,{size:"small",onClick:t=>{t.preventDefault(),t.stopPropagation(),xa(a,"generated-video.mp4"),s&&xa(s,"generated-video-thumbnail-".concat(e+1,".jpg"))},className:B.imageGenerationActionButton,children:(0,K.jsx)(Me,{size:16})})]}),(0,K.jsx)(A.Z,{className:B.imageGenerationOverlay,onMouseEnter:e=>{e.currentTarget.style.opacity=1,e.currentTarget.style.backgroundColor="rgba(0, 0, 0, 0.3)";const t=e.currentTarget.parentElement.querySelector(".".concat(B.imageGenerationActions));t&&(t.style.opacity=1)},onMouseLeave:e=>{e.currentTarget.style.opacity=0,e.currentTarget.style.backgroundColor="transparent";const t=e.currentTarget.parentElement.querySelector(".".concat(B.imageGenerationActions));t&&(t.style.opacity=0)},children:(0,K.jsx)(w.Z,{onClick:()=>{Et(e),Aa(a,s)},variant:"contained",className:B.imageGenerationUseButton,children:"Use this"})})]}):n?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)("video",{src:t,poster:i,className:B.generatedImage,muted:!0}
2),(0,K.jsxs)(A.Z,{className:B.imageGenerationActions,onMouseEnter:e=>{e.currentTarget.style.opacity=1},onMouseLeave:e=>{e.currentTarget.style.opacity=0},children:[(0,K.jsx)(b.Z,{size:"small",onClick:e=>{e.preventDefault(),e.stopPropagation(),zt(t),Wt("Generated Video"),Ot(!0)},className:B.imageGenerationActionButton,children:(0,K.jsx)(Fe,{size:16})}),(0,K.jsx)(b.Z,{size:"small",onClick:a=>{a.preventDefault(),a.stopPropagation(),xa(t,"generated-video.mp4"),i&&xa(i,"generated-video-thumbnail-".concat(e+1,".jpg"))},className:B.imageGenerationActionButton,children:(0,K.jsx)(Me,{size:16})})]}),(0,K.jsx)(A.Z,{className:B.imageGenerationOverlay,onMouseEnter:e=>{e.currentTarget.style.opacity=1,e.currentTarget.style.backgroundColor="rgba(0, 0, 0, 0.3)";const t=e.currentTarget.parentElement.querySelector(".".concat(B.imageGenerationActions));t&&(t.style.opacity=1)},onMouseLeave:e=>{e.currentTarget.style.opacity=0,e.currentTarget.style.backgroundColor="transparent";const t=e.currentTarget.parentElement.querySelector(".".concat(B.imageGenerationActions));t&&(t.style.opacity=0)},children:(0,K.jsx)(w.Z,{onClick:()=>{Et(e),Aa(t,i)},variant:"contained",className:B.imageGenerationUseButton,children:"Use this"})})]}):r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(oe.Z,{variant:"rect",width:"100%",height:"100%",style:{position:"absolute",top:0,left:0,right:0,bottom:0}}),(0,K.jsx)(ot,{progress:tt})]}):null})},e)}))})})]})]}),(0,K.jsx)(je.ZP,{anchor:"right",open:me,onClose:ha,className:B.historyDrawer,PaperProps:{style:{width:window.innerWidth>768?"600px":"100vw",maxWidth:"100vw",backgroundColor:"#ffffff",boxShadow:"-4px 0 20px rgba(0, 0, 0, 0.1)"}},children:(0,K.jsxs)(A.Z,{style:{display:"flex",flexDirection:"column",height:"100%",overflowX:"hidden"},className:B.historyDrawerMainContainer,children:[(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"20px 24px",borderBottom:"1px solid #E8E8E8",backgroundColor:"#ffffff",position:"sticky",top:0,zIndex:10},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:"12px"},children:[(0,K.jsx)(A.Z,{style:{backgroundColor:"#ebf5f3",borderRadius:"8px",padding:"8px",display:"flex",alignItems:"center",justifyContent:"center"},children:(0,K.jsx)(Re.Z,{size:20,color:"#0a474c"})}),(0,K.jsx)(I.Z,{variant:"h5",style:{color:"#0a474c",fontWeight:500,fontSize:"18px",lineHeight:"24px"},children:"Previous Ai Generated Ads"})]}),(0,K.jsx)(b.Z,{onClick:ha,size:"small",style:{backgroundColor:"#f5f5f5",borderRadius:"8px",padding:"8px","&:hover":{backgroundColor:"#e0e0e0"}},children:(0,K.jsx)(ct.Z,{style:{fontSize:"20px",color:"#666"}})})]}),(0,K.jsxs)(A.Z,{className:B.historySearchBarContainer,children:[(0,K.jsx)(A.Z,{className:B.historySearchBar,children:(0,K.jsx)(L.Z,{placeholder:"Search Previous Ai Generated Ads...",value:ye,id:"searchPreviousQuery",name:"searchPreviousQuery",className:B.historySearchField,onKeyDown:e=>(e=>{"Enter"===e.key&&q(e.target.value)})(e),onChange:e=>{fe(e.target.value),ra(1)},InputProps:{startAdornment:(0,K.jsx)(Ce.Z,{position:"start",children:(0,K.jsx)(Oe.Z,{size:18,style:{color:"#808080"}})})}})}),(0,K.jsxs)(A.Z,{className:B.dateRangeSelector,onClick:e=>{if(e.target.closest&&!e.target.closest(".MuiSelect-root")){const e=document.querySelector("#dateRangeSelector .MuiSelect-root");e&&e.click()}},children:[(0,K.jsx)(Ue.Z,{size:16,color:"#808080"}),(0,K.jsx)(A.Z,{style:{flex:1},children:(0,K.jsx)(He.Z,{startDate:aa,endDate:sa,id:"dateRangeSelector",name:"dateRangeSelector",onChange:(e,t)=>
2{ia(e),na(t),ra(1)}})})]})]}),(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"16px 24px",borderBottom:"1px solid #E8E8E8",backgroundColor:"#fafafa",position:"sticky",top:"80px",zIndex:9},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:8},children:[(0,K.jsx)(I.Z,{variant:"caption",style:{color:"#666",fontSize:"12px"},children:"Show:"}),(0,K.jsxs)(Ie.Z,{value:la,onChange:e=>(da(e.target.value),void ra(1)),size:"small",variant:"outlined",style:{minWidth:"100px",height:"32px",fontSize:"12px",paddingRight:"24px"},children:[(0,K.jsx)(de.Z,{value:5,style:{paddingRight:"16px"},children:"5 per page"}),(0,K.jsx)(de.Z,{value:10,style:{paddingRight:"16px"},children:"10 per page"}),(0,K.jsx)(de.Z,{value:25,style:{paddingRight:"16px"},children:"25 per page"}),(0,K.jsx)(de.Z,{value:50,style:{paddingRight:"16px"},children:"50 per page"})]})]}),(0,K.jsx)(ut.Z,{count:Math.ceil(ea/la),color:"primary",size:"small",shape:"rounded",page:oa,onChange:(e,t)=>{ra(t)},style:{"& .MuiPaginationItem-root":{fontSize:"12px",minWidth:"32px",height:"32px"}}})]}),Kt?(0,K.jsx)(A.Z,{className:B.historyLoadingContainer,children:(0,K.jsx)(k.Z,{size:24})}):(0,K.jsx)(A.Z,{className:B.historyContainer,children:(()=>{const{data:e}={data:Xt,total:ea},i=e.reduce(((e,t)=>{const a=new Date(t.createdAt).toLocaleDateString("en-GB");return e[a]||(e[a]=[]),e[a].push(t),e}),{});return Object.entries(i).map((e=>{let[i,s]=e;return(0,K.jsx)(A.Z,{id:i,name:i,children:s.map(((e,s)=>{const n=[...(e.imageResult||[]).map((e=>({...e,type:"image",url:e.url}))),...(e.videoResult||[]).map((e=>{var t,a;return{...e,type:"video",url:(null===(t=e.url)||void 0===t?void 0:t.video_url)||e.url,thumbnail:null===(a=e.url)||void 0===a?void 0:a.first_frame_url}}))];return(0,K.jsx)(st,{images:n,promptId:e._id,prompt:e.userPrompt,timestamp:e.createdAt,styleType:e.styleType,aspectRatio:e.aspectRatio,styles:vt,mainResolutions:yt,onPromptCopy:e=>{navigator.clipboard.writeText(e).then((()=>{N("Prompt copied to clipboard!","success")})).catch((()=>{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),N("Prompt copied to clipboard!","success")}))},onImageSelect:function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"image",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(pa(null),Et(null),"video"===i){if(!h&&!l)return void N("Video isn't supported here \u2014 pick an image instead","info");mt([null,null,null]),bt([null,null,null]),It([null,null,null]),t&&o&&o(null);const a={publicUrl:e,fileName:"Generated Video",fileType:"VIDEO"};if(h&&h(a),l&&l(a),s&&d){d({publicUrl:s,fileName:"Generated Video Thumbnail",fileType:"IMAGE"})}}else D?D(e):(Ct([null]),kt([null]),Tt([null]),Pt([null]),a&&l&&l(null),s&&d&&d(null),u(e),o({publicUrl:e,fileName:"Generated Image",fileType:"IMAGE"}))},onImageModalOpen:ma,onDownload:xa,selectedIndex:ca,onSelectedIndexChange:pa,onHistoryDrawerToggle:ha},e._id||"".concat(i,"-").concat(s))}))},i)}))})()})]})}),(0,K.jsx)(We.default,{openMediaDialog:ce,toggleMediaDialog:()=>{pe(!ce)},onMediaSelect:fa,mediaType:Se,isFromMetaAds:!0,flowConfiguration:{isEnabled:!0},hideProduct:!1,selectedProducts:[],match:{params:{projectId:"current-project"}}}),(0,K.jsx)(We.default,{openMediaDialog:Ae,toggleMediaDialog:ya,onMediaSelect:Qe?e=>{let t=null;Array.isArray(e)&&e.length>0?t=e[0]:e&&!Array.isArray(e)&&(t=e),t&&d&&d(t),be(!1)}:fa,mediaType:Se,isFromMetaAds:!0,flowConfiguration:{isEnabled:!1},selectedProducts:[],match:{params:{projectId:"current-project"}}}),(0,K.jsx)(Z.Z,{open:Rt,onClose:ga,maxWidth:!1,fullWidth:!0,PaperProps:{style:{backgroundColor:"transparent",boxShadow:"none",maxWidth:"90vw",maxHeight:"95vh",margin:"16px",overflow:"hidden",width:"90vw"}},children:(0,K.jsxs)(A.Z,{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.9)",borderRadius:"12px",padding:"20px",width:"100%",height:"100%",maxWidth:"90vw",maxHeight:"95vh",overflow:"hidden",boxSizing:"border-box"},children:[(0,K.jsxs)(A.Z,{style:{position:"absolute",top:"16px",right:"16px",display:"flex",gap:"12px",zIndex:10},children:[(0,K.jsx)(b.Z,{onClick:e=>{e.preventDefault(),e.stopPropagation();const t=Ut.includes("video")||Ut.includes(".mp4")?".mp4":".jpg",a=_t.includes(".")?_t:"".concat(_t).concat(t);xa(Ut,a)},style:{backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#0a474c",width:"48px",height:"48px",boxShadow:"0 4px 12px rgba(0,0,0,0.3)"},children:(0,K.jsx)(Me,{size:24})}),(0,K.jsx)(b.Z,{onClick:e=>{e.preventDefault(),e.stopPropagation(),ga()},style:{backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#0a474c",width:"48px",height:"48px",boxShadow:"0 4px 12px rgba(0,0,0,0.3)"},children:(0,K.jsx)(Le.Z,{size:24})})]}),Vt.length>1&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(b.Z,{onClick:e=>{e.preventDefault(),e.stopPropagation(),(()=>{if(Vt.length>1){const e=0===Ht?Vt.length-1:Ht-1;Gt(e),zt(Vt[e]),Wt("Generated Image ".concat(e+1))}})()},style:{position:"absolute",left:"16px",top:"50%",transform:"translateY(-50%)",backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#0a474c",width:"48px",height:"48px",boxShadow:"0 4px 12px rgba(0,0,0,0.3)",zIndex:10},children:(0,K.jsx)(ze.Z,{size:24})}),(0,K.jsx)(b.Z,{onClick:e=>{e.preventDefault(),e.stopPropagation(),(()=>{if(Vt.length>1){const e=(Ht+1)%Vt.length;Gt(e),zt(Vt[e]),Wt("Generated Image ".concat(e+1))}})()},style:{position:"absolute",right:"16px",top:"50%",transform:"translateY(-50%)",backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#0a474c",width:"48px",height:"48px",boxShadow:"0 4px 12px rgba(0,0,0,0.3)",zIndex:10},children:(0,K.jsx)(_e.Z,{size:24})})]}),(0,K.jsx)(A.Z,{style:{display:"flex",justifyContent:"center",alignItems:"center",width:"100%",height:"100%",maxWidth:"85vw",maxHeight:"calc(90vh - 120px)",overflow:"visible",position:"relative",margin:"0 auto"},children:Ut.includes("video")||Ut.includes(".mp4")?(0,K.jsx)("video",{src:Ut,controls:!0,style:{maxWidth:"85vw",maxHeight:"80vh",width:"auto",height:"auto",objectFit:"contain",borderRadius:"8px"}}):(0,K.jsx)("img",{src:Ut,alt:_t,style:{maxWidth:"85vw",maxHeight:"80vh",width:"auto",height:"auto",objectFit:"contain",borderRadius:"8px",boxShadow:"0 8px 32px rgba(0,0,0,0.3)",display:"block"}})}),(0,K.jsxs)(A.Z,{style:{display:"flex",flexDirection:"column",alignItems:"center",marginTop:"16px",width:"80%"},children:[Vt.length>1&&(0,K.jsxs)(I.Z,{variant:"body2",style:{color:"rgba(255, 255, 255, 0.8)",marginBottom:"4px",fontSize:"14px"},children:[Ht+1," of ",Vt.length]}),(0,K.jsx)(I.Z,{variant:"h6",style:{color:"white",textAlign:"center",fontWeight:500,textShadow:"0 2px 4px rgba(0,0,0,0.5)",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_t})]})]})}),(0,K.jsx)(ht.A9,{open:qt.open,onClose:()=>{Yt({open:!1,message:""})},message:qt.message,anchorOrigin:{vertical:"bottom",horizontal:"center"}}),(0,K.jsx)(je.ZP,{anchor:"right",onClose:()=>et(!1),PaperProps:{style:{width:window.innerWidth>768?"600px":"100vw",maxWidth:"100vw",backgroundColor:"#ffffff",boxShadow:"-4px 0 20px rgba(0, 0, 0, 0.1)",zIndex:1e3}},BackdropProps:{style:{zIndex:999}},ModalProps:{style:{zIndex:1e3}},children:(0,K.jsxs)(A.Z,{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px 12px 8px 24px",boxShadow:"0px 4px 8px #f3efef"},children:[(0,K.jsx)(I.Z,{variant:"h4",style:{fontWeight:600},children:"Purchase AI Credits"}),(0,K.jsx)(b.Z,{onClick:()=>et(!1),style:{padding:"8px"},children:(0,K.jsx)(Le.Z,{size:24})})]}),(0,K.jsx)(A.Z,{style:{padding:"0px 24px",paddingTop:"12px"},children:(0,K.jsxs)(I.Z,{variant:"h6",style:{fontSize:"12px"},children:["AI credits are used to power AI-generated content creation, including:",(0,K.jsx)("br",{}),"\u2022 AI-generated ad creatives and videos",(0,K.jsx)("br",{}),"\u2022 AI-powered content optimization",(0,K.jsx)("br",{}),"\u2022 AI-driven audience targeting and insights"]})}),(0,K.jsx)(A.Z,{style:{padding:"24px 16px",flex:1,overflow:"auto",backgroundColor:"#f9f8f873",maxHeight:"calc(100vh - 140px)"},children:(0,K.jsx)(gt.default,{showSnackbar:e=>{console.log("Snackbar:",e)},closeDialog:()=>et(!1),assistantDetails:p,isFromAdsMediaSection:!0}
2)})]})},3333)]})}var bt=a(98456),St=a(51505),It=a(24241),jt=a(87210),Ct=a(91730),wt=a(82294),kt=a(31063),Zt=a(72198);const Tt=10,Dt=e=>"whatsapp_status"!==e,Pt=function(){return{mediaType:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"image",imageUrl:"",videoUrl:"",headline:"",description:"",websiteUrl:""}},Bt="#0a474c",Et="undefined"!==typeof Symbol?Symbol("carouselCardKey"):"__carouselCardKey";let Nt=0;const Lt=e=>(void 0===e[Et]&&(e[Et]="card-".concat(Nt++)),e[Et]),Ft=(0,Se.Z)((e=>({list:{maxHeight:480,overflowY:"auto",overflowX:"hidden",padding:"2px 4px 2px 2px",scrollBehavior:"smooth","&::-webkit-scrollbar":{width:8},"&::-webkit-scrollbar-track":{background:"#f1f3f3",borderRadius:8},"&::-webkit-scrollbar-thumb":{background:"rgba(10, 71, 76, 0.25)",borderRadius:8,"&:hover":{background:"rgba(10, 71, 76, 0.45)"}}},emptyList:{boxSizing:"border-box",minHeight:270,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:16,border:"1px dashed #d5dcdb",borderRadius:8,backgroundColor:"#f7f8f8"},emptyListIcon:{fontSize:32,color:"rgba(10, 71, 76, 0.35)"},accordion:{marginBottom:10,borderRadius:8,border:"1px solid #e3e7e7",boxSizing:"border-box",boxShadow:"none","&:before":{display:"none"},"&$accordionExpanded":{margin:0,marginBottom:10}},accordionExpanded:{},accordionDragging:{borderColor:Bt,boxShadow:"0 6px 16px rgba(10, 71, 76, 0.18)"},accordionActivePreview:{borderColor:"#2f7d52",borderWidth:1.5},accordionSummary:{minHeight:44,"& .MuiAccordionSummary-content":{display:"flex",alignItems:"center",overflow:"hidden",gap:8}},dragHandle:{display:"flex",alignItems:"center",marginRight:4},mediaTypeBadge:{flex:"0 0 auto",fontSize:"0.65rem",padding:"2px 8px",borderRadius:10,backgroundColor:"#f1f3f3",color:e.palette.text.secondary,whiteSpace:"nowrap",textTransform:"capitalize"},cardPreviewText:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},removeButton:{padding:2},accordionDetails:{display:"flex",flexDirection:"column",paddingTop:0},cardColumns:{display:"flex",gap:16,alignItems:"flex-start"},mediaColumn:{flex:"0 0 38%",minWidth:0,maxWidth:220},mediaColumnNarrow:{flex:"0 0 26%",minWidth:0,maxWidth:160},fieldsColumn:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},mediaBox:{position:"relative",height:160,borderRadius:6,overflow:"hidden",backgroundColor:"#f7f8f8",display:"flex",alignItems:"center",justifyContent:"center"},mediaClickTarget:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},mediaClearButton:{position:"absolute",top:2,right:2,padding:2,backgroundColor:"rgba(255,255,255,0.85)","&:hover":{backgroundColor:"#fff"}},mediaImage:{width:"100%",height:"100%",objectFit:"cover",display:"block"},mediaVideo:{width:"100%",height:"100%",objectFit:"cover",display:"block",backgroundColor:"#000"},fieldLabelRow:{display:"flex",justifyContent:"space-between",alignItems:"center"},fieldLabelActions:{display:"flex",alignItems:"center",gap:4},headerActions:{display:"flex",alignItems:"center",gap:8},addButton:{backgroundColor:e.palette.primary.main,color:"#fff",textTransform:"none","&:hover":{backgroundColor:e.palette.primary.dark}},aiButton:{backgroundColor:e.palette.primary.main,color:"#fff",textTransform:"none","&:hover":{backgroundColor:e.palette.primary.dark}},applyToAllButton:{color:Bt,textTransform:"none",fontSize:"0.7rem",padding:"0 4px",minWidth:"auto",whiteSpace:"nowrap","&.Mui-disabled":{color:e.palette.text.disabled}}}))),Mt={width:"100%"},Rt={padding:"5px 8px",fontSize:"0.75rem",lineHeight:"16px"},Ot=e=>{let{label:t,mediaKind:a,mediaUrl:i,disabled:s,onOpenPicker:n,onUrlChange:o,urlPlaceholder:l}=e;const d=Ft(),[c,p]=(0,r.useState)(!1),u="video"===a,h=Boolean(i);return s?(0,K.jsx)(A.Z,{mb:1,children:(0,K.jsx)(A.Z,{className:d.mediaBox,px:1,children:(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",align:"center",children:"Media locked while live"})})}):(0,K.jsxs)(A.Z,{mb:1,children:[(0,K.jsxs)(A.Z,{className:d.mediaBox,children:[(0,K.jsx)(A.Z,{className:d.mediaClickTarget,onClick:n,title:"Cho
2ose ".concat(t),children:h?u?(0,K.jsx)("video",{src:"".concat(i,"#t=0.1"),className:d.mediaVideo,muted:!0,playsInline:!0,preload:"metadata"}):(0,K.jsx)("img",{src:i,alt:"Card ".concat(t),className:d.mediaImage}):(0,K.jsxs)(A.Z,{display:"flex",flexDirection:"column",alignItems:"center",children:[u?(0,K.jsx)(jt.Z,{style:{color:"rgba(10, 71, 76, 0.35)",fontSize:24}}):(0,K.jsx)(Ct.Z,{style:{color:"rgba(10, 71, 76, 0.35)",fontSize:24}}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{fontSize:"0.65rem"},children:"Add ".concat(t)})]})}),h&&(0,K.jsx)(b.Z,{size:"small",className:d.mediaClearButton,onClick:()=>o(""),title:"Remove ".concat(t),children:(0,K.jsx)(ct.Z,{style:{fontSize:14}})})]}),(0,K.jsx)(S.Z,{component:"button",variant:"caption",onClick:()=>p((e=>!e)),style:{color:Bt,display:"block",marginTop:4},children:c?"Hide URL field":"Or paste a URL instead"}),c&&(0,K.jsx)(L.Z,{variant:"outlined",size:"small",fullWidth:!0,placeholder:l,onChange:e=>o(e.target.value),style:{...Mt,marginTop:4},inputProps:{style:Rt}})]})},Ut=e=>{var t;let{cards:a=[],adTypeValue:i,disabled:s=!1,assistantId:n,assistantDetails:o,updateAssistantAdCredits:l,updateAssistantStore:d,activePreviewIndex:c,onCardsChange:p}=e;const u=Ft(),h="website_traffic"===i||"website_to_whatsapp"===i,[m,g]=(0,r.useState)(null),[x,v]=(0,r.useState)(!1),[y,f]=(0,r.useState)(0),{showSnackbar:S}=(0,ht.Ds)(),{isAiSensy:j}=(0,Y.K)(),C=(0,r.useRef)(null),k=(0,r.useRef)([]),Z=(0,r.useRef)(null),T=(0,r.useMemo)((()=>a.map(((e,t)=>e.imageUrl||e.videoUrl?null:t)).filter((e=>null!==e))),[a]),D=Math.max(Tt-(a.length-T.length),0),P=(0,r.useMemo)((()=>{const e={};return a.forEach(((t,a)=>{t.imageUrl&&(e[t.imageUrl]=a+1),t.videoUrl&&(e[t.videoUrl]=a+1)})),e}),[a]);(0,r.useEffect)((()=>{(e=>{const t=C.current,a=k.current[e];if(!t||!a)return;const i=t.getBoundingClientRect(),s=a.getBoundingClientRect(),n=s.top-i.top+t.scrollTop,o=n+s.height;n<t.scrollTop?t.scrollTop=n:o>t.scrollTop+t.clientHeight&&(t.scrollTop=o-t.clientHeight)})(null!==c&&void 0!==c?c:0)}),[c,a.length]);const B=(e,t)=>{p(a.map(((a,i)=>i===e?{...a,...t}:a)))},E=()=>{const e=a[0];p(a.map(((t,a)=>0===a?t:{...t,headline:e.headline,description:e.description})))},N=m?"thumbnail"===m.field||"video"!==(null===(t=a[m.index])||void 0===t?void 0:t.mediaType)?"IMAGE":"VIDEO":"IMAGE";return(0,K.jsxs)(A.Z,{children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1,children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"h5",children:"Cards"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:a.length>0?"".concat(a.length," of ").concat(Tt," \u2014 drag to reorder"):"0 of ".concat(Tt)})]}),(0,K.jsxs)(A.Z,{className:u.headerActions,children:[(0,K.jsx)(w.Z,{variant:"contained",startIcon:(0,K.jsx)(ce.Z,{}),onClick:()=>v(!0),disabled:s||D<=0,size:"small",className:u.addButton,children:"Add Images & Videos"}),j&&(0,K.jsx)(w.Z,{variant:"contained",startIcon:(0,K.jsx)(we.Z,{size:15}),onClick:()=>{const e=Z.current;if(null===e||void 0===e||!e.scrollIntoView)return;const t=e.getBoundingClientRect().top;e.scrollIntoView({behavior:"smooth",block:"start"}),setTimeout((()=>{Z.current&&Z.current.getBoundingClientRect().top===t&&Z.current.scrollIntoView({block:"start"})}),250)},size:"small",className:u.aiButton,children:"Generate Images with AI"})]})]}),0===a.length?(0,K.jsxs)(A.Z,{className:u.emptyList,children:[(0,K.jsx)(me.Z,{className:u.emptyListIcon}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",align:"center",children:"Add at least 2 images or videos to build your carousel"})]}):(0,K.jsx)(Zt.Z5,{onDragEnd:e=>{const{destination:t,source:i}=e;if(!t)return;const s=Array.from(a),[n]=s.splice(i.index,1);s.splice(t.index,0,n),p(s)},children:(0,K.jsx)(Zt.bK,{droppableId:"carouselCards",type:"CAROUSEL_CARD",children:e=>(0,K.jsxs)(A.Z,{...e.droppableProps,ref:t=>{e.innerRef(t),C.current=t},className:u.list,children:[a.map(((e,t)=>(0,K.jsx)(Zt._l,{draggableId:Lt(e),index:t,isDragDisabled:s,children:(i,n)=>(0,K.jsxs)(bt.Z,{ref:e=>{i.innerRef(e),k.current[t]=e},...i.draggableProps,expanded:y===t,onChange:(e,a)=>f(a?t:null),classes:{expanded:u.accordionExpanded},className:"".concat(u.accordion," ").concat(n.isDragging?u.accordionDragging:""," ").concat(t===c?u.accordionActivePreview:""),style:i.draggableProps.style,TransitionProps:{unmountOnExit:!1},children:[(0,K.jsxs)(St.Z,{expandIcon:(0,K.jsx)(wt.Z,{}),className:u.accordionSummary,children:[(0,K.jsx)(A.Z,{...i.dragHandleProps,className:u.dragHandle,style:{cursor:s?"default":"grab"},children:(0,K.jsx)(kt.Z,{fontSize:"small",color:"disabled"})}),(0,K.jsx)(I.Z,{variant:"body2",noWrap:!0,children:"Card ".concat(t+1)}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",className:u.cardPreviewText,children:e.headline||"Untitled"}),(0,K.jsx)(I.Z,{variant:"caption",className:u.mediaTypeBadge,children:"video"===e.mediaType?"Video":"Image"}),(0,K.jsx)(b.Z,{size:"small",onClick:e=>{e.stopPropagation(),(e=>{p(a.filter(((t,a)=>a!==e)))})(t)},disabled:s,title:"Remove card",className:u.removeButton,children:(0,K.jsx)(ct.Z,{style:{fontSize:16}})})]}
2),(0,K.jsx)(It.Z,{className:u.accordionDetails,children:(0,K.jsxs)(A.Z,{className:u.cardColumns,children:["video"===e.mediaType?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(A.Z,{className:u.mediaColumnNarrow,children:(0,K.jsx)(Ot,{label:"video",mediaKind:"video",mediaUrl:e.videoUrl,disabled:s,onOpenPicker:()=>g({index:t,field:"media"}),onUrlChange:e=>B(t,{videoUrl:e}),urlPlaceholder:"Video URL"})}),(0,K.jsx)(A.Z,{className:u.mediaColumnNarrow,children:(0,K.jsx)(Ot,{label:"thumbnail",mediaKind:"image",mediaUrl:e.imageUrl,disabled:s,onOpenPicker:()=>g({index:t,field:"thumbnail"}),onUrlChange:e=>B(t,{imageUrl:e}),urlPlaceholder:"Thumbnail URL"})})]}):(0,K.jsx)(A.Z,{className:u.mediaColumn,children:(0,K.jsx)(Ot,{label:"image",mediaKind:"image",mediaUrl:e.imageUrl,disabled:s,onOpenPicker:()=>g({index:t,field:"media"}),onUrlChange:e=>B(t,{imageUrl:e}),urlPlaceholder:"Image URL"})}),(0,K.jsxs)(A.Z,{className:u.fieldsColumn,children:[(0,K.jsxs)(A.Z,{className:u.fieldLabelRow,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Headline"}),(0,K.jsxs)(A.Z,{className:u.fieldLabelActions,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"".concat((e.headline||"").length,"/").concat(40)}),0===t&&(0,K.jsx)(w.Z,{size:"small",onClick:E,disabled:s||!((e.headline||"").length>1||(e.description||"").length>1),className:u.applyToAllButton,children:"Apply to all cards"})]})]}),(0,K.jsx)(L.Z,{variant:"outlined",size:"small",fullWidth:!0,value:e.headline||"",onChange:e=>B(t,{headline:e.target.value.slice(0,40)}),style:{...Mt,marginBottom:6},inputProps:{style:Rt}}),(0,K.jsxs)(A.Z,{className:u.fieldLabelRow,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Description"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"".concat((e.description||"").length,"/").concat(30)})]}),(0,K.jsx)(L.Z,{variant:"outlined",size:"small",fullWidth:!0,value:e.description||"",onChange:e=>B(t,{description:e.target.value.slice(0,30)}),style:{...Mt,marginBottom:h?6:0},inputProps:{style:Rt}}),h&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Website URL"}),(0,K.jsx)(L.Z,{variant:"outlined",size:"small",fullWidth:!0,placeholder:"https://",value:e.websiteUrl||"",onChange:e=>B(t,{websiteUrl:e.target.value}),disabled:s,style:Mt,inputProps:{style:Rt}})]})]})]})})]})},Lt(e)))),e.placeholder]})})}),(0,K.jsx)("div",{ref:Z,style:{marginTop:16},children:(0,K.jsx)(At,{aiGeneratorOnly:!0,assistantDetails:o,updateAssistantAdCredits:l,updateAssistantStore:d,useButtonLabel:"Add as new card",onUseGeneratedImage:e=>{a.length>=Tt?S("There are already ".concat(Tt," cards in the Carousel"),"warning"):(p([...a,{...Pt("image"),imageUrl:e}]),S("Image added to the carousel","success"))}})}),(0,K.jsx)(We.default,{openMediaDialog:Boolean(m),toggleMediaDialog:()=>g(null),onMediaSelect:e=>{const t=Array.isArray(e)?e[0]:e;if(t&&m){const e=(0,Ae.replaceDomainInData)(t.publicUrl);if("thumbnail"===m.field)B(m.index,{imageUrl:e});else{const t=a[m.index];B(m.index,"video"===(null===t||void 0===t?void 0:t.mediaType)?{videoUrl:e}:{imageUrl:e})}}g(null)},mediaType:N,isFromMetaAds:!0,flowConfiguration:{isEnabled:!1},selectedProducts:[],match:{params:{projectId:n}}}),(0,K.jsx)(We.default,{openMediaDialog:x,toggleMediaDialog:()=>v(!1),onMediaSelect:e=>{const t=(Array.isArray(e)?e:[e]).filter(Boolean);if(v(!1),0===t.length)return;let i=0;const s=a.map(((e,a)=>{if(!T.includes(a)||i>=t.length)return e;const s=t[i++],n="VIDEO"===(null===s||void 0===s?void 0:s.fileType),o=(0,Ae.replaceDomainInData)((null===s||void 0===s?void 0:s.publicUrl)||"");return{...e,mediaType:n?"video":"image",imageUrl:n?"":o,videoUrl:n?o:""}})),n=Math.max(Tt-s.length,0),o=t.slice(i,i+n).map((e=>{const t="VIDEO"===(null===e||void 0===e?void 0:e.fileType),a=(0,Ae.replaceDomainInData)((null===e||void 0===e?void 0:e.publicUrl)||"");return{...Pt(t?"video":"image"),imageUrl:t?"":a,videoUrl:t?a:""}}));p([...s,...o])},mediaType:["IMAGE","VIDEO"],multiSelect:!0,isFromMetaAds:!0,flowConfiguration:{isEnabled:!1},selectedProducts:[],match:{params:{projectId:n}},carouselPlacedCardNumberByUrl:P,getCarouselPendingCardNumber:e=>e<T.length?T[e]+1:a.length+(e-T.length)+1,onRemoveCarouselMedia:e=>{const t=P[e];t&&p(a.filter(((e,a)=>a!==t-1)))},maxSelectable:D,maxSelectableMessage:"You can select up to ".concat(D," more \u2014 a carousel is limited to ").concat(Tt," cards")})]})};var zt=a(56446),_t=a(82277),Wt=a(96083),Ht=a(58167),Gt=a(68809),Vt=a(13188),Qt=a(28037),qt=a(37034),Yt=a(38493),Kt=a(78097),Jt=a(24764),Xt=a(22494),$t=a(48152),ea=a(43593),ta=a(7649),aa=a(36526),ia=a(95470),sa=a(1776),na=a(197
257),oa=a(38394),ra=a(63584),la=a(28348),da=a(58739),ca=a(56342);const pa=e=>({FULL_NAME:(0,K.jsx)($t.Z,{fontSize:"small"}),FIRST_NAME:(0,K.jsx)($t.Z,{fontSize:"small"}),LAST_NAME:(0,K.jsx)($t.Z,{fontSize:"small"}),EMAIL:(0,K.jsx)(ea.Z,{fontSize:"small"}),PHONE:(0,K.jsx)(ta.Z,{fontSize:"small"}),WORK_EMAIL:(0,K.jsx)(ea.Z,{fontSize:"small"}),WORK_PHONE_NUMBER:(0,K.jsx)(ta.Z,{fontSize:"small"}),COMPANY_NAME:(0,K.jsx)(aa.Z,{fontSize:"small"}),JOB_TITLE:(0,K.jsx)(ia.Z,{fontSize:"small"}),STREET_ADDRESS:(0,K.jsx)(sa.Z,{fontSize:"small"}),CITY:(0,K.jsx)(sa.Z,{fontSize:"small"}),STATE:(0,K.jsx)(sa.Z,{fontSize:"small"}),ZIP:(0,K.jsx)(sa.Z,{fontSize:"small"}),COUNTRY:(0,K.jsx)(sa.Z,{fontSize:"small"}),DATE_TIME:(0,K.jsx)(na.Z,{fontSize:"small"}),DATE_OF_BIRTH:(0,K.jsx)(na.Z,{fontSize:"small"}),CUSTOM:(0,K.jsx)($t.Z,{fontSize:"small"})}[e]||(0,K.jsx)($t.Z,{fontSize:"small"})),ua=e=>{if("CUSTOM"===e.type)return e.label||"Custom Question";return{FULL_NAME:"Full Name",FIRST_NAME:"First Name",LAST_NAME:"Last Name",EMAIL:"Email",PHONE:"Phone Number",WORK_EMAIL:"Work Email",WORK_PHONE_NUMBER:"Work Phone",COMPANY_NAME:"Company Name",JOB_TITLE:"Job Title",STREET_ADDRESS:"Street Address",CITY:"City",STATE:"State/Province",ZIP:"Zip/Postal Code",COUNTRY:"Country",DATE_TIME:"Select Date & Time",DATE_OF_BIRTH:"Date of Birth",GENDER:"Gender",MARITIAL_STATUS:"Marital Status",RELATIONSHIP_STATUS:"Relationship Status",MILITARY_STATUS:"Military Status"}[e.type]||e.type},ha=(0,N.Z)((e=>({previewContainer:{display:"flex",justifyContent:"center",padding:e.spacing(2)},previewCard:{width:"100%",maxWidth:320,backgroundColor:"#fff",borderRadius:8,overflow:"hidden",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",display:"flex",flexDirection:"column",minHeight:450},stepNavHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:e.spacing(1,2),borderBottom:"1px solid #e0e0e0",backgroundColor:"#f9f9fb"},navButton:{padding:e.spacing(.5)},content:{flex:1,padding:e.spacing(2),backgroundColor:"#fff",display:"flex",flexDirection:"column",overflow:"auto"},greetingPreview:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",flex:1,padding:e.spacing(2)},questionsPreview:{flex:1},questionPreviewItem:{marginBottom:e.spacing(2)},contactInfoPreview:{marginTop:e.spacing(2)},privacyPreview:{padding:e.spacing(2),textAlign:"center"},emptyState:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:150,backgroundColor:"#F9F9FB",borderRadius:8},questionLabel:{display:"flex",alignItems:"center",gap:6,marginBottom:e.spacing(.5),color:"#666"},TextFieldRoot:{width:"100%",padding:"2px",marginTop:"4px","& input":{width:"calc(100% - 80px)"},background:"rgb(240,240,240)"},inputPadding:{padding:"8px 10px"},optionsPreview:{display:"flex",flexDirection:"column",gap:6,padding:e.spacing(1),backgroundColor:"#F9F9FB",borderRadius:8},optionItem:{display:"flex",alignItems:"center",gap:8},radioCircle:{width:14,height:14,borderRadius:"50%",border:"2px solid #999"},contactInfoField:{marginBottom:e.spacing(1)},thankYouContainer:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-start",flex:1,textAlign:"center",padding:e.spacing(3,2)},logoPlaceholder:{marginBottom:e.spacing(2)},logoCircle:{width:60,height:60,borderRadius:"50%",backgroundColor:"#e0e0e0",display:"flex",alignItems:"center",justifyContent:"center"},thankYouTitle:{fontWeight:600,marginBottom:e.spacing(1.5),fontSize:"1.25rem"},thankYouBody:{marginBottom:e.spacing(2),fontSize:"0.875rem",lineHeight:1.5},divider:{width:"100%",height:1,backgroundColor:"#e0e0e0",margin:e.spacing(2,0)},successConfirmation:{display:"flex",alignItems:"center",gap:6,justifyContent:"center"},infoIcon:{fontSize:16,color:"#999"},fixedButtonContainer:{padding:e.spacing(2),borderTop:"1px solid #e0e0e0",backgroundColor:"#fff"},flowBadge:{display:"flex",alignItems:"center",gap:6,padding:e.spacing(1,2),backgroundColor:"#e8f5e9",borderRadius:16,marginBottom:e.spacing(2)},thankYouButton:{backgroundColor:"#1877F2",color:"#fff",textTransform:"none",borderRadius:8,padding:e.spacing(1.2,3),fontWeight:600,"&:disabled":{backgroundColor:"#1877F2",color:"#fff",opacity:.8}},privacySection:{marginTop:e.spacing(2)}})))((e=>{let{classes:t,formName:a,customQuestions:i=[],contactInfoFields:s=[],verifyPhoneWithOtp:n=!1,privacyPolicyUrl:o,privacyPolicyLinkText:l,thankYouTitle:c,thankYouBody:p,thankYouButtonText:h,thankYouButtonType:m,connectedFlowName:g,previewMode:x="form",builderStep:v=0,greetingHeadline:y="",greetingDescription:f="",greetingEnabled:S=!0}=e;const j=S&&(y||f),C=(j?1:0)+i.length+(s.length>0?1:0)+1,[k,Z]=(0,r.useState)(0);(0,r.useEffect)((()=>{3===v&&Z(C-1)}),[v,C]);let T=!1,D=!1,P=!1,B=!1,E=-1,N=0;return j&&(k===N&&(T=!0),N++),k>=N&&k<N+i.length&&(D=!0,E=k-N),N+=i.length,s.length>0&&(k===N&&(P=!0),N++),k===N&&(B=!0),(0,K.jsx)(A.Z,{className:t.previewContainer,children:(0,K.jsxs)(A.Z,{className:t.previewCard,children:[C>
21&&(0,K.jsxs)(A.Z,{className:t.stepNavHeader,children:[(0,K.jsx)(b.Z,{size:"small",onClick:()=>{k>0&&Z(k-1)},disabled:0===k,className:t.navButton,children:(0,K.jsx)(d.Z,{fontSize:"small"})}),(0,K.jsxs)(I.Z,{variant:"caption",color:"textSecondary",children:[k+1," of ",C]}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>{k<C-1&&Z(k+1)},disabled:k>=C-1,className:t.navButton,children:(0,K.jsx)(u.Z,{fontSize:"small"})})]}),(0,K.jsx)(A.Z,{className:t.content,children:T?(0,K.jsxs)(A.Z,{className:t.greetingPreview,children:[a&&(0,K.jsx)(I.Z,{variant:"h6",style:{marginBottom:16,fontWeight:600,textAlign:"center"},children:a}),y&&(0,K.jsx)(I.Z,{variant:"h6",style:{marginBottom:12,fontWeight:600,textAlign:"center"},children:y}),f&&(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{whiteSpace:"pre-wrap",textAlign:"center"},children:f})]}):D&&E>=0?(0,K.jsx)(K.Fragment,{children:i[E]&&(0,K.jsxs)(A.Z,{className:t.questionPreviewItem,children:[(0,K.jsxs)(A.Z,{className:t.questionLabel,children:[pa(i[E].type),(0,K.jsxs)(I.Z,{variant:"body2",style:{fontWeight:500},children:[ua(i[E]),i[E].isMandatory&&(0,K.jsx)("span",{style:{color:"#f44336"},children:" *"})]})]}),i[E].options&&i[E].options.length>0?(0,K.jsx)(A.Z,{className:t.optionsPreview,children:i[E].options.map(((e,a)=>(0,K.jsxs)(A.Z,{className:t.optionItem,children:[(0,K.jsx)(A.Z,{className:t.radioCircle}),(0,K.jsx)(I.Z,{variant:"body2",children:e.value||"Option ".concat(a+1)})]},a)))}):(0,K.jsx)(L.Z,{variant:"outlined",size:"small",fullWidth:!0,placeholder:ua(i[E]),disabled:!0,classes:{root:t.TextFieldRoot},InputProps:{classes:{input:t.inputPadding}}})]})}):P?(0,K.jsxs)(A.Z,{className:t.contactInfoPreview,children:[(0,K.jsx)(I.Z,{variant:"body2",style:{fontWeight:500,marginBottom:16},children:"Contact Information"}),s.map(((e,a)=>(0,K.jsxs)(A.Z,{className:t.contactInfoField,style:{marginBottom:16},children:[(0,K.jsxs)(A.Z,{className:t.questionLabel,children:[pa(e.type),(0,K.jsxs)(I.Z,{variant:"body2",style:{fontWeight:500},children:[ua({type:e.type}),e.isMandatory&&(0,K.jsx)("span",{style:{color:"#f44336"},children:" *"})]})]}),(0,K.jsx)(L.Z,{variant:"outlined",size:"small",fullWidth:!0,placeholder:ua({type:e.type}),disabled:!0,classes:{root:t.TextFieldRoot},InputProps:{classes:{input:t.inputPadding},endAdornment:(0,K.jsx)(Ce.Z,{position:"end",children:(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{fontSize:"10px"},children:"Auto-filled"})})}}),"PHONE"===e.type&&n&&(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{fontSize:"10px",marginTop:4,display:"block"},children:"Will be verified with OTP"})]},a))),o&&(0,K.jsx)(A.Z,{className:t.privacySection,style:{marginTop:16},children:(0,K.jsxs)(I.Z,{variant:"caption",color:"textSecondary",style:{display:"flex",alignItems:"center",gap:4},children:[(0,K.jsx)(ca.Z,{fontSize:"inherit"}),"By submitting, you agree to our"," ",(0,K.jsx)("a",{href:o,target:"_blank",rel:"noopener noreferrer",style:{color:"#1976D2",textDecoration:"underline"},children:l||"Privacy Policy"})]})})]}):B?(0,K.jsxs)(A.Z,{className:t.thankYouContainer,children:[(0,K.jsx)(A.Z,{className:t.logoPlaceholder,children:(0,K.jsx)(A.Z,{className:t.logoCircle})}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8},children:a||"Company Name"}),(0,K.jsx)(I.Z,{variant:"h6",className:t.thankYouTitle,children:c||"Thanks, you're all set."}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",className:t.thankYouBody,children:p||"You can visit our website or exit the form now."}),(0,K.jsx)(A.Z,{className:t.divider}),(0,K.jsxs)(A.Z,{className:t.successConfirmation,children:[(0,K.jsx)(ca.Z,{className:t.infoIcon}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"You successfully submitted your responses."})]})]}):(0,K.jsx)(A.Z,{className:t.emptyState,children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"No content to preview"})})}),B&&m&&(0,K.jsx)(A.Z,{className:t.fixedButtonContainer,children:(0,K.jsx)(w.Z,{variant:"contained",fullWidth:!0,className:t.thankYouButton,startIcon:(F=m,{VIEW_WEBSITE:(0,K.jsx)(oa.Z,{fontSize:"small"}),WHATSAPP:(0,K.jsx)(ra.Z,{fontSize:"small"}),CALL_BUSINESS:(0,K.jsx)(la.Z,{fontSize:"small"}),DOWNLOAD:(0,K.jsx)(da.Z,{fontSize:"small"})}[F]||(0,K.jsx)(oa.Z,{fontSize:"small"})),disabled:!0,children:h||"View website"})})]})});var F})),ma=()=>"undefined"!==typeof window&&"undefined"!==typeof window.FB,ga=e=>{let{pageId:t}=e;return new Promise(((e,a)=>{if(ma())if(t)try{window.FB.ui({method:"lead_gen",page_id:t},(t=>{if(t&&!t.error_code)t.formID||t.form_id?e({formId:t.formID||t.form_id,formName:t.name||t.formName}):a("Form creation was cancelled");else if(t&&t.error_code){const e=xa(t.error_code,t.error_message);a(e)}else a("Form creation was cancelled")}))}catch(i){a(i.message||"Failed to open lead form dialog")}else a("Page ID is required to create a lead form");else a("Facebook SDK is not loaded. Please refresh the page and try again.")}))},xa=(e,t)=>({100:"Invalid parameter. Please check your Page ID and try again.",190:"Access token has expired. Please reconnect your Facebook account.",200:"You don't have permission to create lead forms for this page.",4:"Application request limit reached. Please try again later.",10:"This feature is not available for your account.",2
2:"An unexpected error occurred. Please try again."}[e]||t||"An error occurred while creating the lead form.");var va=a(65963),ya=a(20681),fa=a(53154),Aa=(a(13098),a(33591));class ba extends r.Component{constructor(e){super(e),this.fetchExistingCampaigns=async()=>{var e,t;const a=this.props.assistantId||(null===(e=this.props.assistantDetails)||void 0===e?void 0:e.assistantId)||(null===(t=this.props.connectProps)||void 0===t?void 0:t.assistantId);if(a){this.setState({isLoadingCampaigns:!0});try{const e=await i.Z.post("".concat(W.URL,"/api/fetch-api-campaigns"),{assistantId:a});e.data&&Array.isArray(e.data)&&this.setState({existingCampaigns:e.data})}catch(s){console.error("Error fetching existing campaigns:",s)}finally{this.setState({isLoadingCampaigns:!1})}}else console.log("Missing assistantId, skipping campaigns fetch")},this.loadAutomationState=e=>{let t=[],a={};e.fallbackParameters&&"object"===typeof e.fallbackParameters&&Object.entries(e.fallbackParameters).forEach((e=>{let[t,i]=e;a["$".concat(t)]=i||""})),e.templateParameters&&e.templateParameters.length>0&&(t=e.templateParameters.map((e=>"field"===e.type?"$".concat(e.fieldKey||""):"custom"===e.type&&e.value||"")));const i=e.campaignName||"",s=this.state.existingCampaigns.find((e=>e.name===i));let n={};e.media&&(n={url:e.media.url||"",publicUrl:e.media.url||"",filename:e.media.filename||""});let o=[];e.cards&&Array.isArray(e.cards)&&e.cards.length>0&&(o=e.cards),this.setState({automationEnabled:e.enabled||!1,automationTemplateName:e.templateName||"",automationCampaignName:i,automationPhoneField:e.phoneField||"phone",automationNameField:e.nameField||"full_name",parameters:t,fallbackParameters:a,media:n,selectedCampaignName:s?i:"",newCampaignExpanded:!s&&!!i,cards:o,carouselIndex:0},(()=>{this.updatePreviewData()})),e.enabled&&e.templateName&&this.fetchTemplates().then((a=>{if(a&&a.length>0){const i=a.find((t=>{var a;return t.name===e.templateName&&"APPROVED"===(null===(a=t.status)||void 0===a?void 0:a.toUpperCase())}));if(i){let e=t;0===t.length&&i.parameters>0&&(e=Array.from({length:i.parameters},(()=>""))),this.setState({selectedTemplate:i,parameters:e},(()=>{this.updatePreviewData()}))}}}))},this.fetchTemplates=async()=>{var e,t;const a=this.props.assistantId||(null===(e=this.props.assistantDetails)||void 0===e?void 0:e.assistantId)||(null===(t=this.props.connectProps)||void 0===t?void 0:t.assistantId);if(!a)return console.log("Missing assistantId, skipping templates fetch"),Promise.resolve([]);this.setState({isLoadingTemplates:!0});try{const e=await i.Z.post("".concat(W.URL,"/api/templates"),{assistantId:a},{responseType:"text"});let t=[];if(e.data&&e.data.trim()){const a=e.data.trim(),i=a.endsWith(",")?"[".concat(a.substring(0,a.length-1),"]"):"[".concat(a,"]");t=JSON.parse(i)}const s=t.filter((e=>{var t;return!(!e||!e.name)&&"APPROVED"===(null===(t=e.status)||void 0===t?void 0:t.toUpperCase())}));return this.setState({templates:s}),Promise.resolve(s)}catch(s){return console.error("Error fetching templates:",s),Promise.resolve([])}finally{this.setState({isLoadingTemplates:!1})}},this.handleAutomationToggle=e=>{this.setState({automationEnabled:e},(()=>{e&&this.fetchTemplates(),this.updateAutomationInParent()}))},this.handleTemplateSelect=e=>{var t;if(!e)return void this.setState({automationTemplateName:"",automationCampaignName:"",selectedTemplate:null,parameters:[],fallbackParameters:{},media:{},selectedCampaignName:"",cards:[],carouselIndex:0},(()=>{this.updateAutomationInParent()}));const a=this.state.templates.find((t=>{var a;return t.name===e&&"APPROVED"===(null===(a=t.status)||void 0===a?void 0:a.toUpperCase())}));if(!a)return void console.warn('Template "'.concat(e,'" not found or not approved'));const i=a.parameters||0,s=Array.from({length:i},(()=>""));let n=[];"CAROUSEL"===a.type&&null!==(t=a.carouselCards)&&void 0!==t&&t.length&&(n=(0,fa.ni)(a.carouselCards)),this.setState({automationTemplateName:e,automationCampaignName:"LeadForm_".concat(e),selectedTemplate:a,parameters:s,fallbackParameters:{},selectedCampaignName:"",media:{},cards:n,carouselIndex:0},(()=>{this.updatePreviewData(),this.updateAutomationInParent()}))},this.handleCampaignNameChange=e=>{this.setState({automationCampaignName:e.target.value},(()=>{this.updateAutomationInParent()}))},this.handleExistingCampaignSelect=e=>{var t,a,i,s,n;if(!e)return void this.setState({selectedCampaignName:"",automationCampaignName:"",newCampaignExpanded:!1,automationTemplateName:"",selectedTemplate:null,parameters:[],fallbackParameters:{},media:{},cards:[],carouselIndex:0},(()=>{this.updateAutomationInParent()}));const o=this.state.existingCampaigns.find((t=>t.name===e));if(!o)return void this.setState({selectedCampaignName:"",automationCampaignName:"",newCampaignExpanded:!1,automationTemplateName:"",selectedTemplate:null,parameters:[],fallbackParameters:{},media:{},cards:[],carouselIndex:0},(()=>{this.updateAutomationInParent()}));const r=null===(t=o.payload)||void 0===t?void 0:t.templateName;if(!r)return void this.setState({selectedCampaignName:e,automationCampaignName:e,newCampaignExpanded:!1,automationTemplateName:"",selectedTemplate:null,parameters:[],fallbackParameters:{},media:{},cards:[],carouselIndex:0},(()=>{this.updateAutomationInParent()}));const l=this.state.templates.find((e=>{var t;return e.name===r&&"APPROVED"===(null===(t=e.status)||void 0===t?void 0:t.toUpperCase())}));let d=[];if(null!==(a=o.payload)&&void 0!==a&&a.templateParameters&&Array.isArray(o.payload.templateParameters))d=o.payload.templateParameters.map((e=>"field"===e.type?"$".concat(e.fieldKey||""):"custom"===e.type&&e.value||""));else if(l){const e=l.parameters||0;d=Array.from({length:e},(()=>""))}let c={};null!==(i=o.payload)&&void 0!==i&&i.media&&(c={url:o.payload.media.url||"",publicUrl:o.payload.media.url||"",filename:o.payload.media.filename||""});let p=[];null!==(s=o.payload)&&void 0!==s&&s.cards&&Array.isArray(o.payload.cards)?p=o.payload.cards:l&&"CAROUSEL"===l.type&&null!==(n=l.carouselCards)&&void 0!==n&&n.length&&(p=(0,fa.ni)(l.carouselCards)),this.setState({selectedCampaignName:e,automationCampaignName:e,newCampaignExpanded:!1,automationTemplateName:r,selectedTemplate:l||null,parameters:d,fallbackParameters:{},media:c,cards:p,carouselIndex:0},(()=>{this.updatePreviewData(),this.updateAutomationInParent()}))},this.handleCreateNewCampaignClick=()=>{this.setState({newCampaignExpanded:!this.state.newCampaignExpanded,selectedCampaignName:"",automationCampaignName:"",automationTemplateName:"",selectedTemplate:null,parameters:[],fallbackParameters:{},media:{}})},this.toggleMediaDialog=()=>{this.setState({mediaLibraryOpen:!this.state.mediaLibraryOpen})},this.extractFilenameFromUrl=e=>{if(!e)return"media_file";try{const t=e.split("/");return(t[t.length-1]||"media_file").split("?")[0]||"media_file"}catch{return"media_file"}},this.onMediaSelect=e=>{var t;const a=(null===e||void 0===e?void 0:e.publicUrl)||(null===e||void 0===e?void 0:e.url)||"",i={...e,filename:(null===e||void 0===e?void 0:e.filename)||this.extractFilenameFromUrl(a)};if("CAROUSEL"===(null===(t=this.state.selectedTemplate)||void 0===t?void 0:t.type)){const e=JSON.parse(JSON.stringify(this.state.cards||[])),t=e[this.state.carouselIndex];if(t){var s;const i=null===(s=t.components)||void 0===s?void 0:s.find((e=>"HEADER"===e.type));if(i&&i.parameters&&i.parameters.length>0){const t=i.parameters[0].type||i.format||"IMAGE",s=t.toLowerCase();return i.format=t,i.parameters[0][s]?i.parameters[0][s].link=a:i.parameters[0]={type:t,[s]:{link:a}},void this.setState({cards:e,mediaLibraryOpen:!1},(()=>{this.updateAutomationInParent(),this.updatePreviewData()}))}}}this.setState({media:i,mediaLibraryOpen:!1},(()=>{this.updateAutomationInParent(),this.updatePreviewData()}))},this.setCards=e=>{this.setState({cards:e},(()=>{this.updateAutomationInParent(),this.updatePreviewData()}))}
2,this.setCarouselIndex=e=>{this.setState({carouselIndex:e})},this.getAllQuestions=()=>{var e,t;const a=this.props.questions||(null===(e=this.props.parentState)||void 0===e||null===(t=e.leadForm)||void 0===t?void 0:t.questions)||[];return a&&0!==a.length?a.map((e=>{var t;return{key:e.key||(null===(t=e.type)||void 0===t?void 0:t.toLowerCase()),type:e.type,label:e.label||e.type}})):[]},this.getLeadFormAttributes=()=>{var e,t;const a=this.props.questions||(null===(e=this.props.parentState)||void 0===e||null===(t=e.leadForm)||void 0===t?void 0:t.questions)||[];return a&&0!==a.length?a.map((e=>({name:e.key||e.type}))):[]},this.setTemplateMessage=(e,t)=>{this.setState({[e]:t},(()=>{this.updateAutomationInParent()}))},this.getCarouselMediaCount=()=>{const{selectedTemplate:e,cards:t}=this.state;if(!e||"CAROUSEL"!==e.type)return;if(!t||!Array.isArray(t)||0===t.length)return 0;let a=0;return t.forEach((e=>{var t;const i=null===e||void 0===e||null===(t=e.components)||void 0===t?void 0:t.find((e=>{let{type:t}=e;return"HEADER"===t}));if(i&&i.parameters&&i.parameters.length>0){var s,n,o,r,l;const e=i.parameters[0],t=e.type||i.format,d=null===t||void 0===t?void 0:t.toLowerCase(),c=d&&(null===(s=e[d])||void 0===s?void 0:s.link)||(null===(n=e.image)||void 0===n?void 0:n.link)||(null===(o=e.video)||void 0===o?void 0:o.link)||(null===(r=e.document)||void 0===r?void 0:r.link)||(null===(l=e.audio)||void 0===l?void 0:l.link);c&&""!==String(c).trim()&&a++}})),a},this.getAutomationConfig=()=>{const{automationEnabled:e,automationTemplateName:t,automationCampaignName:a,automationPhoneField:i,automationNameField:s,parameters:n,fallbackParameters:o,selectedCampaignName:r,media:l,selectedTemplate:d,cards:c}=this.state;let p={enabled:!1};const u=e=>Object.entries(e||{}).reduce(((e,t)=>{let[a,i]=t;return e[a.startsWith("$")?a.substring(1):a]=i||"",e}),{}),h=e=>e.map((e=>{if("string"===typeof e&&e.startsWith("$")){return{type:"field",fieldKey:e.substring(1)}}return{type:"custom",value:e||""}}));if(e&&r){if(p={enabled:!0,campaignName:r,phoneField:i,nameField:s,fieldMappings:[],templateParameters:h(n),fallbackParameters:u(o)},t&&(p.templateName=t),l&&(l.url||l.publicUrl)){const e=l.publicUrl||l.url||"";p.media={url:e,filename:l.filename||this.extractFilenameFromUrl(e),fileType:(null===d||void 0===d?void 0:d.headerType)||(null===d||void 0===d?void 0:d.type)||"IMAGE"}}"CAROUSEL"===(null===d||void 0===d?void 0:d.type)&&c&&c.length>0&&(p.cards=c)}else if(e&&t){if(p={enabled:!0,templateName:t,campaignName:a||"LeadForm_".concat(t),phoneField:i,nameField:s,fieldMappings:[],templateParameters:h(n),fallbackParameters:u(o)},l&&(l.url||l.publicUrl)){const e=l.publicUrl||l.url||"";p.media={url:e,filename:l.filename||this.extractFilenameFromUrl(e),fileType:(null===d||void 0===d?void 0:d.headerType)||(null===d||void 0===d?void 0:d.type)||"IMAGE"}}"CAROUSEL"===(null===d||void 0===d?void 0:d.type)&&c&&c.length>0&&(p.cards=c)}return p},this.updateAutomationInParent=()=>{const e=this.getAutomationConfig();this.lastEmittedAutomation=e,this.props.onChange?this.props.onChange(e):this.props.changeState&&this.props.changeState("leadFormAutomation",e),this.updatePreviewData()},this.updatePreviewData=()=>{if(this.props.onPreviewDataChange){var e;let t=this.state.selectedTemplate;t&&"CAROUSEL"===t.type&&(null===(e=this.state.cards)||void 0===e?void 0:e.length)>0&&(t={...t,carouselCards:this.state.cards}),this.props.onPreviewDataChange({selectedTemplate:t,parameters:this.state.parameters,media:this.state.media,cards:this.state.cards,carouselIndex:this.state.carouselIndex||0,isHoverPreview:!1})}},this.state={automationEnabled:!1,automationTemplateName:"",automationCampaignName:"",automationPhoneField:"phone",automationNameField:"full_name",templates:[],isLoadingTemplates:!1,selectedTemplate:null,parameters:[],fallbackParameters:{},media:{},cards:[],carouselIndex:0,existingCampaigns:[],isLoadingCampaigns:!1,selectedCampaignName:"",newCampaignExpanded:!1,mediaLibraryOpen:!1,hoveredTemplate:null,templateSearchInput:"",campaignSearchInput:""},this.hoverTimeout=null,this.lastEmittedAutomation=null}componentDidMount(){const e=this.props.automation;e&&this.loadAutomationState(e),this.props.assistantId&&(this.fetchTemplates(),this.fetchExistingCampaigns()),this.props.onGetConfigRef&&this.props.onGetConfigRef(this.getAutomationConfig),this.updatePreviewData()}componentWillUnmount(){this.hoverTimeout&&clearTimeout(this.hoverTimeout)}componentDidUpdate(e,t){const a=this.props.automation,i=e.automation,s=null!==a&&a===this.lastEmittedAutomation;a===i||s||(a&&(a.enabled||a.templateName)?this.loadAutomationState(a):a||this.setState({automationEnabled:!1,automationTemplateName:"",automationCampaignName:"",selectedTemplate:null,parameters:[],fallbackParameters:{},media:{},cards:[],carouselIndex:0},(()=>{this.updatePreviewData()}))),this.props.assistantId&&this.props.assistantId!==e.assistantId&&(this.fetchTemplates(),this.fetchExistingCampaigns()),this.props.onGetConfigRef&&this.props.onGetConfigRef!==e.onGetConfigRef&&this.props.onGetConfigRef(this.getAutomationConfig),t.selectedTemplate===this.state.selectedTemplate&&t.parameters===this.state.parameters&&t.media===this.state.media&&t.cards===this.state.cards&&t.carouselIndex===this.state.carouselIndex||this.updatePreviewData()}render(){var e,t,a,i;const{classes:s}=this.props;if(this.props.hideIfNoForm&&(!this.props.questions||0===this.props.questions.length))return(0,K.jsx)(A.Z,{p:2,children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"Please select a lead form in the Ad Creative section to configure automation."})});const n=this.state.selectedTemplate&&(this.state.newCampaignExpanded||this.state.selectedCampaignName);return(0,K.jsx)(f.Z,{container:!0,spacing:2,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{checked:this.state.automationEnabled,onChange:e=>this.handleAutomationToggle(e.target.checked),color:"primary"}),label:(0,K.jsx)(I.Z,{variant:"body2",children:"Enable Automation"}),style:{marginBottom:16}}),this.state.automationEnabled&&(0,K.jsx)(A.Z,{children:(0,K.jsxs)(f.Z,{container:!0,spacing:2,alignItems:"flex-start",children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",gap:"16px"},children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,md:6,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8},children:"Select Existing Campaign"}),this.state.isLoadingCampaigns?(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",children:[(0,K.jsx)(k.Z,{size:16}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginLeft:8}
2,children:"Loading campaigns..."})]}):(0,K.jsx)(q.ZP,{clearOnEscape:!0,options:this.state.existingCampaigns.filter((e=>{const t=(this.state.campaignSearchInput||"").toLowerCase();return(e.name||"").toLowerCase().includes(t)})).slice(0,100).map((e=>e.name)),value:this.state.selectedCampaignName||null,onChange:(e,t,a)=>{"select-option"!==a&&"clear"!==a||(this.handleExistingCampaignSelect(t||""),this.setState({campaignSearchInput:""}))},onInputChange:(e,t,a)=>{"input"===a&&this.setState({campaignSearchInput:t})},popupIcon:(0,K.jsx)(va.Z,{style:{fontSize:"20px"}}),renderInput:e=>(0,K.jsx)(L.Z,{...e,fullWidth:!0,variant:"outlined",style:{marginTop:"0px !important"},classes:{root:s.TextFieldRoot},InputProps:{...e.InputProps,classes:{input:s.inputPadding}},placeholder:"Select an existing campaign"})})]}),(0,K.jsxs)(f.Z,{item:!0,xs:12,md:6,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8},children:"Or Create New Campaign"}),(0,K.jsx)(w.Z,{variant:"outlined",color:"primary",onClick:this.handleCreateNewCampaignClick,fullWidth:!0,style:{textTransform:"none",height:"40px"},children:"+ Create New Campaign"})]})]}),(this.state.newCampaignExpanded||this.state.selectedCampaignName)&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,style:{marginTop:16},children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8},children:this.state.selectedCampaignName?"Template (Change Template)":"Select Template"}),this.state.isLoadingTemplates?(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",children:[(0,K.jsx)(k.Z,{size:16}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginLeft:8},children:"Loading templates..."})]}):(0,K.jsx)(q.ZP,{clearOnEscape:!0,options:this.state.templates.filter((e=>{var t;if("APPROVED"!==(null===(t=e.status)||void 0===t?void 0:t.toUpperCase()))return!1;const a=(this.state.templateSearchInput||"").toLowerCase();return(e.name||"").toLowerCase().includes(a)})).slice(0,100).map((e=>e.name)),getOptionDisabled:e=>{const t=this.state.templates.find((t=>t.name===e));return this.props.isMarketingDisabled&&(0,Aa.YI)(t)},value:this.state.automationTemplateName||null,onChange:(e,t,a)=>{"select-option"!==a&&"clear"!==a||(this.handleTemplateSelect(t||""),this.setState({templateSearchInput:""}))},onInputChange:(e,t,a)=>{"input"===a&&this.setState({templateSearchInput:t})},popupIcon:(0,K.jsx)(va.Z,{style:{fontSize:"20px"}}),renderInput:e=>(0,K.jsx)(L.Z,{...e,fullWidth:!0,variant:"outlined",classes:{root:s.TextFieldRoot},InputProps:{...e.InputProps,classes:{input:s.inputPadding}},placeholder:"Select a template"}),renderOption:e=>{var t,a;const i=this.state.templates.find((t=>{var a;return t.name===e&&"APPROVED"===(null===(a=t.status)||void 0===a?void 0:a.toUpperCase())}));if(!i)return null;const s=this.props.isMarketingDisabled&&(0,Aa.YI)(i),n=(0,K.jsx)(A.Z,{onMouseEnter:e=>{this.hoverTimeout&&clearTimeout(this.hoverTimeout),this.hoverTimeout=setTimeout((()=>{if(this.props.onPreviewDataChange){var e;const t=i.parameters||0,a=Array.from({length:t},(()=>"Sample"));let s=[];"CAROUSEL"===i.type&&null!==(e=i.carouselCards)&&void 0!==e&&e.length&&(s=(0,fa.ni)(i.carouselCards));let n={};i.headerType&&i.headerMedia&&(n={url:i.headerMedia,publicUrl:i.headerMedia,filename:i.headerMedia.split("/").pop()||"media_file"}),this.props.onPreviewDataChange({selectedTemplate:i,parameters:a,media:n,cards:s,carouselIndex:0,isHoverPreview:!0})}this.setState({hoveredTemplate:i})}),200)},onMouseLeave:()=>{this.hoverTimeout&&clearTimeout(this.hoverTimeout),this.hoverTimeout=setTimeout((()=>{this.updatePreviewData(),this.setState({hoveredTemplate:null})}),200)},style:{display:"flex",alignItems:"center",width:"100%",padding:"8px 16px"},children:(0,K.jsx)(I.Z,{variant:"body1",noWrap:!0,style:{flex:1},children:e})});return(0,K.jsx)(Aa.P$,{show:s,projectId:null===(t=this.props.match)||void 0===t||null===(a=t.params)||void 0===a?void 0:a.projectId,history:this.props.history,children:n})}})]}),(0,K.jsxs)(f.Z,{item:!0,xs:12,style:{marginTop:16},children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8},children:"Campaign Name"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:s.TextFieldRoot},InputProps:{classes:{input:s.inputPadding}},placeholder:"LeadForm_TemplateName",value:this.state.automationCampaignName,onChange:this.handleCampaignNameChange,disabled:!!this.state.selectedCampaignName&&!this.state.newCampaignExpanded}),this.state.selectedCampaignName&&!this.state.newCampaignExpanded&&(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginTop:4,display:"block"},children:"To edit campaign name, create a new campaign or clear the existing campaign selection"})]})]}),n&&"CAROUSEL"===(null===(e=this.state.selectedTemplate)||void 0===e?void 0:e.type)&&(null===(t=this.state.cards)||void 0===t?void 0:t.length)>0&&(0,K.jsx)(f.Z,{item:!0,xs:12,children:(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",mb:2,p:2,style:{backgroundColor:"#f5f5f5",borderRadius:8},children:[(0,K.jsx)(w.Z,{variant:"outlined",size:"small",disabled:0===this.state.carouselIndex,onClick:()=>this.setCarouselIndex(this.state.carouselIndex-1),children:"Previous"}),(0,K.jsxs)(I.Z,{variant:"body2",color:"textSecondary",children:["Card ",this.state.carouselIndex+1," of ",this.state.cards.length]}),(0,K.jsx)(w.Z,{variant:"outlined",size:"small",disabled:this.state.carouselIndex>=this.state.cards.length-1,onClick:()=>this.setCarouselIndex(this.state.carouselIndex+1),children:"Next"})]})}),n&&(0,K.jsx)(f.Z,{item:!0,xs:12,style:{marginTop:16},children:(0,K.jsx)(ya.Z,{selectedTemplate:this.state.selectedTemplate,attributes:this.getLeadFormAttributes(),parameters:this.state.parameters,fallbackParameters:this.state.fallbackParameters,setTemplateMessage:this.setTemplateMessage,media:this.state.media,onMediaSelect:this.onMediaSelect,toggleMediaDialog:this.toggleMediaDialog,cards:this.state.cards,setCards:this.setCards,carouselIndex:this.state.carouselIndex,mediaCount:this.getCarouselMediaCount()})})]})}),this.state.mediaLibraryOpen&&(0,K.jsx)(We.default,{openMediaDialog:this.state.mediaLibraryOpen,toggleMediaDialog:this.toggleMediaDialog,onMediaSelect:this.onMediaSelect,mediaType:(null===(a=this.state.selectedTemplate)||void 0===a?void 0:a.headerType)||(null===(i=this.state.selectedTemplate)||void 0===i?void 0:i.type)||"IMAGE",isFromMetaAds:!0})]})})}}const Sa=e=>({TextFieldRoot:{width:"100%",padding:"2px",marginTop:"0px !important","& input":{width:"calc(100% - 80px)",marginTop:"0px !important"},background:"rgb(240,240,240)"},inputPadding:{padding:"12px 10px"}}),Ia=(0,o.connect)((e=>{var t,a,i;return{isMarketingDisabled:Boolean(null===(t=e.assistantDetails)||void 0===t||null===(a=t.data)||void 0===a||null===(i=a.optSetting)||void 0===i?void 0:i.disableMarketingMessaging)}}),null)((0,l.withRouter)((0,N.Z)(Sa)(ba)));(0,o.connect)((e=>{var t,a,i,s,n,o,r,l,d;return{assistantDetails:null===(t=e.assistantDetails)||void 0===t?void 0:t.data,assistantId:(null===(a=e.login)||void 0===a||null===(i=a.user)||void 0===i?void 0:i.assistantId)||(null===(s=e.assistantDetails)||void 0===s||null===(n=s.data)||void 0===n?void 0:n.assistantId),pageDetails:null===(o=e.pageDetails)||void 0===o?void 0:o.pageDetails,isMarketingDisabled:Boolean(null===(r=e.assistantDetails)||void 0===r||null===(l=r.data)||void 0===l||null===(d=l.optSetting)||void 0===d?void 0:d.disableMarketingMessaging)}}),null)((0,l.withRouter)((0,N.Z)(Sa)(ba)));var ja=a(71533);const Ca=function(){return"".concat(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"id","_").concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},wa=()=>{const e=new Date,t=e.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),a=e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!0});return"Untitled Form ".concat(t," ").concat(a)},ka=()=>Xt.dh.map((e=>({type:e.value,enabled:"FULL_NAME"===e.value||"PHONE"===e.value,isMandatory:"FULL_NAME"===e.value||"PHONE"===e.value,locked:e.locked||!1,mappedParameter:null})));class Za extends r.Component{constructor(e){var t;super(e),t=this,this.fetchAvailableParameters=async()=>{const{assistantId:e}=this.props;if(e){this.setState({isLoadingParameters:!0});try{var t;const s=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/parameters"),{params:{assistantId:e}});if(null!==(t=s.data)&&void 0!==t&&t.status){var a;const e=(null===(a=s.data.data)||void 0===a?void 0:a.all)||[];this.setState({availableParameters:e})}}
2catch(s){console.error("Error fetching parameters:",s)}finally{this.setState({isLoadingParameters:!1})}}},this.handleButtonTypeChange=e=>{this.setState({thankYouButtonType:e})},this.getAllQuestions=()=>{const{customQuestions:e,contactInfoFields:t}=this.state,a=[];for(const i of e)if(a.push(i),i.conditionalQuestions)for(const e of Object.values(i.conditionalQuestions))a.push(e);for(const i of t)i.enabled&&a.push({type:i.type});return a},this.handleAddQuestion=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"CUSTOM";const{customQuestions:a}=t.state,i={id:Ca("q"),type:"SHORT_ANSWER"===e||"MULTIPLE_CHOICE"===e?"CUSTOM":e,questionType:"SHORT_ANSWER"===e||"MULTIPLE_CHOICE"===e?e:void 0,key:"custom_".concat(Date.now()),label:"DATE_TIME"===e?"Appointment time":"",inline_context:"DATE_TIME"===e?"We will verify and call you to confirm your appointment.":void 0,options:[],isMultipleChoice:"MULTIPLE_CHOICE"===e,conditionalQuestions:{},isMandatory:!0,mappedParameter:null};t.setState({customQuestions:[...a,i]})},this.handleRemoveQuestion=e=>{const{customQuestions:t}=this.state;this.setState({customQuestions:t.filter((t=>t.id!==e))})},this.handleDragEnd=e=>{const{destination:t,source:a,type:i}=e;if(t&&"QUESTION"===i){const{customQuestions:e}=this.state,i=Array.from(e),[s]=i.splice(a.index,1);i.splice(t.index,0,s),this.setState({customQuestions:i})}},this.handleQuestionChange=(e,t,a)=>{const{customQuestions:i}=this.state;this.setState({customQuestions:i.map((i=>{if(i.id!==e)return i;const s={...i,[t]:a};return"type"===t&&"CUSTOM"!==a&&(s.key=a.toLowerCase(),s.label="",s.options=[],s.isMultipleChoice=!1,s.conditionalQuestions={}),"questionType"===t&&(s.questionType=a,s.isMultipleChoice="MULTIPLE_CHOICE"===a,"MULTIPLE_CHOICE"!==a&&(s.options=[],s.conditionalQuestions={})),"mappedParameter"===t&&"create_new"===a&&s.label,s}))})},this.generateKeyFromName=e=>e.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),this.handleCreateNewParameter=async(e,t,a)=>{const{assistantId:s}=this.props;if(!s||!t.trim())return this.setState({error:"Parameter name is required"}),null;const n=a&&a.trim()?a.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""):this.generateKeyFromName(t);if(!n||!/^[a-z][a-z0-9_]*$/.test(n))return this.setState({error:"Parameter key must start with a letter and contain only lowercase letters, numbers, and underscores"}),null;try{var o;const a=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/parameters"),{params:{assistantId:s}});if(null!==(o=a.data)&&void 0!==o&&o.status){var r;const{custom:o,limit:l,all:d}=a.data.data;if(d.some((e=>e.key===n)))return this.setState({error:'Parameter key "'.concat(n,'" already exists. Please use a different key.')}),null;if(o.length>=l)return this.setState({error:"Parameter limit reached. Maximum ".concat(l," custom parameters allowed.")}),null;if(null!==(r=(await i.Z.post("".concat(W.URL,"/meta-ads/lead-form-parameters"),{assistantId:s,parameters:[...a.data.data.preDefined,...o,{key:n,name:t.trim(),type:"CUSTOM",dataType:"TEXT"}]})).data)&&void 0!==r&&r.status){if(e&&e.startsWith("contact_")){const t=e.replace("contact_","");this.setState({contactInfoFields:this.state.contactInfoFields.map((e=>e.type===t?{...e,mappedParameter:n}:e))})}else this.handleQuestionChange(e,"mappedParameter",n);return this.setState({creatingParameterFor:null,newParamName:"",newParamKey:"",creatingParameterForFieldType:null}),await this.fetchAvailableParameters(),n}}}catch(c){var l,d;console.error("Error creating parameter:",c),this.setState({error:(null===(l=c.response)||void 0===l||null===(d=l.data)||void 0===d?void 0:d.message)||"Failed to create parameter"})}return null},this.handleAddOption=e=>{const{customQuestions:t}=this.state;this.setState({customQuestions:t.map((t=>{if(t.id!==e)return t;const a=t.options||[],i={value:"",key:Ca("opt")};return{...t,options:[...a,i]}}))})},this.handleRemoveOption=(e,t)=>{const{customQuestions:a}=this.state;this.setState({customQuestions:a.map((a=>a.id!==e?a:{...a,options:a.options.filter(((e,a)=>a!==t)),conditionalQuestions:Object.fromEntries(Object.entries(a.conditionalQuestions||{}).filter((e=>{var i;let[s]=e;return s!==(null===(i=a.options[t])||void 0===i?void 0:i.key)}
2)))}))})},this.handleOptionChange=(e,t,a)=>{const{customQuestions:i}=this.state;this.setState({customQuestions:i.map((i=>{var s;if(i.id!==e)return i;const n=[...i.options||[]];return n[t]={...n[t],value:a,key:(null===(s=n[t])||void 0===s?void 0:s.key)||Ca("opt")},{...i,options:n}}))})},this.hasAppointmentQuestion=()=>{const{customQuestions:e}=this.state;return e.some((e=>"DATE_TIME"===e.type))||e.some((e=>e.conditionalQuestions&&Object.values(e.conditionalQuestions).some((e=>"DATE_TIME"===e.type))))},this.handleAddConditionalQuestion=(e,t,a)=>{this.setState({conditionalQuestionMenuAnchor:a.currentTarget,conditionalQuestionParentId:e,conditionalQuestionOptionKey:t})},this.handleCreateConditionalQuestion=e=>{const{customQuestions:t,conditionalQuestionParentId:a,conditionalQuestionOptionKey:i}=this.state;let s;s="DATE_TIME"===e?{id:Ca("q"),type:"DATE_TIME",key:"conditional_".concat(Date.now()),label:"Appointment time",inline_context:"We will verify and call you to confirm your appointment.",isConditional:!0,parentQuestionId:a,dependentOptionKey:i}:{id:Ca("q"),type:"CUSTOM",questionType:"MULTIPLE_CHOICE"===e?"MULTIPLE_CHOICE":"SHORT_ANSWER",key:"conditional_".concat(Date.now()),label:"",options:[],isMultipleChoice:"MULTIPLE_CHOICE"===e,isConditional:!0,parentQuestionId:a,dependentOptionKey:i},this.setState({customQuestions:t.map((e=>e.id!==a?e:{...e,conditionalQuestions:{...e.conditionalQuestions||{},[i]:s}})),conditionalQuestionMenuAnchor:null,conditionalQuestionParentId:null,conditionalQuestionOptionKey:null})},this.getQuestionTypeDisplayName=e=>{if("DATE_TIME"===e.type)return"Appointment";if("CUSTOM"===e.type){if("SHORT_ANSWER"===e.questionType)return"Short Answer";if("MULTIPLE_CHOICE"===e.questionType)return"Multiple Choice"}return e.type||"Custom"},this.hasConditionalQuestions=()=>{const{customQuestions:e}=this.state;return e.some((e=>e.conditionalQuestions&&Object.keys(e.conditionalQuestions).length>0))},this.handleRemoveConditionalQuestion=(e,t)=>{const{customQuestions:a}=this.state;this.setState({customQuestions:a.map((a=>{if(a.id!==e)return a;const{[t]:i,...s}=a.conditionalQuestions||{};return{...a,conditionalQuestions:s}}))})},this.handleConditionalQuestionChange=(e,t,a,i)=>{const{customQuestions:s}=this.state;this.setState({customQuestions:s.map((s=>{var n;if(s.id!==e)return s;const o=null===(n=s.conditionalQuestions)||void 0===n?void 0:n[t];return o?{...s,conditionalQuestions:{...s.conditionalQuestions,[t]:{...o,[a]:i}}}:s}))})},this.handleContactFieldToggle=(e,t)=>{const{contactInfoFields:a}=this.state;this.setState({contactInfoFields:a.map((a=>a.type===e?{...a,enabled:t,isMandatory:!(!t||"FULL_NAME"!==a.type&&"PHONE"!==a.type)||a.isMandatory}:a))})},this.handleContactFieldMandatory=(e,t)=>{const{contactInfoFields:a}=this.state;"FULL_NAME"!==e&&"PHONE"!==e&&this.setState({contactInfoFields:a.map((a=>a.type===e?{...a,isMandatory:t}:a))})},this.handleContactFieldParameterChange=async(e,t)=>{const{contactInfoFields:a}=this.state;if("create_new"===t){const t=Xt.dh.find((t=>t.value===e)),a=(null===t||void 0===t?void 0:t.label)||e,i=this.generateKeyFromName(a);this.setState({creatingParameterFor:"contact_".concat(e),newParamName:a,newParamKey:i,creatingParameterForFieldType:e})}else this.setState({contactInfoFields:a.map((a=>a.type===e?{...a,mappedParameter:t||null}:a))})},this.handleAddFieldFromCategory=e=>{const{contactInfoFields:t}=this.state;t.find((t=>t.type===e));this.handleContactFieldToggle(e,!0),this.setState({categoryDropdownAnchor:null,submenuAnchor:null,submenuCategory:null})},this.handleRemoveContactField=e=>{const{contactInfoFields:t}=this.state;"FULL_NAME"!==e&&"PHONE"!==e&&this.setState({contactInfoFields:t.map((t=>t.type===e?{...t,enabled:!1}:t))})},this.getStepValidation=()=>{const{greetingEnabled:e,greetingHeadline:t,greetingDescription:a,conditionalLogicEnabled:i,customQuestions:s,privacyPolicyUrl:n,thankYouButtonType:o,thankYouWebsiteUrl:r,thankYouPhoneNumber:l,thankYouDownloadFileUrl:d}=this.state,c=!e||t.trim()&&a.trim(),p=!i||s.some((e=>e.isMultipleChoice&&e.options&&e.options.length>0)),u=n.trim().length>0;let h=!0;return"VIEW_WEBSITE"===o?h=(0,Xt.RG)((0,Xt.W7)(r)):"CALL_BUSINESS"===o?h=l.trim().length>0:"DOWNLOAD"===o&&(h=d.trim().length>0),{intro:c,questions:p,privacy:u,ending:h}},this.isFormValid=()=>{var e,t;const{formName:a,contactInfoFields:i}=this.state,s=this.getStepValidation();if(!a.trim())return!1;const n=null===(e=i.find((e=>"FULL_NAME"===e.type)))||void 0===e?void 0:e.enabled,o=null===(t=i.find((e=>"PHONE"===e.type)))||void 0===t?void 0:t.enabled;return!(!n||!o)&&(s.intro&&s.questions&&s.privacy&&s.ending)},this.validateForm=()=>{var e,t;const{formName:a,customQuestions:i,contactInfoFields:s,privacyPolicyUrl:n,thankYouButtonType:o,thankYouWebsiteUrl:r}=this.state;if(console.log("Validating form:",{formName:a,customQuestions:i,contactInfoFields:s,privacyPolicyUrl:n}),!a.trim())return console.log("Validation failed: Form name is required"),this.setState({error:"Form name is required"}),!1;const l=null===(e=s.find((e=>"FULL_NAME"===e.type)))||void 0===e?void 0:e.enabled,d=null===(t=s.find((e=>"PHONE"===e.type)))||void 0===t?void 0:t.enabled;if(!l||!d)return console.log("Validation failed: Full Name and Phone Number must be enabled"),this.setState({error:"Full Name and Phone Number must be enabled in Contact Information"}),!1;for(const h of i){if("CUSTOM"===h.type){var c,p;if(null===(c=h.label)||void 0===c||!c.trim())return console.log("Validation failed: Custom questions must have a label"),this.setState({error:"Custom question must have a label"}),!1;if(h.isMultipleChoice&&(!h.options||h.options.length<2))return console.log("Validation failed: Multiple choice questions need at least 2 options"),this.setState({error:'Multiple choice question "'.concat(h.label,'" needs at least 2 options')}),!1;if(h.isMultipleChoice&&null!==(p=h.options)&&void 0!==p&&p.some((e=>{var t;return!(null!==(t=e.value)&&void 0!==t&&t.trim())})))return console.log("Validation failed: All options must have a value"),this.setState({error:'All options in "'.concat(h.label,'" must have a value')}),!1}
2if(h.conditionalQuestions)for(const[e,t]of Object.entries(h.conditionalQuestions)){var u;if(null===(u=t.label)||void 0===u||!u.trim())return console.log("Validation failed: Conditional questions must have a label"),this.setState({error:'Conditional question for option "'.concat(e,'" must have a label')}),!1}}if(!n.trim())return console.log("Validation failed: Privacy policy URL is required"),this.setState({error:"Privacy policy URL is required"}),!1;try{new window.URL(n)}catch{return console.log("Validation failed: Invalid privacy policy URL"),this.setState({error:"Please enter a valid privacy policy URL"}),!1}return"VIEW_WEBSITE"!==o||(0,Xt.RG)((0,Xt.W7)(r))?(console.log("Form validation passed!"),!0):(console.log("Validation failed: Invalid thank you page website URL"),this.setState({error:"Please enter a valid website URL for the thank you page (e.g., https://example.com)"}),!1)},this.loadFormForEdit=e=>{const t=e.questions||[],a=ka().map((e=>{const a=t.find((t=>t.type===e.type||"PHONE"===e.type&&"PHONE_OTP"===t.type));return a?{...e,enabled:!0,mappedParameter:a.mappedParameter||e.mappedParameter}:e})),i=!0===e.phoneVerificationEnabled||t.some((e=>"PHONE_OTP"===e.type)),s=t.filter((e=>"CUSTOM"===e.type||"DATE_TIME"===e.type)).map((e=>{var t,a;return{conditionalQuestions:{},id:Ca("q"),inline_context:"DATE_TIME"===e.type?e.inline_context||"We will verify and call you to confirm your appointment.":e.inline_context,isMandatory:!0,isMultipleChoice:!(null===(t=e.options)||void 0===t||!t.length),key:e.key,label:e.label,mappedParameter:e.mappedParameter,options:e.options,questionType:"DATE_TIME"===e.type?"DATE_TIME":null!==(a=e.options)&&void 0!==a&&a.length?"MULTIPLE_CHOICE":"SHORT_ANSWER",type:"CUSTOM"}})),n=e.thankYouPage||{},o=e.privacyPolicy||{},r=e.greeting||{};this.setState({mode:"edit",editingForm:e,formName:e.name||"",automation:e.automation||null,contactInfoFields:a,formType:e.isOptimizedForQuality||i?"higher_intent":"more_volume",verifyPhoneWithOtp:i,currentStep:4,customQuestions:s,privacyPolicyUrl:o.url||"",privacyPolicyLinkText:o.linkText||"Privacy Policy",thankYouTitle:n.title||"Thank you!",thankYouBody:n.body||"We'll be in touch shortly.",thankYouButtonType:n.buttonType||"VIEW_WEBSITE",thankYouButtonText:n.buttonText||"Visit Website",thankYouWebsiteUrl:n.websiteUrl||"",thankYouPhoneNumber:n.phoneNumber||"",thankYouDownloadFileUrl:n.downloadFileUrl||n.gatedFileUrl||"",greetingEnabled:!(!r.headline&&!r.description),greetingHeadline:r.headline||"",greetingDescription:r.description||"",descriptionType:r.descriptionType||"PARAGRAPH"})},this.fetchExistingForms=async()=>{const{assistantId:e,pageId:t}=this.props;if(e&&t){this.setState({isLoadingForms:!0});try{var a,s;const n=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms"),{params:{assistantId:e,pageId:t,status:"ACTIVE",limit:100}});null!==(a=n.data)&&void 0!==a&&a.status&&null!==(s=n.data)&&void 0!==s&&s.data&&this.setState({existingForms:n.data.data})}catch(n){console.error("Error fetching existing forms:",n),this.setState({error:"Failed to fetch lead forms. Please try again."})}finally{this.setState({isLoadingForms:!1})}}},this.handleUpdateAutomation=async()=>{const{assistantId:e}=this.props,{editingForm:t}=this.state;if(e&&null!==t&&void 0!==t&&t.formId){this.setState({isUpdating:!0,error:null});try{var a;const n=this.getAutomationConfigRef?this.getAutomationConfigRef():this.state.automation;console.log("Sending automation config to backend:",JSON.stringify(n,null,2)),console.log("Template parameters in automation:",null===n||void 0===n?void 0:n.templateParameters);const o=await i.Z.put("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/automation"),{assistantId:e,formId:t.formId,automation:n});var s;if(null!==(a=o.data)&&void 0!==a&&a.status)this.setState({success:"Automation settings updated successfully!"}),this.props.onFormUpdated&&this.props.onFormUpdated(t),setTimeout((()=>{this.props.onClose(),this.resetForm()}),1500);else this.setState({error:(null===(s=o.data)||void 0===s?void 0:s.message)||"Failed to update automation settings"})}catch(r){var n,o;console.error("Error updating automation:",r),this.setState({error:(null===(n=r.response)||void 0===n||null===(o=n.data)||void 0===o?void 0:o.message)||r.message||"Failed to update automation settings"})}finally{this.setState({isUpdating:!1})}}else this.setState({error:"Missing required information"})},this.handleCreateForm=async()=>
2{if(console.log("handleCreateForm called"),!this.validateForm())return;const{assistantId:e,pageId:t}=this.props;if(console.log("Props:",{assistantId:e,pageId:t}),!e||!t)return console.log("Missing assistantId or pageId"),void this.setState({error:"Assistant ID and Page ID are required"});this.setState({isCreating:!0,error:null});try{var a;const{formName:l,customQuestions:d,contactInfoFields:c,verifyPhoneWithOtp:p,privacyPolicyUrl:u,privacyPolicyLinkText:h,thankYouTitle:m,thankYouBody:g,thankYouButtonType:x,thankYouButtonText:v,thankYouWebsiteUrl:y,thankYouPhoneNumber:f,blockDisplayForNonTargetedViewer:A}=this.state,b=this.getAutomationConfigRef?this.getAutomationConfigRef():this.state.automation,S=[];for(const e of d){const t={type:e.type};if("DATE_TIME"===e.type)t.label=e.label||"Appointment time",e.inline_context?t.inline_context=e.inline_context:t.inline_context="We will verify and call you to confirm your appointment.";else if("CUSTOM"===e.type){var s;t.key=e.key||"custom_question_".concat(S.length),e.label&&(t.label=e.label),e.mappedParameter&&(t.mappedParameter=e.mappedParameter),e.isMultipleChoice&&(null===(s=e.options)||void 0===s?void 0:s.length)>0&&(t.options=e.options.map(((e,t)=>({key:e.key||"option_".concat(t),value:e.value||e}))))}if(S.push(t),e.conditionalQuestions&&Object.keys(e.conditionalQuestions).length>0)for(const[a,i]of Object.entries(e.conditionalQuestions)){var n;const s=null===(n=e.options)||void 0===n?void 0:n.find((e=>e.key===a)),r=(null===s||void 0===s?void 0:s.key)||a,l={type:i.type||"CUSTOM",dependent_key:e.key||t.key,dependent_option:r};var o;if("DATE_TIME"===i.type)l.label=i.label||"Appointment time",i.inline_context?l.inline_context=i.inline_context:l.inline_context="We will verify and call you to confirm your appointment.";else l.key=i.key||"conditional_".concat(S.length),l.label=i.label,i.isMultipleChoice&&(null===(o=i.options)||void 0===o?void 0:o.length)>0&&(l.options=i.options.map(((e,t)=>({key:e.key||"option_".concat(t),value:e.value||e}))));S.push(l)}}for(const e of c)if(e.enabled){const t={type:e.type};e.mappedParameter&&(t.mappedParameter=e.mappedParameter),S.push(t)}const I={title:m,body:g,buttonType:x,buttonText:v};"VIEW_WEBSITE"===x&&(I.websiteUrl=(0,Xt.W7)(y)),"CALL_BUSINESS"===x&&(I.phoneNumber=f),"DOWNLOAD"===x&&(I.downloadFileUrl=this.state.thankYouDownloadFileUrl,I.gatedFileUrl=this.state.thankYouDownloadFileUrl);const j={assistantId:e,pageId:t,name:l,questions:S,privacyPolicy:{url:u,linkText:h},thankYouPage:I,greeting:this.state.greetingEnabled?{headline:this.state.greetingHeadline,description:this.state.greetingDescription,descriptionType:this.state.descriptionType||"PARAGRAPH"}:null,isOptimizedForQuality:"higher_intent"===this.state.formType,verifyPhoneWithOtp:"higher_intent"===this.state.formType&&p,blockDisplayForNonTargetedViewer:A,automation:b||null};console.log("Creating lead form with payload:",j),console.log("API URL:","".concat(W.ADS_REST_API_URL,"/meta/lead-forms/create"));const C=await i.Z.post("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/create"),j);if(console.log("API Response:",C.data),null!==(a=C.data)&&void 0!==a&&a.status){const e=C.data.data;this.setState({success:"Lead form created successfully!"}),this.setState({formName:wa(),customQuestions:[],contactInfoFields:ka(),formType:"more_volume",verifyPhoneWithOtp:!1}),this.props.onFormCreated&&this.props.onFormCreated(e)}else{var r;this.setState({error:(null===(r=C.data)||void 0===r?void 0:r.message)||"Failed to create lead form"})}}catch(g){var l;console.error("Error creating lead form:",g);const{action:e,assistant:t}=(null===(l=g.response)||void 0===l?void 0:l.data)||{};var d,c;if("accept_lead_gen_tos"===e)this.setState({error:(null===(d=g.response)||void 0===d||null===(c=d.data)||void 0===c?void 0:c.message)||"You need to accept Facebook's Lead Generation Terms of Service.",tosLink:(null===t||void 0===t?void 0:t.link)||"https://www.facebook.com/legal/leadgen/tos",reconnectRequired:!1});else if("reconnect_meta_for_lead_ads"===e){var p,u;this.setState({error:(null===(p=g.response)||void 0===p||null===(u=p.data)||void 0===u?void 0:u.message)||"You need to reconnect your Meta account with additional permissions for Lead Form Ads.",tosLink:null,reconnectRequired:!0})}else{var h,m;this.setState({error:(null===(h=g.response)||void 0===h||null===(m=h.data)||void 0===m?void 0:m.message)||g.message||"Failed to create lead form",tosLink:null,reconnectRequired:!1})}}finally{this.setState({isCreating:!1})}},this.handleSelectForm=e=>{this.props.onFormSelected&&this.props.onFormSelected({label:e.name,value:e.formId,...e}),this.props.onClose()},this.resetForm=()=>{this.setState({formName:wa(),customQuestions:[],contactInfoFields:ka(),formType:"more_volume",verifyPhoneWithOtp:!1,privacyPolicyUrl:"",privacyPolicyLinkText:"Privacy Policy",thankYouTitle:"Thank y
2ou!",thankYouBody:"We'll be in touch shortly.",thankYouButtonType:"VIEW_WEBSITE",thankYouButtonText:"Visit Website",thankYouWebsiteUrl:"",thankYouPhoneNumber:"",blockDisplayForNonTargetedViewer:!1,error:null,success:null,mode:"create",editingForm:null,automation:null,currentStep:0})},this.handleCreateWithFacebookDialog=async()=>{const{pageId:e}=this.props;if(ma())if(e){this.setState({isCreating:!0,error:null});try{const t=await ga({pageId:e});null!==t&&void 0!==t&&t.formId&&(this.setState({success:"Lead form created via Facebook! Form ID: ".concat(t.formId)}),this.props.onFormCreated&&this.props.onFormCreated({formId:t.formId,name:t.formName||"Facebook Lead Form"}))}catch(t){this.setState({error:"string"===typeof t?t:"Failed to create lead form via Facebook dialog"})}finally{this.setState({isCreating:!1})}}else this.setState({error:"Page ID is required to use Facebook dialog"});else this.setState({error:"Facebook SDK is not loaded. Please use the custom form builder."})},this.renderQuestion=(e,t,a)=>{const{classes:i}=this.props;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1,children:(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{size:"small",disabled:"edit"===this.state.mode,checked:e.isMandatory||!1,onChange:t=>this.handleQuestionChange(e.id,"isMandatory",t.target.checked),color:"primary"}),label:(0,K.jsx)(I.Z,{variant:"caption",children:"Mandatory"})})}),("CUSTOM"===e.type||"DATE_TIME"===e.type)&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Question Label *"}),(0,K.jsx)(L.Z,{fullWidth:!0,disabled:"edit"===this.state.mode,variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"DATE_TIME"===e.type?"e.g., Appointment time":"e.g., What is your budget?",value:e.label||"",onChange:t=>this.handleQuestionChange(e.id,"label",t.target.value)})]}),(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Map to Parameter"}),(0,K.jsxs)(L.Z,{select:!0,fullWidth:!0,variant:"outlined",disabled:"edit"===this.state.mode,classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Select parameter to map",value:e.mappedParameter||"",onChange:t=>{const a=t.target.value;if("create_new"===a){var i;const t=(null===(i=e.label)||void 0===i?void 0:i.trim())||"",a=t?this.generateKeyFromName(t):"";this.setState({creatingParameterFor:e.id,newParamName:t,newParamKey:a})}else this.handleQuestionChange(e.id,"mappedParameter",a||null)},SelectProps:{renderValue:e=>{if(!e)return"Don't map";if("create_new"===e)return"Create new parameter...";const t=this.state.availableParameters.find((t=>t.key===e));return t?t.name:e},displayEmpty:!0},children:[(0,K.jsx)(de.Z,{value:"",children:(0,K.jsx)("em",{children:"Don't map"})}),(0,K.jsx)(de.Z,{value:"create_new",children:"Create new parameter..."}),this.state.availableParameters.filter((e=>"CUSTOM"===e.type&&!e.archived)).map((e=>(0,K.jsx)(de.Z,{value:e.key,children:e.name},e.key)))]})]}),this.state.creatingParameterFor===e.id&&(0,K.jsxs)(A.Z,{mt:1.5,p:1.5,style:{border:"1px solid #e0e0e0",borderRadius:6,backgroundColor:"#f9f9fb"},children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:8,display:"block",fontWeight:500},children:"Create New Parameter"}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Parameter Name *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",size:"small",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"e.g., Budget Range",value:this.state.newParamName,onChange:e=>{const t=e.target.value,a=this.generateKeyFromName(t);this.setState({newParamName:t,newParamKey:a})}})]}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Parameter Key *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",size:"small",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"e.g., budget_range",value:this.state.newParamKey,onChange:e=>{const t=e.target.value.toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"");this.setState({newParamKey:t})},helperText:"Lowercase letters, numbers, and underscores only"})]}),(0,K.jsxs)(A.Z,{display:"flex",gap:1,children:[(0,K.jsx)(w.Z,{size:"small",variant:"contained",color:"primary",onClick:async()=>{await this.handleCreateNewParameter(e.id,this.state.newParamName,this.state.newParamKey)},disabled:!this.state.newParamName.trim()||!this.state.newParamKey.trim(),style:{textTransform:"none"},children:"Save Parameter"}),(0,K.jsx)(w.Z,{size:"small",variant:"outlined",onClick:()=>{this.setState({creatingParameterFor:null,newParamName:"",newParamKey:""})},style:{textTransform:"none"},children:"Cancel"})]})]}),"DATE_TIME"===e.type&&(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"}
2,children:"Inline Context"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"We will verify and call you to confirm your appointment.",value:e.inline_context||"",onChange:t=>this.handleQuestionChange(e.id,"inline_context",t.target.value)})]}),"CUSTOM"===e.type&&(0,K.jsx)(A.Z,{mt:1.5,children:(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{size:"small",disabled:"edit"===this.state.mode,checked:e.isMultipleChoice||!1,onChange:t=>this.handleQuestionChange(e.id,"isMultipleChoice",t.target.checked),color:"primary"}),label:(0,K.jsx)(I.Z,{variant:"body2",children:"Multiple Choice Question"})})}),e.isMultipleChoice&&(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",gutterBottom:!0,style:{display:"block"},children:"Options *"}),(e.options||[]).map(((t,a)=>{var s;return(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",gap:1,mb:1,children:[(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",disabled:"edit"===this.state.mode,classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Option ".concat(a+1),value:t.value,onChange:t=>this.handleOptionChange(e.id,a,t.target.value)}),"edit"!==this.state.mode&&(0,K.jsx)(b.Z,{size:"small",onClick:()=>this.handleRemoveOption(e.id,a),children:(0,K.jsx)(Kt.Z,{fontSize:"small"})}),e.isMultipleChoice&&this.state.conditionalLogicEnabled&&!(null!==(s=e.conditionalQuestions)&&void 0!==s&&s[t.key])&&(0,K.jsx)(w.Z,{size:"small",onClick:a=>this.handleAddConditionalQuestion(e.id,t.key,a),style:{textTransform:"none"},children:"Add Conditional"})]},a)})),"edit"!==this.state.mode&&(0,K.jsx)(w.Z,{size:"small",startIcon:(0,K.jsx)(ce.Z,{}),onClick:()=>this.handleAddOption(e.id),style:{textTransform:"none"},children:"Add Option"}),e.isMultipleChoice&&(!e.options||e.options.length<2)&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{display:"block",marginTop:4},children:"Add at least 2 options for multiple choice"})]}),e.conditionalQuestions&&Object.keys(e.conditionalQuestions).length>0&&(0,K.jsxs)(A.Z,{mt:2,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",gutterBottom:!0,style:{marginBottom:12,fontWeight:500},children:"Conditional Questions"}),Object.entries(e.conditionalQuestions).map((t=>{var a;let[s,n]=t;const o=null===(a=e.options)||void 0===a?void 0:a.find((e=>e.key===s));return(0,K.jsxs)(_t.Z,{elevation:1,style:{marginBottom:12,padding:12,borderLeft:"3px solid #1976d2"},children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1,children:[(0,K.jsx)(A.Z,{display:"flex",alignItems:"center",gap:1,children:(0,K.jsx)(Wt.Z,{label:'If "'.concat((null===o||void 0===o?void 0:o.value)||s,'" is selected'),size:"small",variant:"outlined",color:"primary",style:{fontSize:"0.7rem",height:20}})}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>this.handleRemoveConditionalQuestion(e.id,s),children:(0,K.jsx)(Kt.Z,{fontSize:"small"})})]}),(0,K.jsx)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1,children:(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{size:"small",disabled:"edit"===this.state.mode,checked:n.isMandatory||!1,onChange:t=>this.handleConditionalQuestionChange(e.id,s,"isMandatory",t.target.checked),color:"primary"}),label:(0,K.jsx)(I.Z,{variant:"caption",children:"Mandatory"})})}),("CUSTOM"===n.type||"DATE_TIME"===n.type)&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Question Label *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"DATE_TIME"===n.type?"e.g., Appointment time":"e.g., What is your budget?",value:n.label||"",onChange:t=>this.handleConditionalQuestionChange(e.id,s,"label",t.target.value)})]}),"CUSTOM"===n.type&&(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Map to Parameter"}),(0,K.jsxs)(L.Z,{select:!0,fullWidth:!0,variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Select parameter to map",value:n.mappedParameter||"",onChange:t=>{const a=t.target.value;if("create_new"===a){var i;const t=(null===(i=n.label)||void 0===i?void 0:i.trim())||"",a=t?this.generateKeyFromName(t):"";this.setState({creatingParameterFor:"".concat(e.id,"_").concat(s),newParamName:t,newParamKey:a})}else this.handleConditionalQuestionChange(e.id,s,"mappedParameter",a||null)},SelectProps:{renderValue:e=>{if(!e)return"Don't map";if("create_new"===e)return"Create new parameter...";const t=this.state.availableParameters.find((t=>t.key===e));return t?t.name:e},displayEmpty:!0},children:[(0,K.jsx)(de.Z,{value:"",children:(0,K.jsx)("em",{children:"Don't map"})}),(0,K.jsx)(de.Z,{value:"create_new",children:"Create new parameter..."}),this.state.availableParameters.filter((e=>"CUSTOM"===e.type&&!e.archived)).map((e=>(0,K.jsx)(de.Z,{value:e.key,children:e.name},e.key)))]})]}),this.state.creatingParameterFor==="".concat(e.id,"_").concat(s)&&(0,K.jsxs)(A.Z,{mt:1.5,p:1.5,style:{border:"1px solid #e0e0e0",borderRadius:6,backgroundColor:"#f9f9fb"},children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:8,display:"block",fontWeight:500},children:"Create New Parameter"}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Parameter Name *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",size:"small",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"e.g., Budget Range",value:this.state.newParamName,onChange:e=>{const t=e.target.value,a=this.generateKeyFromName(t);this.setState({newParamName:t,newParamKey:a})}})]}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"},children:"Parameter Key *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",size:"small",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"e.g., budget_range",value:this.state.newParamKey,onChange:e=>{const t=e.target.value.toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"");this.setState({newParamKey:t})},helperText:"Lowercase letters, numbers, and underscores only"})]}),(0,K.jsxs)(A.Z,{display:"flex",gap:1,children:[(0,K.jsx)(w.Z,{size:"small",variant:"contained",color:"primary",onClick:async()=>{const t=await this.handleCreateNewParameter("".concat(e.id,"_").concat(s),this.state.newParamName,this.state.newParamKey);t&&this.handleConditionalQuestionChange(e.id,s,"mappedParameter",t)},disabled:!this.state.newParamName.trim()||!this.state.newParamKey.trim(),style:{textTransform:"none"},children:"Save Parameter"}),(0,K.jsx)(w.Z,{size:"small",variant:"outlined",onClick:()=>{this.setState({creatingParameterFor:null,newParamName:"",newParamKey:""})},style:{textTransform:"none"},children:"Cancel"})]})]}),"DATE_TIME"===n.type&&(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",style:{marginBottom:4,display:"block"}
2,children:"Inline Context"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"We will verify and call you to confirm your appointment.",value:n.inline_context||"",onChange:t=>this.handleConditionalQuestionChange(e.id,s,"inline_context",t.target.value)})]}),"CUSTOM"===n.type&&(0,K.jsx)(A.Z,{mt:1.5,children:(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{size:"small",disabled:"edit"===this.state.mode,checked:n.isMultipleChoice||!1,onChange:t=>this.handleConditionalQuestionChange(e.id,s,"isMultipleChoice",t.target.checked),color:"primary"}),label:(0,K.jsx)(I.Z,{variant:"body2",children:"Multiple Choice Question"})})})]}),n.isMultipleChoice&&"CUSTOM"===n.type&&(0,K.jsxs)(A.Z,{mt:1.5,children:[(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",gutterBottom:!0,style:{display:"block"},children:"Options *"}),(n.options||[]).map(((t,a)=>(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",gap:1,mb:1,children:[(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Option ".concat(a+1),value:t.value,onChange:i=>{const o=[...n.options||[]];o[a]={...t,value:i.target.value},this.handleConditionalQuestionChange(e.id,s,"options",o)}}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>{const t=(n.options||[]).filter(((e,t)=>t!==a));this.handleConditionalQuestionChange(e.id,s,"options",t)},children:(0,K.jsx)(Kt.Z,{fontSize:"small"})})]},a))),(0,K.jsx)(w.Z,{size:"small",startIcon:(0,K.jsx)(ce.Z,{}),onClick:()=>{const t=[...n.options||[],{value:"",key:Ca("opt")}];this.handleConditionalQuestionChange(e.id,s,"options",t)},style:{textTransform:"none"},children:"Add Option"}),(!n.options||n.options.length<2)&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{display:"block",marginTop:4},children:"Add at least 2 options for multiple choice"})]})]},s)}))]})]})]})},this.getAutomationConfigRef=null,this.state={formName:wa(),customQuestions:[],contactInfoFields:ka(),formType:"more_volume",verifyPhoneWithOtp:!1,privacyPolicyUrl:"",privacyPolicyLinkText:"Privacy Policy",draggedItem:null,thankYouTitle:"Thank you!",thankYouBody:"We'll be in touch shortly.",thankYouButtonType:"VIEW_WEBSITE",thankYouButtonText:"Visit Website",thankYouWebsiteUrl:"",thankYouPhoneNumber:"",thankYouDownloadFileUrl:"",isOptimizedForQuality:!1,blockDisplayForNonTargetedViewer:!1,isCreating:!1,error:null,tosLink:null,reconnectRequired:!1,success:null,currentStep:0,automation:null,previewMode:"form",mode:"create",editingForm:null,existingForms:[],isLoadingForms:!1,isUpdating:!1,greetingEnabled:!0,greetingHeadline:"",greetingDescription:"",descriptionType:"PARAGRAPH",conditionalLogicEnabled:!1,questionDropdownAnchor:null,categoryDropdownAnchor:null,submenuAnchor:null,submenuCategory:null,contactInfoDescription:"",availableParameters:[],isLoadingParameters:!1,creatingParameterFor:null,newParamName:"",newParamKey:"",automationPreviewData:{selectedTemplate:null,parameters:[],media:{},cards:[],carouselIndex:0},previewCarouselIndex:0,conditionalQuestionMenuAnchor:null,conditionalQuestionParentId:null,conditionalQuestionOptionKey:null}}componentDidMount(){this.fetchAvailableParameters(),this.props.editMode&&this.props.editForm?this.loadFormForEdit(this.props.editForm):"manage"===this.props.initialView&&(this.setState({mode:"manage"}),this.fetchExistingForms())}componentDidUpdate(e){!e.open&&this.props.open&&(this.props.editMode&&this.props.editForm?this.loadFormForEdit(this.props.editForm):"manage"===this.props.initialView?(this.setState({mode:"manage"}),this.fetchExistingForms()):this.setState({mode:"create",currentStep:0,formName:wa(),customQuestions:[],contactInfoFields:ka(),formType:"more_volume",verifyPhoneWithOtp:!1,privacyPolicyUrl:"",privacyPolicyLinkText:"Privacy Policy",thankYouTitle:"Thank you!",thankYouBody:"We'll be in touch shortly.",thankYouButtonType:"VIEW_WEBSITE",thankYouButtonText:"Visit Website",thankYouWebsiteUrl:"",thankYouPhoneNumber:"",isOptimizedForQuality:!1,blockDisplayForNonTargetedViewer:!1,greetingEnabled:!0,greetingHeadline:"",greetingDescription:"",descriptionType:"PARAGRAPH",conditionalLogicEnabled:!1,contactInfoDescription:"",automation:null,error:null,success:null}))}render(){var e,t;const{classes:a,open:i,onClose:s}=this.props,{formName:n,customQuestions:o,contactInfoFields:r,verifyPhoneWithOtp:l,privacyPolicyUrl:d,privacyPolicyLinkText:c,thankYouTitle:p,thankYouBody:h,thankYouButtonType:m,thankYouButtonText:g,thankYouWebsiteUrl:x,isOptimizedForQuality:v,blockDisplayForNonTargetedViewer:S,isCreating:j,error:Z,tosLink:T,success:D,currentStep:P,previewMode:B,mode:N,editingForm:R,existingForms:O,isLoadingForms:U,isUpdating:z}=this.state;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(je.ZP,{anchor:"right",open:i,onClose:s,classes:{paper:a.drawerPaper},children:(0,K.jsxs)(A.Z,{className:a.drawerContainer,children:[(0,K.jsxs)(A.Z,{className:a.header,children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",children:[(0,K.jsx)(I.Z,{variant:"h5",className:a.headerTitle,children:"edit"===N?"Edit Automation: ".concat((null===R||void 0===R?void 0:R.name)||"Lead Form"):"manage"===N?"Manage Lead Forms":n||"Create Lead Form"}),(0,K.jsx)(b.Z,{onClick:s,size:"small",children:(0,K.jsx)(ct.Z,{})})]}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"edit"===N?"Edit WhatsApp automation settings for this lead form":"manage"===N?"View and edit automation settings for your lead forms":"Build a custom lead form for your ad"})]}),(0,K.jsx)(E.Z,{}),(0,K.jsx)(A.Z,{className:a.content,children:(0,K.jsxs)(A.Z,{className:a.contentInner,children:[Z&&(0,K.jsx)(pt.Z,{severity:"error",onClose:()=>this.setState({error:null,tosLink:null,reconnectRequired:!1}),style:{marginBottom:12},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:Z}),T&&(0,K.jsx)(w.Z,{href:T,target:"_blank",rel:"noopener noreferrer",color:"primary",size:"small",style:{marginTop:8,textTransform:"none"},endIcon:(0,K.jsx)(y.Z,{fontSize:"small"}),children:"Accept Lead Generation Terms of Service"}),this.state.reconnectRequired&&(0,K.jsx)(w.Z,{color:"primary",size:"small",style:{marginTop:8,textTransform:"none"},onClick:()=>{this.props.onClose(),this.props.assistantId&&(window.location.href="/projects/".concat(this.props.assistantId,"/advertisement"))},children:"Reconnect Meta Account"})]})}),D&&(0,K.jsx)(pt.Z,{severity:"success",onClose:()=>this.setState({success:null}),style:{marginBottom:12},children:D}),"manage"===N&&(0,K.jsxs)(A.Z,{children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[(0,K.jsx)(I.Z,{variant:"h6",children:"Existing Lead Forms"}),(0,K.jsx)(w.Z,{variant:"contained",color:"primary",startIcon:(0,K.jsx)(ce.Z,{}),onClick:()=>this.setState({mode:"create",currentStep:0}),style:{textTransform:"none"},children:"Create New Form"})]}),U?(0,K.jsx)(A.Z,{display:"flex",justifyContent:"center",p:4,children:(0,K.jsx)(k.Z,{})}):0===O.length?(0,K.jsx)(A.Z,{p:3,textAlign:"center",children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"No lead forms found. Create one to get started."})}):(0,K.jsx)(Ht.Z,{children:O.map((e=>{var t,a;return(0,K.jsx)(_t.Z,{style:{marginBottom:8},children:(0,K.jsxs)(Gt.Z,{children:[(0,K.jsx)(Vt.Z,{primary:e.name,secondary:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(Wt.Z,{label:e.status||"ACTIVE",size:"small",style:{marginRight:8,height:20,fontSize:"0.7rem"}}),(0,K.jsx)(Wt.Z,{label:null!==(t=e.automation)&&void 0!==t&&t.enabled?"Automation Enabled":"No Automation",size:"small",color:null!==(a=e.automation)&&void 0!==a&&a.enabled?"primary":"default",style:{height:20,fontSize:"0.7rem"}})]})}),(0,K.jsx)(Qt.Z,{children:(0,K.jsx)(w.Z,{variant:"outlined",size:"small",startIcon:(0,K.jsx)(he.Z,{}),onClick:()=>this.loadFormForEdit(e),style:{textTransform:"none"},children:"Edit Automation"})})]})},e.formId)}))})]}),"manage"!==N&&(0,K.jsxs)(f.Z,{container:!0,spacing:2,children:[(0,K.jsx)(f.Z,{item:!0,xs:12,md:2,children:(0,K.jsx)(A.Z,{className:a.sidebar,children:[{id:0,label:"Intro",icon:null},{id:1,label:"Questions",icon:null},{id:2,label:"Privacy Policy",icon:null},{id:3,label:"Completion",icon:null},{id:4,label:"Automation",icon:null}].map((e=>{const t=this.getStepValidation();let i=!0;0===e.id?i=t.intro:1===e.id?i=t.questions:2===e.id?i=t.privacy:3===e.id?i=t.ending:4===e.id&&(i=!0);const s=P===e.id,n="edit"===N&&4!==e.id;return(0,K.jsxs)(A.Z,{className:a.stepItem,onClick:()=>this.setState({currentStep:e.id}
2),style:{backgroundColor:s?"#ebf5f3":"transparent",cursor:"pointer",opacity:n?.6:1},children:[(0,K.jsx)(A.Z,{className:a.stepIndicator,style:{backgroundColor:s?"#0a474c":"#E0E0E0"}}),(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",children:[(0,K.jsx)(I.Z,{variant:"body1",style:{color:s?"#0a474c":"#666",fontWeight:s?600:400,fontSize:"0.9375rem"},children:e.label}),n&&(0,K.jsx)(Jt.Z,{fontSize:"small",style:{color:"#999",fontSize:"14px"}})]})]},e.id)}))})}),(0,K.jsx)(f.Z,{item:!0,xs:12,md:5,children:(0,K.jsxs)(A.Z,{children:[0===P&&(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"subtitle1",gutterBottom:!0,style:{fontWeight:500},children:"Intro \u2022 Optional"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:12},children:"Add a greeting to introduce your form"}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Form Name *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"Enter form name",value:n,onChange:e=>this.setState({formName:e.target.value}),disabled:"edit"===N})]}),(0,K.jsxs)(A.Z,{mb:2,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Form type"}),(0,K.jsxs)(qt.Z,{value:this.state.formType||"more_volume",onChange:e=>this.setState({formType:e.target.value,..."higher_intent"!==e.target.value&&{verifyPhoneWithOtp:!1}}),children:[(0,K.jsx)(zt.Z,{value:"more_volume",control:(0,K.jsx)(M.Z,{color:"primary",size:"small"}),disabled:"edit"===N,label:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"More volume"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Use a form that's quick to fill in and submit on a mobile device."})]}),style:{alignItems:"flex-start",marginBottom:8}}),(0,K.jsx)(zt.Z,{value:"higher_intent",control:(0,K.jsx)(M.Z,{color:"primary",size:"small"}),disabled:"edit"===N,label:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Higher intent"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Add a review step that gives people a chance to confirm their info."})]}),style:{alignItems:"flex-start"}})]}),"higher_intent"===this.state.formType&&(0,K.jsx)(A.Z,{pl:4,mt:.5,children:(0,K.jsx)(zt.Z,{control:(0,K.jsx)(F.Z,{checked:this.state.verifyPhoneWithOtp,onChange:e=>this.setState({verifyPhoneWithOtp:e.target.checked}),color:"primary",size:"small",disabled:"edit"===N}),label:(0,K.jsx)(I.Z,{variant:"caption",children:"Require leads to verify their phone number with a one-time passcode."})})})]}),(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{checked:!1!==this.state.greetingEnabled,onChange:e=>this.setState({greetingEnabled:e.target.checked}),color:"primary",disabled:"edit"===N}),label:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Greeting"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Add a headline and description to introduce your form"})]}),style:{marginBottom:16}}),!1!==this.state.greetingEnabled&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Headline *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"Enter headline",value:this.state.greetingHeadline||"",onChange:e=>this.setState({greetingHeadline:e.target.value}),inputProps:{maxLength:60},error:!this.getStepValidation().intro&&!(this.state.greetingHeadline||"").trim(),disabled:"edit"===N}),!this.getStepValidation().intro&&!(this.state.greetingHeadline||"").trim()&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{marginTop:4,display:"block"},children:"Headline is required when greeting is enabled"}),this.state.greetingHeadline&&(0,K.jsxs)(I.Z,{variant:"caption",color:"textSecondary",style:{marginTop:4,display:"block"},children:[(this.state.greetingHeadline||"").length,"/60"]})]}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Description *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"Enter description",value:this.state.greetingDescription||"",onChange:e=>this.setState({greetingDescription:e.target.value}),error:!this.getStepValidation().intro&&!(this.state.greetingDescription||"").trim(),multiline:!0,rows:2,disabled:"edit"===N}),!this.getStepValidation().intro&&!(this.state.greetingDescription||"").trim()&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{marginTop:4,display:"block"},children:"Description is required when greeting is enabled"})]})]})]}),1===P&&(0,K.jsxs)(A.Z,{children:[(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"subtitle1",gutterBottom:!0,style:{fontWeight:500},children:"Questions \u2022 Optional"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"Add questions to your form to better understand your leads"})]}),(0,K.jsx)(A.Z,{display:"flex",alignItems:"center",gap:1,style:{minWidth:150,justifyContent:"flex-end"}})]}),(0,K.jsx)(A.Z,{style:{minHeight:20,marginTop:4},children:!this.getStepValidation().questions&&this.state.conditionalLogicEnabled&&(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"At least one multiple choice question is required when conditional logic is enabled"})})]}),o.length>0&&(0,K.jsx)(A.Z,{mb:2,children:(0,K.jsx)(Zt.Z5,{onDragEnd:this.handleDragEnd,children:(0,K.jsx)(Zt.bK,{droppableId:"customQuestions",type:"QUESTION",children:e=>(0,K.jsxs)(A.Z,{...e.droppableProps,ref:e.innerRef,children:[o.map(((e,t)=>(0,K.jsx)(Zt._l,{draggableId:e.id,index:t,isDragDisabled:"edit"===this.state.mode,children:(a,i)=>(0,K.jsxs)(_t.Z,{ref:a.innerRef,...a.draggableProps,elevation:i.isDragging?4:1,style:{marginBottom:8,padding:8,backgroundColor:i.isDragging?"#f5f5f5":"white",...a.draggableProps.style},children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",mb:1,children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",gap:1,children:[(0,K.jsx)(A.Z,{...a.dragHandleProps,style:{cursor:"grab"},children:(0,K.jsx)(kt.Z,{fontSize:"small",color:"disabled"})}),(0,K.jsxs)(I.Z,{variant:"caption",color:"textSecondary",children:["Step ",t+1]}),"CUSTOM"===e.type&&(0,K.jsx)(Wt.Z,{label:this.getQuestionTypeDisplayName(e),size:"small",variant:"outlined",style:{marginLeft:8,height:20,fontSize:"0.65rem"}}),"DATE_TIME"===e.type&&(0,K.jsx)(Wt.Z,{label:this.getQuestionTypeDisplayName(e),size:"small",variant:"outlined",style:{marginLeft:8,height:20,fontSize:"0.65rem"}})]}),(0,K.jsx)(b.Z,{size:"small",onClick:()=>this.handleRemoveQuestion(e.id),style:{padding:4},title:"Delete question",children:"edit"!==N&&(0,K.jsx)(Kt.Z,{fontSize:"small"})})]}),this.renderQuestion(e,t,a)]})},e.id))),e.placeholder]})})})}),(0,K.jsxs)(A.Z,{mb:2,children:["edit"!==N&&(0,K.jsx)(w.Z,{variant:"outlined",startIcon:(0,K.jsx)(ce.Z,{}),onClick:e=>{const t=e.currentTarget;this.setState({questionDropdownAnchor:t})},style:{textTransform:"none"},children:"Add question"}
2),this.state.questionDropdownAnchor&&(0,K.jsxs)(Yt.Z,{anchorEl:this.state.questionDropdownAnchor,open:Boolean(this.state.questionDropdownAnchor),onClose:()=>this.setState({questionDropdownAnchor:null}),children:[(0,K.jsx)(de.Z,{onClick:()=>{this.handleAddQuestion("MULTIPLE_CHOICE"),this.setState({questionDropdownAnchor:null})},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Multiple choice"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Add questions and conditional logic to filter leads"})]})}),(0,K.jsx)(de.Z,{onClick:()=>{this.handleAddQuestion("SHORT_ANSWER"),this.setState({questionDropdownAnchor:null})},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Short answer"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Get additional info in a sentence or 2"})]})}),(0,K.jsx)(de.Z,{onClick:()=>{this.handleAddQuestion("DATE_TIME"),this.setState({questionDropdownAnchor:null})},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Appointment time"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Let people request a time to meet with you"})]})})]})]}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"subtitle1",style:{fontWeight:500},gutterBottom:!0,children:"Contact information"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8,display:"block"},children:"Ask for contact information and additional personal details. This will be prefilled from their Facebook account."}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Description"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"Let people know how the information that they give you will be used or shared. See examples",value:this.state.contactInfoDescription||"",onChange:e=>this.setState({contactInfoDescription:e.target.value}),multiline:!0,rows:2})]}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:8,fontWeight:500},children:"Contact Information Fields"}),r.filter((e=>e.enabled)).length>0?(0,K.jsx)(A.Z,{children:r.filter((e=>e.enabled)).map((e=>{const t=Xt.dh.find((t=>t.value===e.type));if(!t)return null;const i="FULL_NAME"===e.type||"PHONE"===e.type;return(0,K.jsxs)(A.Z,{mb:1,p:1,style:{border:"1px solid #e0e0e0",borderRadius:6,backgroundColor:"#f9f9fb"},children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",children:[(0,K.jsxs)(A.Z,{display:"flex",flexDirection:"column",gap:.5,flex:1,children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",gap:.5,children:[e.locked&&(0,K.jsx)(Jt.Z,{fontSize:"small",color:"disabled"}),(0,K.jsxs)(I.Z,{variant:"caption",style:{fontWeight:500},children:[t.label,e.isMandatory&&(0,K.jsx)("span",{children:" *"})]})]}),e.locked?(0,K.jsx)(Wt.Z,{label:"Parameter: ".concat(e.type),size:"small",style:{height:20,fontSize:"0.65rem",backgroundColor:"#f5f5f5",color:"#666",alignSelf:"flex-start"}}):(0,K.jsxs)(A.Z,{mt:.5,children:[(0,K.jsxs)(L.Z,{select:!0,size:"small",variant:"outlined",fullWidth:!0,value:e.mappedParameter||"",onChange:a=>{const i=a.target.value;if("create_new"===i){const a=t.label||e.type,i=this.generateKeyFromName(a);this.setState({creatingParameterFor:"contact_".concat(e.type),newParamName:a,newParamKey:i,creatingParameterForFieldType:e.type})}else this.handleContactFieldParameterChange(e.type,i)},SelectProps:{displayEmpty:!0,renderValue:e=>{if(!e)return"Don't map";if("create_new"===e)return"Create new parameter...";const t=this.state.availableParameters.find((t=>t.key===e));return t?t.name:e}},style:{minWidth:200},classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},children:[(0,K.jsx)(de.Z,{value:"",children:"Don't map"}),this.state.availableParameters.map((e=>(0,K.jsxs)(de.Z,{value:e.key,children:[e.name," (",e.key,")"]},e.key))),(0,K.jsx)(de.Z,{value:"create_new",children:"Create new parameter..."})]}),this.state.creatingParameterFor==="contact_".concat(e.type)&&(0,K.jsxs)(A.Z,{mt:1,p:1,style:{border:"1px solid #e0e0e0",borderRadius:4,backgroundColor:"#fafafa"},children:[(0,K.jsx)(L.Z,{fullWidth:!0,size:"small",variant:"outlined",label:"Parameter Name",value:this.state.newParamName,onChange:e=>this.setState({newParamName:e.target.value}),style:{marginBottom:8},classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}}}),(0,K.jsx)(L.Z,{fullWidth:!0,size:"small",variant:"outlined",label:"Parameter Key",value:this.state.newParamKey,onChange:e=>this.setState({newParamKey:e.target.value}),helperText:"Lowercase letters, numbers, and underscores only. Must start with a letter.",style:{marginBottom:8},classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}}}),(0,K.jsxs)(A.Z,{display:"flex",gap:1,children:[(0,K.jsx)(w.Z,{size:"small",variant:"contained",color:"primary",onClick:async()=>{await this.handleCreateNewParameter("contact_".concat(e.type),this.state.newParamName,this.state.newParamKey)},children:"Save Parameter"}),(0,K.jsx)(w.Z,{size:"small",onClick:()=>{this.setState({creatingParameterFor:null,newParamName:"",newParamKey:"",creatingParameterForFieldType:null})},children:"Cancel"})]})]})]})]}),!i&&(0,K.jsx)(b.Z,{size:"small",onClick:()=>this.handleRemoveContactField(e.type),style:{padding:4},children:(0,K.jsx)(Kt.Z,{fontSize:"small"})})]}),"PHONE"===e.type&&"higher_intent"===this.state.formType&&l&&(0,K.jsx)(A.Z,{mt:.5,pl:4,children:(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Verified with a one-time passcode (set under Form type)"})})]},e.type)}))}):(0,K.jsx)(A.Z,{mb:2,children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:'No contact fields added yet. Use "Add category" below to add fields.'})}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(w.Z,{variant:"outlined",startIcon:(0,K.jsx)(ce.Z,{}),onClick:e=>{const t=e.currentTarget;this.setState({categoryDropdownAnchor:t})},style:{textTransform:"none"},children:"Add category"}
2),(0,K.jsx)(Yt.Z,{anchorEl:this.state.categoryDropdownAnchor,open:Boolean(this.state.categoryDropdownAnchor),onClose:()=>this.setState({categoryDropdownAnchor:null,submenuAnchor:null,submenuCategory:null}),getContentAnchorEl:null,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:Xt.pD.map((e=>(0,K.jsx)(de.Z,{onMouseEnter:t=>{this.setState({submenuAnchor:t.currentTarget,submenuCategory:e.id})},style:{minWidth:180},children:(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",children:[(0,K.jsx)(I.Z,{variant:"body2",children:e.label}),(0,K.jsx)(u.Z,{fontSize:"small",style:{marginLeft:8,fontSize:14}})]})},e.id)))}),(0,K.jsx)(Yt.Z,{anchorEl:this.state.submenuAnchor,open:Boolean(this.state.submenuAnchor)&&Boolean(this.state.submenuCategory),onClose:()=>this.setState({submenuAnchor:null,submenuCategory:null}),getContentAnchorEl:null,anchorOrigin:{vertical:"top",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"left"},style:{pointerEvents:"none"},PaperProps:{style:{pointerEvents:"auto"}},children:this.state.submenuCategory&&(null===(e=Xt.pD.find((e=>e.id===this.state.submenuCategory)))||void 0===e?void 0:e.types.map((e=>{const t=Xt.dh.find((t=>t.value===e));if(!t)return null;const a=r.find((t=>t.type===e)),i=null===a||void 0===a?void 0:a.enabled;return(0,K.jsx)(de.Z,{onClick:()=>this.handleAddFieldFromCategory(e),disabled:(null===a||void 0===a?void 0:a.locked)||i,style:{minWidth:150},children:(0,K.jsxs)(I.Z,{variant:"body2",children:[t.label,i&&(0,K.jsx)("span",{style:{color:"#999",marginLeft:8},children:"(Added)"})]})},e)})))})]})]})]}),2===P&&(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"subtitle1",gutterBottom:!0,style:{fontWeight:500},children:"Privacy Policy"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:12},children:"Add your privacy policy URL and link text"}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Privacy Policy URL *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"https://yoursite.com/privacy",value:d,onChange:e=>this.setState({privacyPolicyUrl:e.target.value}),error:!this.getStepValidation().privacy}),!this.getStepValidation().privacy&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{marginTop:4,display:"block"},children:"Privacy Policy URL is required"})]}),(0,K.jsxs)(A.Z,{mb:1.5,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Link Text"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"Privacy Policy",value:c,onChange:e=>this.setState({privacyPolicyLinkText:e.target.value})})]})]}),3===P&&(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"subtitle1",gutterBottom:!0,style:{fontWeight:500},children:"Completion"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:12},children:"Customize the thank you page shown after form submission"}),(0,K.jsxs)(f.Z,{container:!0,spacing:2,children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Title"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"Thank you!",value:p,onChange:e=>this.setState({thankYouTitle:e.target.value})})]}),(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Body"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"We'll be in touch shortly.",multiline:!0,rows:2,value:h,onChange:e=>this.setState({thankYouBody:e.target.value})})]}),(0,K.jsxs)(f.Z,{item:!0,xs:6,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Button Type"}),(0,K.jsx)(L.Z,{select:!0,fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding},style:{height:"40px"}},value:m||"",onChange:e=>this.handleButtonTypeChange(e.target.value),SelectProps:{renderValue:e=>{const t=Xt.S$.find((t=>t.value===e));return t?t.label:""},displayEmpty:!0},children:Xt.S$.map((e=>(0,K.jsx)(de.Z,{value:e.value,children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:e.label}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:e.description})]})},e.value)))})]}),(0,K.jsxs)(f.Z,{item:!0,xs:6,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Button Text"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding},style:{height:"40px"}},placeholder:"Visit Website",value:g,onChange:e=>this.setState({thankYouButtonText:e.target.value})})]}),"VIEW_WEBSITE"===m&&(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Website URL *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"https://yoursite.com",value:x,onChange:e=>this.setState({thankYouWebsiteUrl:e.target.value}),onBlur:()=>this.setState({thankYouWebsiteUrl:(0,Xt.W7)(this.state.thankYouWebsiteUrl)}),error:!this.getStepValidation().ending}),!this.getStepValidation().ending&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{marginTop:4,display:"block"},children:x.trim()?"Please enter a valid URL (e.g., https://example.com)":"Website URL is required"})]}),"CALL_BUSINESS"===m&&(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:4},children:"Business Phone Number *"}),(0,K.jsx)(L.Z,{fullWidth:!0,variant:"outlined",classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}},placeholder:"+1234567890",value:this.state.thankYouPhoneNumber,onChange:e=>this.setState({thankYouPhoneNumber:e.target.value}),error:!this.getStepValidation().ending}),!this.getStepValidation().ending&&(0,K.jsx)(I.Z,{variant:"caption",color:"error",style:{marginTop:4,display:"block"},children:"Business Phone Number is required"})]})]}),(0,K.jsxs)(A.Z,{mt:2,children:[(0,K.jsx)(I.Z,{variant:"subtitle2",gutterBottom:!0,children:"Advanced Settings"}),(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{checked:S,onChange:e=>this.setState({blockDisplayForNonTargetedViewer:e.target.checked}),color:"primary"}),label:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Filter Organic Leads"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Only show form to ad viewers"})]})})]})]}),(4===P||"edit"===N)&&(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"subtitle1",gutterBottom:!0,style:{fontWeight:500,marginBottom:8},children:"edit"===N?"WhatsApp Automation":"Automation \u2022 Optional"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:16},children:"Configure WhatsApp automation to automatically send messages to leads when they submit the form at Meta."}),(0,K.jsx)(Ia,{automation:this.state.automation,onChange:e=>{this.setState({automation:e})},onGetConfigRef:e=>{this.getAutomationConfigRef=e},onPreviewDataChange:e=>
2{this.setState({automationPreviewData:e,previewCarouselIndex:e.carouselIndex||0})},questions:"edit"===N&&null!==R&&void 0!==R&&R.questions?R.questions.map((e=>{var t;return{key:e.key||(null===(t=e.type)||void 0===t?void 0:t.toLowerCase()),label:e.label||e.type}})):this.getAllQuestions(),assistantId:this.props.assistantId,classes:a})]})]})}),(0,K.jsx)(f.Z,{item:!0,xs:12,md:5,children:(0,K.jsx)(A.Z,{style:{position:"sticky",top:20,display:"flex",justifyContent:"center",alignItems:"flex-start",width:"100%"},children:4===P&&null!==(t=this.state.automationPreviewData)&&void 0!==t&&t.selectedTemplate?(0,K.jsx)(A.Z,{style:{width:"100%",maxWidth:340,padding:"16px"},children:(0,K.jsx)(ja.Z,{media:this.state.automationPreviewData.media||{},parameters:this.state.automationPreviewData.parameters||[],selectedTemplate:this.state.automationPreviewData.selectedTemplate,showDisclaimer:!0,carouselIndex:this.state.previewCarouselIndex,setCarouselIndex:e=>{this.setState({previewCarouselIndex:e})},cards:this.state.automationPreviewData.cards||[],formattedButtons:[]})}):4===P?(0,K.jsx)(A.Z,{style:{width:"100%",maxWidth:320,padding:"16px"},children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",align:"center",children:"Select a template to see preview"})}):(0,K.jsx)(A.Z,{style:{width:"100%",maxWidth:320},children:(0,K.jsx)(ha,{classes:this.props.classes,formName:n,customQuestions:o,contactInfoFields:r.filter((e=>e.enabled)),verifyPhoneWithOtp:l,privacyPolicyUrl:d,privacyPolicyLinkText:c,thankYouTitle:p,thankYouBody:h,thankYouButtonText:g,thankYouButtonType:m,previewMode:B,builderStep:P,greetingHeadline:this.state.greetingHeadline,greetingDescription:this.state.greetingDescription,greetingEnabled:this.state.greetingEnabled})})})})]})]})}),"manage"!==N&&(0,K.jsx)(A.Z,{className:a.footer,children:"edit"===N?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(w.Z,{variant:"outlined",onClick:s,style:{textTransform:"none"},children:"Cancel"}),(0,K.jsx)(w.Z,{variant:"contained",color:"primary",onClick:this.handleUpdateAutomation,disabled:z,style:{textTransform:"none"},children:z?"Saving...":"Save Changes"})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(w.Z,{variant:"outlined",onClick:()=>{P>0&&this.setState({currentStep:P-1})},disabled:0===P,style:{textTransform:"none"},children:"Previous"}),(0,K.jsx)(A.Z,{display:"flex",gap:1,children:P<4?(0,K.jsx)(w.Z,{variant:"contained",color:"primary",onClick:()=>{P<4&&this.setState({currentStep:P+1})},style:{textTransform:"none"},children:"Next"}):(0,K.jsx)(w.Z,{variant:"contained",color:"primary",onClick:this.handleCreateForm,disabled:j||!this.isFormValid(),style:{textTransform:"none"},children:j?"Creating...":"Create Form"})})]})})]})}),this.state.conditionalQuestionMenuAnchor&&(0,K.jsxs)(Yt.Z,{anchorEl:this.state.conditionalQuestionMenuAnchor,open:Boolean(this.state.conditionalQuestionMenuAnchor),onClose:()=>this.setState({conditionalQuestionMenuAnchor:null,conditionalQuestionParentId:null,conditionalQuestionOptionKey:null}),children:[(0,K.jsx)(de.Z,{onClick:()=>{this.handleCreateConditionalQuestion("SHORT_ANSWER"),this.setState({conditionalQuestionMenuAnchor:null})},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Short answer"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Get additional info in a sentence or 2"})]})}),(0,K.jsx)(de.Z,{onClick:()=>{this.handleCreateConditionalQuestion("MULTIPLE_CHOICE"),this.setState({conditionalQuestionMenuAnchor:null})},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Multiple choice"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Add questions and conditional logic to filter leads"})]})}),!this.hasAppointmentQuestion()&&(0,K.jsx)(de.Z,{onClick:()=>{this.handleCreateConditionalQuestion("DATE_TIME"),this.setState({conditionalQuestionMenuAnchor:null})},children:(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"body2",children:"Appointment time"}),(0,K.jsx)(I.Z,{variant:"caption",color:"textSecondary",children:"Let people request a time to meet with you"})]})})]})]})}}const Ta=(0,N.Z)((e=>({drawerPaper:{width:"90%",maxWidth:1200,[e.breakpoints.down("md")]:{width:"95%"},[e.breakpoints.down("sm")]:{width:"100%"}},drawerContainer:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#fff"},header:{padding:"20px 24px",backgroundColor:"#fff",borderBottom:"1px solid #e0e0e0",[e.breakpoints.down("sm")]:{padding:"16px"}},headerTitle:{fontWeight:600,fontSize:18},content:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",backgroundColor:"#F9F9FB"},contentInner:{flex:1,overflow:"auto",padding:"16px",[e.breakpoints.down("sm")]:{padding:"12px"}},TextFieldRoot:{width:"100%",padding:"2px",marginTop:"4px",background:"rgb(240,240,240)"},inputPadding:{padding:"8px 10px"},footer:{padding:"16px 70px 16px 40px",borderTop:"1px solid #e0e0e0",display:"flex",justifyContent:"space-between",alignItems:"center",backgroundColor:"#fff",gap:16,flexShrink:0,[e.breakpoints.down("sm")]:{padding:"12px 16px",flexDirection:"column",gap:12}},questionCard:{padding:"16px",borderRadius:8,backgroundColor:"#fff",boxShadow:"0 1px 3px rgba(0,0,0,0.05)"},formCard:{padding:"20px",borderRadius:8,backgroundColor:"#fff",boxShadow:"0 1px 3px rgba(0,0,0,0.05)"},previewContainer:{position:"sticky",top:0,padding:"16px",backgroundColor:"#F9F9FB",borderRadius:8,minHeight:400},sidebar:{padding:e.spacing(1.5),backgroundColor:"#F9F9FB",borderRadius:8,minHeight:400,position:"sticky",top:e.spacing(1)},stepItem:{display:"flex",alignItems:"center",gap:e.spacing(1),padding:e.spacing(1,.75),borderRadius:4,marginBottom:e.spacing(.75),cursor:"pointer",transition:"background-color 0.2s"},stepIndicator:{width:12,height:12,borderRadius:"50%",flexShrink:0}})))(Za);class Da extends r.Component{constructor(e){super(e),this.isDuplicateAd=window.location.pathname.includes("duplicate"),this.isCreateAd=window.location.pathname.includes("create"),this.updateFormatIndicatorStyle=()=>{const{adFormat:e,uploadType:t}=this.props.parentState||{},a=("carousel"===e?this.carouselTabRef:"VIDEO_UPLOAD"===t?this.videoTabRef:this.imageTabRef).current;if(!a)return;const{offsetLeft:i,offsetWidth:s}=a;this.setState((e=>e.formatIndicatorStyle.left===i&&e.formatIndicatorStyle.width===s&&1===e.formatIndicatorStyle.opacity?null:{formatIndicatorStyle:{left:i,width:s,opacity:1}}))},this.scheduleFormatIndicatorUpdate=()=>{this.formatIndicatorRaf&&cancelAnimationFrame(this.formatIndicatorRaf),this.formatIndicatorRaf=requestAnimationFrame((()=>{this.formatIndicatorRaf=null,this.updateFormatIndicatorStyle()}
2))},this.checkLeadFormPermissions=async()=>{var e,t,a,s;const n=null===(e=this.props.assistantDetails)||void 0===e?void 0:e.assistantId,o=(null===(t=this.props.pageDetails)||void 0===t?void 0:t.pageId)||(null===(a=this.props.parentState)||void 0===a||null===(s=a.selectedPage)||void 0===s?void 0:s.pageId);if(n&&o){this.setState({checkingPermissions:!0});try{var r;const e=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/permissions/check"),{params:{assistantId:n,pageId:o}});null!==(r=e.data)&&void 0!==r&&r.status&&this.setState({hasLeadFormPermissions:e.data.hasLeadFormPermissions||!1,leadFormTosAccepted:e.data.leadFormTosAccepted||!1,checkingPermissions:!1})}catch(l){console.error("Error checking lead form permissions:",l),this.setState({hasLeadFormPermissions:!1,leadFormTosAccepted:!1,checkingPermissions:!1})}}},this.fetchLeadForms=async()=>{var e,t;const{assistantDetails:a,pageDetails:s}=this.props,n=null===a||void 0===a?void 0:a.assistantId,o=(null===s||void 0===s?void 0:s.pageId)||(null===(e=this.props.parentState)||void 0===e||null===(t=e.selectedPage)||void 0===t?void 0:t.pageId);if(console.log("fetchLeadForms called:",{assistantId:n,pageId:o,pageDetails:s}),n&&o){this.setState({isLoadingLeadForms:!0});try{var r,l;const e=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms"),{params:{assistantId:n,pageId:o,status:"ACTIVE",limit:50}});if(console.log("Lead forms API response:",e.data),null!==(r=e.data)&&void 0!==r&&r.status&&null!==(l=e.data)&&void 0!==l&&l.data){const t=e.data.data;this.setState({leadForms:t});const{parentState:a,changeState:i}=this.props,s=null===a||void 0===a?void 0:a.leadFormId,n=null===a||void 0===a?void 0:a.leadForm;if(s&&(null===n||void 0===n||!n.value)){const e=t.find((e=>e.formId===s));e&&(console.log("Auto-selecting lead form from saved leadFormId:",e),i("leadForm",{label:e.name,value:e.formId,...e}))}}}catch(d){console.error("Error fetching lead forms:",d)}finally{this.setState({isLoadingLeadForms:!1})}}else console.log("Missing assistantId or pageId, skipping lead forms fetch")},this.handleOpenLeadFormDrawer=()=>{this.setState({leadFormDrawerOpen:!0})},this.handleCloseLeadFormDrawer=()=>{this.setState({leadFormDrawerOpen:!1,editingLeadForm:null})},this.handleLeadFormCreated=e=>{this.fetchLeadForms(),null!==e&&void 0!==e&&e.formId&&(this.props.changeState("leadForm",{label:e.name,value:e.formId,...e}),this.props.changeState("leadFormId",e.formId))},this.handleSyncLeadFormsFromMeta=async()=>{var e,t;const{assistantDetails:a,pageDetails:s}=this.props,n=null===a||void 0===a?void 0:a.assistantId,o=(null===s||void 0===s?void 0:s.pageId)||(null===(e=this.props.parentState)||void 0===e||null===(t=e.selectedPage)||void 0===t?void 0:t.pageId);if(n&&o){this.setState({isSyncingLeadForms:!0});try{var r;const e=await i.Z.post("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/sync"),{assistantId:n,pageId:o});var l,d;if(null!==(r=e.data)&&void 0!==r&&r.status)await this.fetchLeadForms(),console.log((null===(l=e.data)||void 0===l?void 0:l.message)||"Successfully synced lead forms from Meta");else console.error("Failed to sync lead forms:",null===(d=e.data)||void 0===d?void 0:d.message)}catch(c){console.error("Error syncing lead forms:",c)}finally{this.setState({isSyncingLeadForms:!1})}}else console.log("Missing assistantId or pageId, skipping sync")},this.handleLeadFormSelected=e=>{this.props.changeState("leadForm",e),this.props.changeState("leadFormId",(null===e||void 0===e?void 0:e.value)||(null===e||void 0===e?void 0:e.formId)||""),this.setState({leadFormDrawerOpen:!1})},this.hasLeadFormPermissions=()=>{const{assistantDetails:e}=this.props,t=(null===e||void 0===e?void 0:e.fbGrantedScopes)||"";return t.includes("pages_manage_ads")&&t.includes("leads_retrieval")},this.onMediaSelect=e=>{const{mediaType:t}=this.state,{uploadType:a}=this.props.parentState;if("VIDEO_UPLOAD"===a&&"VIDEO"===t)this.props.changeState("videoFile",e);else if("VIDEO_UPLOAD"===a&&"IMAGE"===t)this.props.changeState("thumbnailUrl",e);else if("IMAGE"===t&&"IMAGE_UPLOAD"===a)this.props.changeState("imageFile",e);else if("AI_UPLOAD"===a&&e&&e.length>0){const t=e[0];"VIDEO"===t.fileType?this.props.changeState("videoFile",t):"IMAGE"===t.fileType&&this.props.changeState("imageFile",t)}},this.handleInput=e=>{const{name:t,value:a}=e.target;this.props.changeState(t,a);const i={selectedMedia:{},previewImageUrl:(0,Ae.replaceDomainInData)(e.target.value)};this.props.createnewAds(i)},this.onChangename=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<256&&this.props.changeState(t,a)},this.onChangeCaption=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<=2200&&this.props.changeState(t,a)},this.onChangeHeadline=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<=40&&this.props.changeState(t,a)},this.onChangeHeadlineDescription=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<=30&&this.props.changeState(t,a)},this.onImageGeneration=e=>{const t="string"===typeof e?{publicUrl:e,fileName:"Generated Image",fileType:"IMAGE"}:{...e,fileType:"IMAGE"};this.props.changeState("imageFile",t),this.props.changeState("uploadType","IMAGE_UPLOAD")},this.onVideoGeneration=e=>{const t="string"===typeof e?{publicUrl:e,fileName:"Generated Video",fileType:"VIDEO"}:{...e,fileType:"VIDEO"};this.props.changeState("videoFile",t),this.props.changeState("uploadType","VIDEO_UPLOAD")},this.handleUploadTypeToggle=(e,t)=>
2{"IMAGE_UPLOAD"===t?this.props.changeState("uploadType","IMAGE_UPLOAD"):"VIDEO_UPLOAD"===t&&this.props.changeState("uploadType","VIDEO_UPLOAD")},this.handleGenerationStateChange=e=>{this.setState({isGenerating:e.isGenerating,isImageGenerating:e.isImageGenerating,isVideoGenerating:e.isVideoGenerating}),this.props.onGenerationStateChange&&this.props.onGenerationStateChange(e)},this.validateUrl=e=>{if(!e)return"";return/^https:\/\/([\w-]+\.)+[\w-]+(\/[^\s]*)?$/.test(e)?"":"Please enter a valid URL (e.g., https://example.com)"},this.handleWebsiteUrlChange=e=>{const{changeState:t}=this.props,a=e.target.value;t("websiteUrl",a);const i=this.validateUrl(a);this.setState({websiteUrlError:i})},this.handleWebsiteUrlBlur=e=>{const t=e.target.value,a=this.validateUrl(t);this.setState({websiteUrlError:a})},this.state={openMediaDialog:!1,mediaType:"IMAGE",isResolutionDropdownOpen:!1,adType:"image",isGenerating:!1,isImageGenerating:!1,isVideoGenerating:!1,websiteUrlError:"",leadFormDrawerOpen:!1,leadForms:[],isLoadingLeadForms:!1,isSyncingLeadForms:!1,editingLeadForm:null,hasLeadFormPermissions:null,leadFormTosAccepted:!1,checkingPermissions:!1,formatIndicatorStyle:{left:0,width:0,opacity:0}},this.imageTabRef=r.createRef(),this.videoTabRef=r.createRef(),this.carouselTabRef=r.createRef()}componentDidMount(){var e,t;const{websiteUrl:a}=this.props.parentState;a&&this.setState({websiteUrlError:this.validateUrl(a)}),"LEAD"===(null===(e=this.props.parentState)||void 0===e||null===(t=e.adType)||void 0===t?void 0:t.type)&&(this.checkLeadFormPermissions(),this.fetchLeadForms()),this.scheduleFormatIndicatorUpdate()}componentWillUnmount(){this.formatIndicatorRaf&&cancelAnimationFrame(this.formatIndicatorRaf)}componentDidUpdate(e){var t,a,i,s,n,o,r,l,d,c,p,u,h,m;const g="LEAD"===(null===(t=this.props.parentState)||void 0===t||null===(a=t.adType)||void 0===a?void 0:a.type),x="LEAD"===(null===(i=e.parentState)||void 0===i||null===(s=i.adType)||void 0===s?void 0:s.type),v=null===(n=this.props.pageDetails)||void 0===n?void 0:n.pageId,y=null===(o=e.pageDetails)||void 0===o?void 0:o.pageId;g&&!x&&(console.log("Ad type changed to LEAD, fetching lead forms"),this.checkLeadFormPermissions(),this.fetchLeadForms()),g&&v&&v!==y&&(console.log("Page details changed while on LEAD ad type, fetching lead forms"),this.checkLeadFormPermissions(),this.fetchLeadForms()),(null===(r=e.parentState)||void 0===r?void 0:r.adFormat)===(null===(l=this.props.parentState)||void 0===l?void 0:l.adFormat)&&(null===(d=e.parentState)||void 0===d?void 0:d.uploadType)===(null===(c=this.props.parentState)||void 0===c?void 0:c.uploadType)&&(null===(p=e.parentState)||void 0===p||null===(u=p.adType)||void 0===u?void 0:u.value)===(null===(h=this.props.parentState)||void 0===h||null===(m=h.adType)||void 0===m?void 0:m.value)||this.scheduleFormatIndicatorUpdate()}render(){var e,t,a,i,s,n,o,r,l,d,c;const{classes:p,parentState:u,isLiveAD:h,assistantDetails:m,pageDetails:g}=this.props,{adName:x,adCaption:v,adHeadline:y,adHeadlineDescription:b,imageFile:S,videoFile:C,thumbnailUrl:Z,ctaButton:T="APPLY_NOW",websiteUrl:D="",leadForm:P,adFormat:B="single",cards:N=[],uploadType:F}=u,M=Dt(null===u||void 0===u||null===(e=u.adType)||void 0===e?void 0:e.value),R="carousel"===B,O=R?"":y,U=R?"":b,z=D,_=R?"Headlines and descriptions are added per card in Carousel mode \u2014 edit them in the card strip below.":"",{leadForms:W,isLoadingLeadForms:H,leadFormDrawerOpen:G,hasLeadFormPermissions:V,leadFormTosAccepted:Q,checkingPermissions:q,isSyncingLeadForms:Y}=this.state,J=[{value:"APPLY_NOW",label:"Apply now"},{value:"BOOK_NOW",label:"Book now"},{value:"CONTACT_US",label:"Contact us"},{value:"DOWNLOAD",label:"Download"},{value:"LEARN_MORE",label:"Learn more"},{value:"SEE_MENU",label:"See menu"},{value:"SHOP_NOW",label:"Shop now"},{value:"SIGN_UP",label:"Sign up"},{value:"WATCH_MORE",label:"Watch more"},{value:"DONATE_NOW",label:"Donate now"}],X="LEAD"===(null===u||void 0===u||null===(t=u.adType)||void 0===t?void 0:t.type),$=X?Xt.$7:J;return(0,K.jsxs)(f.Z,{container:!0,spacing:this.props.isSmallScreen?2:4,marginTop:"3em",children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,md:12,style:{display:"flex",flexDirection:"column",justifyContent:"center",minWidth:"221px",marginBottom:"20px"},children:[(0,K.jsx)(f.Z,{container:!0,style:{display:"flex",justifyContent:"space-between",gap:"20px"},className:p.bottomMargin,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Ad Name"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((x||"").length,"/255")})]}),(0,K.jsx)(j.ZP,{title:h&&!this.isDuplicateAd?"You can't edit the Ad name once the ad is live":"",placement:"top",children:this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},placeholder:"Enter Ad Name ",name:"adName",id:"adName",onChange:this.onChangename,value:x,disabled:h&&!this.isDuplicateAd}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})})]})}),(0,K.jsx)(f.Z,{container:!0,style:{display:"flex",gap:"20px"},className:p.bottomMargin,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Primary Text"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((v||"").length,"/2200")})]}),this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},placeholder:"Enter Ad Caption ",name:"adCaption",id:"adCaption",onChange:this.onChangeCaption,value:v,multiline:!0,rows:4}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:100,style:{borderRadius:"10px"}})]})}),(0,K.jsxs)(f.Z,{container:!0,style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"20px"},className:p.bottomMargin,children:["whatsapp_status"!==(null===u||void 0===u||null===(a=u.adType)||void 0===a?void 0:a.value)&&(0,K.jsxs)(f.Z,{item:!0,style:{minWidth:0},children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",className:R?p.mutedFieldLabel:void 0,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Headline"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((O||"").length,"/40")})]}),this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(j.ZP,{title:_,placement:"top",children:(0,K.jsx)("div",{children:(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},placeholder:"Enter Display Headline ",name:"adHeadline",id:"adHeadline",onChange:this.onChangeHeadline,value:O,disabled:R,multiline:!0,rows:1})})}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]}),"whatsapp_status"!==(null===u||void 0===u||null===(i=u.adType)||void 0===i?void 0:i.value)&&(0,K.jsxs)(f.Z,{item:!0,style:{minWidth:0},children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",className:R?p.mutedFieldLabel:void 0,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Description"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((U||"").length,"/30")})]}),this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(j.ZP,{title:_,placement:"top",children:(0,K.jsx)("div",{children:(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},placeholder:"Enter Description ",name:"adHeadlineDescription",id:"adHeadlineDescription",onChange:this.onChangeHeadlineDescription,value:U,disabled:R,multiline:!0,rows:1})})}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]})]}),["website_traffic","website_to_whatsapp"].includes(null===u||void 0===u||null===(s=u.adType)||void 0===s?void 0:s.value)&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(A.Z,{display:"flex",style:{gap:"20px"},className:p.bottomMargin,flexWrap:"wrap",alignItems:"flex-start",children:[(0,K.jsxs)(A.Z,{flex:1,minWidth:"300px",display:"flex",flexDirection:"column",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"CTA Button"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Select the CTA button for your ad"}),u.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{select:!0,variant:"outlined",fullWidth:!0,classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},name:"ctaButton",value:T,onChange:e=>this.props.changeState("ctaButton",e.target.value),placeholder:"Select CTA Button",children:J.map((e=>(0,K.jsx)(de.Z,{value:e.value,children:e.label},e.value)))}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]}
2),!R&&(0,K.jsxs)(A.Z,{flex:1,minWidth:"300px",display:"flex",flexDirection:"column",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Destination"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Enter the Destination URL"}),u.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",fullWidth:!0,classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},placeholder:"https://example.com",name:"websiteUrl",id:"websiteUrl",onChange:this.handleWebsiteUrlChange,onBlur:this.handleWebsiteUrlBlur,value:z,type:"url",error:!!this.state.websiteUrlError,helperText:this.state.websiteUrlError,FormHelperTextProps:{style:{marginTop:"4px",fontSize:"12px"}}}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]})]}),"website_to_whatsapp"===(null===u||void 0===u||null===(n=u.adType)||void 0===n?void 0:n.value)&&(0,K.jsx)(A.Z,{className:p.bottomMargin,minWidth:"300px",maxWidth:"640px",children:(0,K.jsxs)(A.Z,{display:"flex",alignItems:"flex-start",style:{gap:"8px",padding:"8px 12px",borderRadius:"8px",background:"rgba(29, 158, 117, 0.08)"},children:[(0,K.jsx)(ye.Z,{style:{color:"#1D9E75",fontSize:"18px",marginTop:"2px"}}),(0,K.jsxs)(A.Z,{children:[(0,K.jsxs)(I.Z,{variant:"body2",style:{color:"#0F6E56"},children:["Your website will open with a WhatsApp button \u2014 replies go to ",(null===g||void 0===g?void 0:g.whatsappNumber)||"the number"," \u2014 the verified number on \u201c",(null===g||void 0===g?void 0:g.pageName)||"your Page","\u201d. Set automatically."]}),(0,K.jsxs)(I.Z,{variant:"body2",style:{color:"#0F6E56",marginTop:"4px"},children:[(0,K.jsx)("b",{children:"Note:"})," the WhatsApp button appears only when the ad is opened in the Facebook or Instagram mobile app. Clicks from desktop browsers open your website without the button."]})]})]})})]}),X&&(0,K.jsx)(K.Fragment,{children:(0,K.jsxs)(A.Z,{display:"flex",style:{gap:"20px"},className:p.bottomMargin,flexWrap:"wrap",alignItems:"flex-start",children:[(0,K.jsxs)(A.Z,{flex:2,minWidth:"300px",display:"flex",flexDirection:"column",children:[(0,K.jsx)(A.Z,{mb:1,children:(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:1,children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Lead Form"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Select or create a lead form to collect user information"})]}),(0,K.jsx)(j.ZP,{title:Q&&V?"":Q?"Missing pages_manage_ads permission. Please reconnect your Meta account":"Please accept Lead Form Terms of Service in the Ads Setup page",placement:"top",children:(0,K.jsx)("span",{children:(0,K.jsx)(w.Z,{variant:"outlined",color:"primary",size:"small",startIcon:(0,K.jsx)(ce.Z,{}),onClick:this.handleOpenLeadFormDrawer,style:{textTransform:"none",marginTop:4},disabled:!Q||!V||q,children:"Create New"})})})]})}),u.isAdFetched||this.isCreateAd?(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(j.ZP,{title:Q&&V?"":Q?"Missing pages_manage_ads permission. Please reconnect your Meta account":"Please accept Lead Form Terms of Service in the Ads Setup page",placement:"top",children:(0,K.jsx)("div",{children:(0,K.jsxs)(L.Z,{select:!0,variant:"outlined",fullWidth:!0,classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding},startAdornment:H?(0,K.jsx)(k.Z,{size:20,style:{marginRight:8}}):(0,K.jsx)(pe.Z,{fontSize:"small",style:{marginRight:8,color:"#666"}})},SelectProps:{MenuProps:{getContentAnchorEl:null,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"}},renderValue:e=>{if(!e)return"";const t=W.find((t=>t.formId===e));return t?t.name:""}},value:(null===P||void 0===P?void 0:P.value)||"",disabled:!Q||!V||q||H||Y,onChange:e=>{const t=W.find((t=>t.formId===e.target.value));t&&(this.props.changeState("leadForm",{label:t.name,value:t.formId,...t}),this.props.changeState("leadFormId",t.formId))},placeholder:"Select Lead Form",children:[(0,K.jsx)(de.Z,{value:"",disabled:!0,children:H?"Loading forms...":"Select a Lead Form"}),W.map((e=>(0,K.jsx)(de.Z,{value:e.formId,children:(0,K.jsx)(I.Z,{variant:"body2",children:e.name})},e.formId))),0===W.length&&!H&&(0,K.jsx)(de.Z,{value:"",disabled:!0,children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"No lead forms found. Create one to continue."})}),(0,K.jsx)(E.Z,{}),(0,K.jsx)(de.Z,{onClick:this.handleSyncLeadFormsFromMeta,disabled:this.state.isSyncingLeadForms,children:(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",gap:1,children:[this.state.isSyncingLeadForms?(0,K.jsx)(k.Z,{size:16}):(0,K.jsx)(ue.Z,{fontSize:"small"}),(0,K.jsx)(I.Z,{variant:"body2",children:this.state.isSyncingLeadForms?"Syncing...":"Sync from Meta"})]})})]})})}),(null===P||void 0===P?void 0:P.value)&&(0,K.jsx)(A.Z,{mt:1.5,children:(0,K.jsx)(j.ZP,{title:Q&&V?"":Q?"Missing pages_manage_ads permission. Please reconnect your Meta account":"Please accept Lead Form Terms of Service in the Ads Setup page",placement:"top",children:(0,K.jsx)("span",{children:(0,K.jsx)(w.Z,{variant:"outlined",color:"primary",size:"small",startIcon:(0,K.jsx)(he.Z,{}),onClick:()=>{const e=W.find((e=>e.formId===P.value));e&&this.setState({leadFormDrawerOpen:!0,editingLeadForm:e})},disabled:!Q||!V||q||H,style:{textTransform:"none"},fullWidth:!0,children:"Edit Automation"})})})})]}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]}),(0,K.jsxs)(A.Z,{flex:1,minWidth:"250px",display:"flex",flexDirection:"column",children:[(0,K.jsx)(A.Z,{mb:1,children:(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:1,children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"CTA Button"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Button text shown on your ad"})]}),(0,K.jsx)(A.Z,{style:{width:100}})]})}),u.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{select:!0,variant:"outlined",fullWidth:!0,classes:{root:p.TextFieldRoot},InputProps:{classes:{input:p.inputPadding}},name:"ctaButton",value:T,onChange:e=>this.props.changeState("ctaButton",e.target.value),placeholder:"Select CTA Button",children:$.map((e=>(0,K.jsx)(de.Z,{value:e.value,children:e.label},e.value)))}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]})]})}
2),(0,K.jsxs)(f.Z,{item:!0,style:{marginBottom:"16px"},children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Media"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Upload your media from the media library or generate with AI"}),(0,K.jsxs)("div",{className:p.mediaFormatToggle,children:[(0,K.jsx)("div",{className:p.mediaFormatIndicator,style:{left:this.state.formatIndicatorStyle.left,width:this.state.formatIndicatorStyle.width,opacity:this.state.formatIndicatorStyle.opacity}}),(0,K.jsxs)("button",{ref:this.imageTabRef,className:"".concat(p.mediaFormatButton," ").concat("carousel"!==B&&"VIDEO_UPLOAD"!==F?p.mediaFormatButtonActive:""),onClick:()=>{this.props.changeState("uploadType","IMAGE_UPLOAD"),this.props.changeState("adFormat","single")},children:[(0,K.jsx)(xe,{size:16}),(0,K.jsx)(I.Z,{children:"Image"})]}),(0,K.jsxs)("button",{ref:this.videoTabRef,className:"".concat(p.mediaFormatButton," ").concat("carousel"!==B&&"VIDEO_UPLOAD"===F?p.mediaFormatButtonActive:""),onClick:()=>{this.props.changeState("uploadType","VIDEO_UPLOAD"),this.props.changeState("adFormat","single")},children:[(0,K.jsx)(ve,{size:16}),(0,K.jsx)(I.Z,{children:"Video"})]}),M&&(0,K.jsxs)("button",{ref:this.carouselTabRef,className:"".concat(p.mediaFormatButton," ").concat("carousel"===B?p.mediaFormatButtonActive:""),onClick:()=>{this.props.changeState("adFormat","carousel"),0===N.length&&this.props.changeState("cards",[Pt(),Pt()])},children:[(0,K.jsx)(me.Z,{fontSize:"small"}),(0,K.jsx)(I.Z,{children:"Carousel"})]})]})]}),"carousel"===B?(0,K.jsx)(f.Z,{item:!0,style:{marginBottom:"16px",minWidth:0},children:(0,K.jsx)(Ut,{cards:N,adTypeValue:null===u||void 0===u||null===(o=u.adType)||void 0===o?void 0:o.value,assistantId:null===m||void 0===m?void 0:m.assistantId,assistantDetails:this.props.assistantDetails,updateAssistantAdCredits:this.props.updateAssistantAdCredit,updateAssistantStore:this.props.updateAssistantStore,activePreviewIndex:null!==(r=null===u||void 0===u?void 0:u.previewCardIndex)&&void 0!==r?r:0,onCardsChange:e=>{if(this.props.changeState("cards",e),e.length>N.length)this.props.changeState("previewCardIndex",e.length-1);else if(e.length<N.length){var t;const a=null!==(t=null===u||void 0===u?void 0:u.previewCardIndex)&&void 0!==t?t:0;this.props.changeState("previewCardIndex",Math.min(a,e.length-1))}}})}):(0,K.jsx)(At,{imageFile:S,videoFile:C,thumbnailUrl:Z,onImageFileChange:e=>{this.props.changeState("imageFile",e),e&&this.props.changeState("uploadType","IMAGE_UPLOAD")},onVideoFileChange:e=>{this.props.changeState("videoFile",e),e&&this.props.changeState("uploadType","VIDEO_UPLOAD")},onThumbnailUrlChange:e=>this.props.changeState("thumbnailUrl",e),onMediaSelect:this.onMediaSelect,assistantDetails:this.props.assistantDetails,onImageGeneration:this.onImageGeneration,onVideoGeneration:this.onVideoGeneration,uploadType:this.props.parentState.uploadType,onUploadTypeChange:this.handleUploadTypeToggle,hideTabToggle:!0,fetchAssistantDetails:this.props.fetchAssistantDetails,updateAssistantAdCredits:this.props.updateAssistantAdCredit,updateAssistantStore:this.props.updateAssistantStore,isLoading:!this.props.parentState.isAdFetched&&!this.isCreateAd,onGenerationStateChange:this.handleGenerationStateChange,mediaRecommendation:"whatsapp_status"===(null===u||void 0===u||null===(l=u.adType)||void 0===l?void 0:l.value)?"For WhatsApp Status and Instagram Stories, a vertical 9:16 image or video (recommended 1080\xd71920) works best. This isn't enforced \u2014 other sizes are still accepted.":void 0})]}),(0,K.jsx)(Ta,{open:G,onClose:()=>{this.handleCloseLeadFormDrawer(),this.setState({editingLeadForm:null})},assistantId:null===m||void 0===m?void 0:m.assistantId,assistantDetails:m,pageId:(null===(d=this.props.pageDetails)||void 0===d?void 0:d.pageId)||(null===u||void 0===u||null===(c=u.selectedPage)||void 0===c?void 0:c.pageId),onFormCreated:this.handleLeadFormCreated,onFormSelected:this.handleLeadFormSelected,editMode:!!this.state.editingLeadForm,editForm:this.state.editingLeadForm,onFormUpdated:()=>{this.fetchLeadForms(),this.setState({editingLeadForm:null})}})]})}}const Pa=(0,o.connect)((e=>({aiAdParams:e.assistantDetails.aiAdParams,assistantDetails:e.assistantDetails.data,pageDetails:e.ads.pageDetails})),{createnewAds:fe.iA,FetchNames:fe.PE,FetchDetails:fe.$4,fetchAssistantDetails:be.W9,updateAssistantAdCredit:be.ju,updateAssistantStore:be.sJ,updateAiAdParameters:e=>({type:"UPDATE_AI_AD_PARAMS",payload:e})})(Da),Ba=(0,N.Z)((e=>({root:{width:"100%",padding:"20px 10px",display:"flex"},codeTextFieldRoot:{width:"105px",padding:"0 0 0 24px",position:"absolute",zIndex:1,margin:"8px 0 0 2px",background:"rgb(240,240,240)","& input":{padding:"10px 0 !important"},"& button":{width:"12px",position:"relative",left:"7px",background:"rgb(240,240,240)",borderRadius:0,"&:hover":{background:"rgb(240,240,240)"}},"& div":{paddingRight:"0px !important"}},bottomMargin:{marginBottom:e.spacing(4)},mediaFormatToggle:{position:"relative",backgroundColor:"#f0f0f0",display:"flex",borderRadius:"8px",padding:"4px",width:"fit-content",minWidth:"260px",marginBottom:e.spacing(2)},mediaFormatIndicator:{position:"absolute",top:4,bottom:4,borderRadius:"8px",backgroundColor:"white",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.12)",transition:"left 0.25s cubic-bezier(0.4, 0, 0.2, 1), width 0.25s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.15s ease"},mediaFormatButton:{position:"relative",zIndex:1,flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:e.spacing(.5),padding:e.spacing(.75,1.5),borderRadius:"8px",border:"none",backgroundColor:"transparent",color:e.palette.text.secondary,fontSize:"0.8125rem",fontWeight:600,cursor:"pointer",transition:"color 0.2s ease"},mediaFormatButtonActive:{color:"black"}
2,mutedFieldLabel:{opacity:.5},TextFieldRoot:{width:"100%",padding:"2px",marginTop:"4px","& input":{width:"calc(100% - 80px)"},background:"rgb(240,240,240)"},ad:{display:"flex",justifyContent:"center",marginTop:"1.35em",marginBottom:"2em",[e.breakpoints.up("md")]:{minWidth:"315px"}},textFieldRoot1:{width:"100%",padding:"2px 10px",paddinTop:"4px",paddingLeft:"50px",marginTop:"4px","& input":{width:"calc(100% - 80px)",marginLeft:"80px"},background:"rgb(240,240,240)"},inputPadding:{padding:"12px 10px"},codeTextFieldRoot2:{width:"72px",height:"40px",padding:"0 0 0 22px",position:"absolute",zIndex:1,marginTop:"6px","& input":{padding:"12px 0 !important"}},historySearchBarContainer:{display:"flex",gap:"20px",width:"100%",[e.breakpoints.down("sm")]:{flexDirection:"column",gap:"12px",width:"100%"},borderBottom:"1px solid #E8E8E8",padding:"16px"},historySearchBar:{flex:"1 1 auto",minWidth:0,[e.breakpoints.down("sm")]:{maxWidth:"calc(100% - 32px)"}},dateRangeSelector:{flex:"0 0 auto",border:"2px solid #E8E8E8",borderRadius:"8px",padding:"4px",paddingLeft:"16px",display:"flex",alignItems:"center",justifyContent:"center",gap:8,marginRight:"32px",cursor:"pointer",transition:"border-color 0.2s ease","&:hover":{borderColor:"#0a474c"},[e.breakpoints.down("sm")]:{width:"calc(100% - 36px)",padding:"4px 0px",marginRight:"0px"}},promptContainer:{margin:"16px",borderRadius:"8px",padding:"16px",backgroundColor:"#ffffff","&:hover":{backgroundColor:"rgba(0, 0, 0, 0.02)",cursor:"pointer"},"&:hover $iconButtonContainer":{opacity:1}},promptContent:{flex:1,maxWidth:"30rem"},iconButtonContainer:{opacity:0,[e.breakpoints.down("sm")]:{opacity:1},display:"flex",flexDirection:"column",gap:8,transition:"opacity 0.3s ease, visibility 0.3s ease"},icon:{marginRight:24,"&:hover":{cursor:"pointer"}},dialogTitle:{"& .MuiTypography-h6":{fontSize:20,fontWeight:600,color:"rgb(0,0,0,0.87)"}},textFieldPopper:{[e.breakpoints.down("md")]:{left:"12px !important",minWidth:"calc(100% - 35px)"},[e.breakpoints.up("md")]:{left:"calc(12.5vw - 16px) !important",minWidth:"calc(25vw + 54px)"}},iconButton:{borderRadius:"4px",border:"1px solid #E8E8E8",backgroundColor:"white","&:hover":{backgroundColor:"#0a474c",color:"white"},padding:6},selectedButton:{marginTop:"16px",color:"white",background:"linear-gradient(90deg, #0a474c 0%, #0c5456 46.36%, #0d6161 59.52%,#0e6e6b 100%)"},unselectedButton:{marginTop:"16px",color:"black",backgroundColor:"white",border:"1px solid #E8E8E8","&:hover":{backgroundColor:"#E8E8E8"}},qualityStatus:{"& .MuiChip-label":{color:"white"}},generateButton:{background:"linear-gradient(90deg, #0a474c 0%, #0c5456 46.36%, #0d6161 59.52%,#0e6e6b 100%)",color:"white",borderRadius:"8px",animation:"$gradient 4s ease infinite",position:"relative",overflow:"hidden","&:before":{content:'""',position:"absolute",top:0,left:"-100%",width:"100%",height:"100%",background:"linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent)",animation:"$shine 1.2s linear infinite"},"&:hover":{boxShadow:"0px 2px 6px 0px #3C404326"},"&:disabled":{color:"white"},width:"100%",padding:"8px 16px",height:"40px"},promptHistoryButton:{color:"#0a474c",border:"1px solid #0a474c",borderRadius:"8px",padding:"6px 24px","&:disabled":{color:"#808080",border:"1px solid #808080"}},promptHistoryButtonSmall:{color:"#0a474c",padding:"8px","&:disabled":{color:"#808080"}},textArea:{width:"100%","& .MuiOutlinedInput-root":{backgroundColor:"#f5f5f5",borderRadius:"8px","&:hover":{backgroundColor:"#ebebeb"},"&.Mui-focused":{backgroundColor:"#ffffff"}}},characterCounter:{color:"#808080"},aiLogoContainer:{display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#ebf5f3",borderRadius:"6px",padding:"8px",animation:"$gradient 4s ease infinite",position:"relative",overflow:"hidden","&:before":{content:'""',position:"absolute",top:0,left:"-100%",width:"100%",height:"100%",background:"linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent)",animation:"$shine 1.2s linear infinite"}},shimmerAnimation:{position:"relative",overflow:"hidden","&::before":{content:'""',position:"absolute",top:0,left:"-100%",width:"100%",height:"100%",background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.6) 50%, transparent 100%)",animation:"$shimmer 2s ease-in-out infinite",zIndex:1}},historyDrawerMainContainer:{display:"flex",flexDirection:"column",height:"100%",overflowX:"hidden",
2width:"42rem",[e.breakpoints.down("sm")]:{width:"100%"}},historyImagePreviewContainer:{width:"100%"},historyLoadingContainer:{display:"flex",justifyContent:"center",marginTop:"auto",marginBottom:"auto",width:"100%"},historyContainer:{flex:1,overflowY:"auto",backgroundColor:"#f9f9f9",width:"100%"},assetContainer:{display:"flex",gap:"40px",[e.breakpoints.down("sm")]:{flexDirection:"column"}},assetImageContainer:{display:"flex",flexDirection:"column",width:"200px",height:"200px",border:"1px solid #E8E8E8",borderRadius:"8px",justifyContent:"center",alignItems:"center",cursor:"pointer",position:"relative"},assetImage:{objectFit:"cover",width:"100%",height:"100%",borderRadius:"8px",cursor:"pointer"},deleteButton:{position:"absolute",top:"8px",right:"8px",backgroundColor:"white",border:"1px solid #E8E8E8",borderRadius:"4px",padding:"4px",cursor:"pointer",zIndex:1,"&:hover":{backgroundColor:"#E8E8E8"}},"@global":{"@keyframes gradient":{"0%":{backgroundPosition:"0% 50%"},"50%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0% 50%"}},"@keyframes shimmer":{"0%":{left:"-100%"},"100%":{left:"100%"}},"@keyframes shine":{"0%":{left:"-100%"},"100%":{left:"100%"}}},adDetailMedia:{display:"flex",alignItems:"center",[e.breakpoints.up(1100)]:{display:"flex",flexDirection:"row"},[e.breakpoints.down(1100)]:{flexDirection:"column",gap:"5px"},[e.breakpoints.down(950)]:{display:"flex",flexDirection:"row"},[e.breakpoints.down(700)]:{flexDirection:"column",gap:"5px"}}})))((0,l.withRouter)((Ea=Pa,e=>{const t=(0,re.Z)(),a=(0,le.Z)(t.breakpoints.down("sm"));return(0,K.jsx)(Ea,{...e,theme:t,isSmallScreen:a})})));a(52500);var Ea,Na=a(75933);class La extends r.Component{constructor(e){super(e),this.isDuplicateAd=window.location.pathname.includes("duplicate"),this.isCreateAd=window.location.pathname.includes("create"),this.fetchLeadForms=async()=>{const{assistantDetails:e,pageDetails:t}=this.props,a=null===e||void 0===e?void 0:e.assistantId,s=null===t||void 0===t?void 0:t.pageId;if(console.log("fetchLeadForms called:",{assistantId:a,pageId:s,pageDetails:t}),a&&s){this.setState({isLoadingLeadForms:!0});try{var n,o;const e=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms"),{params:{assistantId:a,pageId:s,status:"ACTIVE",limit:50}});if(console.log("Lead forms API response:",e.data),null!==(n=e.data)&&void 0!==n&&n.status&&null!==(o=e.data)&&void 0!==o&&o.data){const t=e.data.data;this.setState({leadForms:t});const{parentState:a,changeState:i}=this.props,s=null===a||void 0===a?void 0:a.leadFormId,n=null===a||void 0===a?void 0:a.leadForm;if(s&&(null===n||void 0===n||!n.value)){const e=t.find((e=>e.formId===s));e&&(console.log("Auto-selecting lead form from saved leadFormId:",e),i("leadForm",{label:e.name,value:e.formId,...e}))}}}catch(r){console.error("Error fetching lead forms:",r)}finally{this.setState({isLoadingLeadForms:!1})}}else console.log("Missing assistantId or pageId, skipping lead forms fetch")},this.handleOpenLeadFormDrawer=()=>{this.setState({leadFormDrawerOpen:!0})},this.handleCloseLeadFormDrawer=()=>{this.setState({leadFormDrawerOpen:!1})},this.handleLeadFormCreated=e=>{this.fetchLeadForms(),null!==e&&void 0!==e&&e.formId&&(this.props.changeState("leadForm",{label:e.name,value:e.formId,...e}),this.props.changeState("leadFormId",e.formId))},this.handleLeadFormSelected=e=>{this.props.changeState("leadForm",e),this.props.changeState("leadFormId",(null===e||void 0===e?void 0:e.value)||(null===e||void 0===e?void 0:e.formId)||""),this.setState({leadFormDrawerOpen:!1})},this.hasLeadFormPermissions=()=>{const{assistantDetails:e}=this.props,t=(null===e||void 0===e?void 0:e.fbGrantedScopes)||"";return t.includes("pages_manage_ads")&&t.includes("leads_retrieval")},this.toggleMediaDialog=e=>{const{openMediaDialog:t}=this.state,{uploadType:a}=this.props.parentState;"VIDEO_UPLOAD"===a&&"second"===e?this.setState({mediaType:"IMAGE"}):"VIDEO_UPLOAD"===a&&"first"===e?this.setState({mediaType:"VIDEO"}):this.setState({mediaType:"IMAGE"}),this.setState({openMediaDialog:!t})},this.onMediaSelect=e=>{const{uploadType:t}=this.props.parentState,{mediaType:a}=this.state;"VIDEO"==a&&this.props.changeState("videoFile",e),"VIDEO_UPLOAD"===t&&"IMAGE"==a&&this.props.changeState("thumbnailUrl",e),"IMAGE"===a&&"IMAGE_
2UPLOAD"===t&&this.props.changeState("imageFile",e)},this.handleUploadTypeToggle=(e,t)=>{"IMAGE"==t?this.props.changeState("uploadType","IMAGE_UPLOAD"):"VIDEO"==t&&this.props.changeState("uploadType","VIDEO_UPLOAD"),this.props.changeState("imageFile",null),this.props.changeState("videoFile",null),this.props.changeState("thumbnailUrl",null)},this.handleInput=e=>{const{name:t,value:a}=e.target;this.props.changeState(t,a);const i={selectedMedia:{},previewImageUrl:(0,Ae.replaceDomainInData)(e.target.value)};this.props.createnewAds(i)},this.onChangename=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<256&&this.props.changeState(t,a)},this.onChangeCaption=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<=2200&&this.props.changeState(t,a)},this.onChangeHeadline=e=>{const{name:t}=e.target;let a=e.target.value.replace(/^\s+/,"");a.length<256&&this.props.changeState(t,a)},this.state={openMediaDialog:!1,mediaType:"IMAGE",leadFormDrawerOpen:!1,leadForms:[],isLoadingLeadForms:!1}}componentDidMount(){var e,t;"LEAD"===(null===(e=this.props.parentState)||void 0===e||null===(t=e.adType)||void 0===t?void 0:t.type)&&this.fetchLeadForms()}componentDidUpdate(e){var t,a,i,s,n,o;const r="LEAD"===(null===(t=this.props.parentState)||void 0===t||null===(a=t.adType)||void 0===a?void 0:a.type),l="LEAD"===(null===(i=e.parentState)||void 0===i||null===(s=i.adType)||void 0===s?void 0:s.type),d=null===(n=this.props.pageDetails)||void 0===n?void 0:n.pageId,c=null===(o=e.pageDetails)||void 0===o?void 0:o.pageId;r&&!l&&(console.log("Ad type changed to LEAD, fetching lead forms"),this.fetchLeadForms()),r&&d&&d!==c&&(console.log("Page details changed while on LEAD ad type, fetching lead forms"),this.fetchLeadForms())}render(){var e,t,a;const{classes:i,parentState:s,isLiveAD:n,assistantDetails:o}=this.props,{adName:r,adCaption:l,adHeadline:d,imageFile:c,videoFile:p,thumbnailUrl:u,leadForm:h,ctaButton:m="APPLY_NOW"}=s,{openMediaDialog:g,leadForms:x,isLoadingLeadForms:v,leadFormDrawerOpen:y}=this.state,b="LEAD"===(null===s||void 0===s||null===(e=s.adType)||void 0===e?void 0:e.type);return(0,K.jsxs)(f.Z,{container:!0,spacing:this.props.isSmallScreen?2:4,marginTop:"3em",children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,md:12,style:{display:"flex",flexDirection:"column",justifyContent:"center",minWidth:"221px",marginBottom:"20px"},children:[(0,K.jsx)(f.Z,{container:!0,style:{display:"flex",justifyContent:"space-between",gap:"20px"},className:i.bottomMargin,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Ad Name"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((r||"").length,"/255")})]}),(0,K.jsx)(j.ZP,{title:n&&!this.isDuplicateAd?"You can't edit the Ad name once the ad is live":"",placement:"top",children:this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Enter Ad Name ",name:"adName",onChange:this.onChangename,value:r,disabled:n&&!this.isDuplicateAd}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})})]})}),(0,K.jsx)(f.Z,{container:!0,style:{display:"flex",gap:"20px"},className:i.bottomMargin,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Primary Text"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((l||"").length,"/2200")})]}),this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Enter Ad Caption ",name:"adCaption",onChange:this.onChangeCaption,value:l,multiline:!0,rows:4}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:100,style:{borderRadius:"10px"}})]})}),(0,K.jsx)(f.Z,{container:!0,style:{display:"flex",gap:"20px"},className:i.bottomMargin,children:(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"end",children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Headline"}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"".concat((d||"").length,"/255")})]}),this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},placeholder:"Enter Display Headline",name:"adHeadline",onChange:this.onChangeHeadline,value:d,multiline:!0,rows:1}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]})}),b&&(0,K.jsxs)(A.Z,{display:"flex",style:{gap:"20px"},className:i.bottomMargin,flexWrap:"wrap",alignItems:"flex-start",children:[(0,K.jsxs)(A.Z,{flex:2,minWidth:"300px",display:"flex",flexDirection:"column",children:[(0,K.jsx)(A.Z,{mb:1,children:(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:1,children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Lead Form"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Select or create a lead form to collect user information"})]}),(0,K.jsx)(j.ZP,{title:this.hasLeadFormPermissions()?"":"Missing permissions: pages_manage_ads and leads_retrieval. Please reconnect your Meta account.",placement:"top",children:(0,K.jsx)("span",{children:(0,K.jsx)(w.Z,{variant:"outlined",color:"primary",size:"small",startIcon:(0,K.jsx)(ce.Z,{}),onClick:this.handleOpenLeadFormDrawer,style:{textTransform:"none",marginTop:4},disabled:!this.hasLeadFormPermissions(),children:"Create New"})})})]})}),s.isAdFetched||this.isCreateAd?(0,K.jsx)(j.ZP,{title:this.hasLeadFormPermissions()?n&&!this.isDuplicateAd?"You can't edit the Lead Form once the ad is live":"":"Missing permissions: pages_manage_ads and leads_retrieval. Please reconnect your Meta account.",placement:"top",children:(0,K.jsx)("div",{children:(0,K.jsxs)(L.Z,{select:!0,variant:"outlined",fullWidth:!0,classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding},startAdornment:v?(0,K.jsx)(k.Z,{size:20,style:{marginRight:8}}):(0,K.jsx)(pe.Z,{fontSize:"small",style:{marginRight:8,color:"#666"}})},value:(null===h||void 0===h?void 0:h.value)||"",disabled:n&&!this.isDuplicateAd||!this.hasLeadFormPermissions(),onChange:e=>{const t=x.find((t=>t.formId===e.target.value));t&&this.props.changeState("leadForm",{label:t.name,value:t.formId,...t})},placeholder:"Select Lead Form",children:[(0,K.jsx)(de.Z,{value:"",disabled:!0,children:v?"Loading forms...":"Select a Lead Form"}),x.map((e=>(0,K.jsx)(de.Z,{value:e.formId,children:(0,K.jsx)(I.Z,{variant:"body2",children:e.name})},e.formId))),0===x.length&&!v&&(0,K.jsx)(de.Z,{value:"",disabled:!0,children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"No lead forms found. Create one to continue."})})]})})}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]}),(0,K.jsxs)(A.Z,{flex:1,minWidth:"250px",display:"flex",flexDirection:"column",children:[(0,K.jsx)(A.Z,{mb:1,children:(0,K.jsxs)(A.Z,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:1,children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"CTA Button"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Button text shown on your ad"})]}),(0,K.jsx)(A.Z,{style:{width:100}})]})}),s.isAdFetched||this.isCreateAd?(0,K.jsx)(j.ZP,{title:n&&!this.isDuplicateAd?"You can't edit the CTA Button once the ad is live":"",placement:"top",children:(0,K.jsx)("div",{children:(0,K.jsx)(L.Z,{select:!0,variant:"outlined",fullWidth:!0,classes:{root:i.TextFieldRoot},InputProps:{classes:{input:i.inputPadding}},name:"ctaButton",value:m,disabled:n&&!this.isDuplicateAd,onChange:e=>this.props.changeState("ctaButton",e.target.value),placeholder:"Select CTA Button",children:Xt.$7.map((e=>(0,K.jsx)(de.Z,{value:e.value,children:e.label},e.value)))})})}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]})]}),(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Media"}),(0,K.jsx)(A.Z,{position:"relative",md:6,children:this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(q.ZP,{disableClearable:!0,options:["IMAGE","VIDEO"],onChange:(e,t)=>
2{this.handleUploadTypeToggle(e,t)},value:(null===(t=[{value:"IMAGE_UPLOAD",label:"IMAGE"},{value:"VIDEO_UPLOAD",label:"VIDEO"}].find((e=>e.value===this.props.parentState.uploadType)))||void 0===t?void 0:t.label)||"",name:"format",renderInput:e=>(0,K.jsx)(L.Z,{...e,placeholder:"Type",variant:"outlined",classes:{root:i.codeTextFieldRoot},InputProps:{...e.InputProps}})}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})}),(0,K.jsxs)("div",{className:i.adDetailMedia,style:{marginBottom:"10px",gap:"10px"},children:["IMAGE_UPLOAD"===this.props.parentState.uploadType?(0,K.jsx)(K.Fragment,{children:this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.textFieldRoot1},placeholder:"Media url",name:"url",value:(0,Ae.replaceDomainInData)((null===c||void 0===c?void 0:c.publicUrl)||""),onChange:e=>{this.props.changeState("imageFile",e.target.value?{publicUrl:e.target.value,fileName:"Image"}:null)}}):(0,K.jsx)(K.Fragment,{})}):(0,K.jsx)(K.Fragment,{children:this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.textFieldRoot1},placeholder:"Media url",name:"url",value:(0,Ae.replaceDomainInData)((null===p||void 0===p?void 0:p.publicUrl)||""),onChange:e=>{this.props.changeState("videoFile",e.target.value?{publicUrl:e.target.value,fileName:"Video"}:null)}}):(0,K.jsx)(K.Fragment,{})}),(0,K.jsx)(A.Z,{style:{display:"flex",alignItems:"center",paddingLeft:"5px",paddingRight:"5px"},children:(this.props.parentState.isAdFetched||this.isCreateAd)&&(0,K.jsx)(I.Z,{color:"textSecondary",variant:"body1",children:"OR"})}),(0,K.jsx)(K.Fragment,{children:this.props.parentState.isAdFetched||this.isCreateAd?(0,K.jsx)(w.Z,{color:"primary",variant:"contained",fullWidth:!0,startIcon:(0,K.jsx)(Na.Z,{}),onClick:()=>this.toggleMediaDialog("first"),style:{paddingTop:"10px",paddingBottom:"10px"},children:"Upload from Media Library"}):(0,K.jsx)(K.Fragment,{})})]}),"VIDEO_UPLOAD"===this.props.parentState.uploadType&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(A.Z,{position:"relative",children:(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.codeTextFieldRoot},value:"THUMBNAIL"})}),(0,K.jsxs)("div",{className:i.adDetailMedia,style:{width:"100%",gap:"10px"},children:[(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(L.Z,{variant:"outlined",classes:{root:i.textFieldRoot1},placeholder:"Image url",name:"thumbnailUrl",value:(0,Ae.replaceDomainInData)((null===u||void 0===u?void 0:u.publicUrl)||("string"===typeof u?u:"")),onChange:e=>{this.props.changeState("thumbnailUrl",e.target.value?{publicUrl:(0,Ae.replaceDomainInData)(e.target.value),fileName:"Image"}:null)}})}),(0,K.jsx)(A.Z,{style:{display:"flex",alignItems:"center",paddingLeft:"5px",paddingRight:"5px"},children:(0,K.jsx)(I.Z,{color:"textSecondary",variant:"body1",children:"OR"})}),(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(w.Z,{color:"primary",variant:"contained",fullWidth:!0,startIcon:(0,K.jsx)(Na.Z,{}),onClick:()=>this.toggleMediaDialog("second"),style:{paddingTop:"10px",paddingBottom:"10px"},children:"Upload from Media Library"})})]})]})]})]}),(0,K.jsx)(We.default,{openMediaDialog:g,toggleMediaDialog:this.toggleMediaDialog,onMediaSelect:this.onMediaSelect,mediaType:this.state.mediaType,isFromMetaAds:!0}),(0,K.jsx)(Ta,{open:y,onClose:this.handleCloseLeadFormDrawer,assistantId:null===o||void 0===o?void 0:o.assistantId,assistantDetails:o,pageId:null===(a=this.props.pageDetails)||void 0===a?void 0:a.pageId,onFormCreated:this.handleLeadFormCreated,onFormSelected:this.handleLeadFormSelected})]})}}const Fa=(0,o.connect)((e=>({assistantDetails:e.assistantDetails.data,pageDetails:e.ads.pageDetails})),{createnewAds:fe.iA,FetchNames:fe.PE,FetchDetails:fe.$4})(La);(0,N.Z)((e=>({root:{width:"100%",padding:"20px 10px",display:"flex"},codeTextFieldRoot:{width:"105px",padding:"0 0 0 24px",position:"absolute",zIndex:1,margin:"8px 0 0 2px",background:"rgb(240,240,240)","& input":{padding:"10px 0 !important"},"& button":{width:"12px",position:"relative",left:"7px",background:"rgb(240,240,240)",borderRadius:0,"&:hover":{background:"rgb(240,240,240)"}},"& div":{paddingRight:"0px !important"}},bottomMargin:{marginBottom:e.spacing(4)},TextFieldRoot:{width:"100%",padding:"2px",marginTop:"4px","& input":{width:"calc(100% - 80px)"},background:"rgb(240,240,240)"},ad:{display:"flex",justifyContent:"center",marginTop:"1.35em",marginBottom:"2em",[e.breakpoints.up("md")]:{minWidth:"315px"}},textFieldRoot1:{width:"100%",padding:"2px 10px",paddinTop:"4px",paddingLeft:"50px",marginTop:"4px","& input":{width:"calc(100% - 80px)",marginLeft:"80px"},background:"rgb(240,240,240)"},inputPadding:{padding:"12px 10px"},codeTextFieldRoot2:{width:"72px",height:"40px",padding:"0 0 0 22px",position:"absolute",zIndex:1,marginTop:"6px","& input":{padding:"12px 0 !important"}},adDetailMedia:{display:"flex",alignItems:"center",[e.breakpoints.up(1100)]:{display:"flex",flexDirection:"row"},[e.breakpoints.down(1100)]:{flexDirection:"column",gap:"5px"},[e.breakpoints.down(950)]:{display:"flex",flexDirection:"row"},[e.breakpoints.down(700)]:{flexDirection:"column",gap:"5px"}}})))((0,l.withRouter)((e=>t=>{const a=(0,re.Z)(),i=(0,le.Z)(a.breakpoints.down("sm"));return(0,K.jsx)(e,{...t,theme:a,isSmallScreen:i})})(Fa)));var Ma=a(47893),Ra=a(35139),Oa=a(41790),Ua=a(10632),za=a(91506);class _a extends r.Component{constructor(e){super(e),this.debounce=(e,t)=>{let a;return function(){for(var i=arguments.length,s=new Array(i),n=0;n<i;n++)s[n]=arguments[n];clearTimeout(a),a=setTimeout((()=>e(...s)),t)}},this.checkWhatsappNumberLinked=async e=>{try{var t;const a=await i.Z.post("".concat(W.URL,"/meta-ads/fetch-meta-ad-setup"),{assistantId:e}),s=null===a||void 0===a||null===(t=a.data)||void 0===t?void 0:t.whatsappNumberLinked;"boolean"===typeof s&&this.setState({whatsappNumberLinked:s})}catch(a){console.log("AdType: whatsappNumberLinked check failed",null===a||void 0===a?void 0:a.message)}},this.checkLeadFormPermissions=async()=>{var e,t,a;const s=this.props.assistantId||(null===(e=this.props.match)||void 0===e||null===(t=e.params)||void 0===t?void 0:t.projectId),n=null===(a=this.props.parentState)||void 0===a?void 0:a.selectedMetaPageId;if(s&&n){this.setState({checkingPermissions:!0});try{var o;const e=await i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/lead-forms/permissions/check"),{params:{assistantId:s,pageId:n}});if(console.log("AdType: Permission check response:",e.data),null!==(o=e.data)&&void 0!==o&&o.status){const t=!0===e.data.hasLeadFormPermissions,a=!0===e.data.leadFormTosAccepted;console.log("AdType: Setting permissions state:",{hasPermissions:t,tosAccepted:a,rawHasPermissions:e.data.hasLeadFormPermissions,rawTosAccepted:e.data.leadFormTosAccepted}),this.setState({hasLeadFormPermissions:t,leadFormTosAccepted:a,checkingPermissions:!1},(()=>{console.log("AdType: State updated:",{hasLeadFormPermissions:this.state.hasLeadFormPermissions,leadFormTosAccepted:this.state.leadFormTosAccepted})}
2))}else console.log("AdType: API returned status false, setting permissions to false"),this.setState({hasLeadFormPermissions:!1,leadFormTosAccepted:!1,checkingPermissions:!1})}catch(l){var r;console.error("AdType: Error checking lead form permissions:",l),console.error("AdType: Error response:",null===l||void 0===l||null===(r=l.response)||void 0===r?void 0:r.data),this.setState({hasLeadFormPermissions:!1,leadFormTosAccepted:!1,checkingPermissions:!1})}}else console.log("AdType: Missing assistantId or pageId, skipping permission check",{assistantId:s,pageId:n})},this.handleCreatePixel=()=>{this.setState({createPixelDialogOpen:!0})},this.handleCloseCreatePixelDialog=()=>{this.setState({createPixelDialogOpen:!1,pixelName:"",pixelDescription:"",pixelNameError:""})},this.handlePixelNameChange=e=>{const t=e.target.value;t.length<=100&&this.setState({pixelName:t,pixelNameError:""===t.trim()?"Pixel name is required":""})},this.handlePixelDescriptionChange=e=>{const t=e.target.value;t.length<=1024&&this.setState({pixelDescription:t})},this.handleCreatePixelSubmit=async()=>{var e;const{assistantId:t,match:a}=this.props,{pixelName:s,pixelDescription:n}=this.state,o=t||(null===a||void 0===a||null===(e=a.params)||void 0===e?void 0:e.projectId);if(s&&""!==s.trim())if(o){this.setState({creatingPixel:!0});try{var r;const e=await i.Z.post("".concat(W.ADS_REST_API_URL,"/meta/pixels/create"),{assistantId:o,pixelName:s.trim(),pixelDescription:n.trim()||""});this.setState({creatingPixel:!1,createPixelDialogOpen:!1,pixelName:"",pixelDescription:"",pixelNameError:"",snackbar:{open:!0,message:(null===(r=e.data)||void 0===r?void 0:r.message)||"Pixel created successfully!",severity:"success"}}),o&&setTimeout((()=>{this.props.fetchPixels({assistantId:o})}),500)}catch(c){var l,d;const e=(null===c||void 0===c||null===(l=c.response)||void 0===l||null===(d=l.data)||void 0===d?void 0:d.message)||(null===c||void 0===c?void 0:c.message)||"Failed to create pixel. Please try again.";this.setState({creatingPixel:!1,snackbar:{open:!0,message:e,severity:"error"}})}}else this.setState({snackbar:{open:!0,message:"Assistant ID is missing. Please try again.",severity:"error"}});else this.setState({pixelNameError:"Pixel name is required"})},this.handleSnackbarClose=(e,t)=>{"clickaway"!==t&&this.setState({snackbar:{open:!1,message:"",severity:"success"}})},this.isAdTypeOptionDisabled=e=>{if("ctwa"===e.value||"website_to_whatsapp"===e.value)return!1===this.state.whatsappNumberLinked;if("lead_form"!==e.value)return!1;const{hasLeadFormPermissions:t,leadFormTosAccepted:a}=this.state;return null!==t&&!this.state.checkingPermissions&&(!1===t||!1===a)},this.getAdTypeOptionTooltip=e=>{if("ctwa"===e.value||"website_to_whatsapp"===e.value)return!1===this.state.whatsappNumberLinked?"Verify your WhatsApp number in Setup (Link Whatsapp Number) to run WhatsApp Ads":null;if("lead_form"!==e.value)return null;const{hasLeadFormPermissions:t,leadFormTosAccepted:a}=this.state;return null===t||this.state.checkingPermissions?null:!1===t?"Please reconnect your Meta account with the 'pages_manage_ads' permission to run Lead Form Ads":!1===a?"Accept the Lead Form Terms of Service in Setup to run Lead Form Ads":null},this.handleAdTypeSelect=e=>{const{changeState:t}=this.props;t("adType",e),t("pixel",""),t("conversionEvent",""),t("leadForm","");const{objective:a,goal:i}=(0,Xt.Ge)(null===e||void 0===e?void 0:e.type);t("adObjective",a||""),t("optimizationGoal",i||"")},this.state={createPixelDialogOpen:!1,pixelName:"",pixelDescription:"",pixelNameError:"",pixelOptions:[],pixelsLoading:!1,pixelSearchQuery:"",creatingPixel:!1,snackbar:{open:!1,message:"",severity:"success"},code:"",hasLeadFormPermissions:null,leadFormTosAccepted:!1,checkingPermissions:!1,whatsappNumberLinked:null},this.debouncedSearchPixels=this.debounce(this.searchPixels,500)}componentDidMount(){var e,t;const a=this.props.assistantId||(null===(e=this.props.match)||void 0===e||null===(t=e.params)||void 0===t?void 0:t.projectId);a&&(this.props.fetchPixels({assistantId:a}),this.checkLeadFormPermissions(),this.checkWhatsappNumberLinked(a))}componentDidUpdate(e){var t,a,i,s,n,o,r,l,d;const c=e.assistantId||(null===(t=e.match)||void 0===t||null===(a=t.params)||void 0===a?void 0:a.projectId),p=this.props.assistantId||(null===(i=this.props.match)||void 0===i||null===(s=i.params)||void 0===s?void 0:s.projectId),u=null===(n=e.parentState)||void 0===n?void 0:n.selectedMetaPageId,h=null===(o=this.props.parentState)||void 0===o?void 0:o.selectedMetaPageId;(c!==p||u!==h)&&p&&h&&this.checkLeadFormPermissions();null===(r=e.parentState)||void 0===r||r.adType;const m=null===(l=this.props.parentState)||void 0===l?void 0:l.adType,g=null===(d=this.props.parentState)||void 0===d?void 0:d.adObjective;if("LEAD"===(null===m||void 0===m?void 0:m.type)&&(!g||"OUTCOME_LEADS"!==g.value)){const e=Xt.eO.find((e=>"OUTCOME_LEADS"===e.value));e&&this.props.changeState("adObjective",e)}}render(){var e,t;const{classes:a,parentState:i,isAdFetched:s,isCreateAd:n,changeState:o,isLiveAD:r}=this.props,{adType:l,optimizationGoal:d,adObjective:p,pixel:u,conversionEvent:h}=i||{};let m=p;if("LEAD"===(null===l||void 0===l?void 0:l.type)){const e=Xt.eO.find((e=>"OUTCOME_LEADS"===e.value));e&&(m=e)}const g=Xt.T$;return(0,K.jsxs)(f.Z,{container:!0,spacing:3,children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,children:[(0,K.jsxs)(A.Z,{style:{marginBottom:"16
2px"},children:[(0,K.jsx)(A.Z,{style:{display:"flex",alignItems:"flex-start",gap:"14px",marginBottom:"16px"}}),s||n?(0,K.jsx)(f.Z,{container:!0,spacing:2,children:g.map((e=>{const t=(null===l||void 0===l?void 0:l.value)===e.value,i=r||this.isAdTypeOptionDisabled(e),s=r?null:this.getAdTypeOptionTooltip(e),n=(0,K.jsxs)(A.Z,{onClick:()=>{i||t||this.handleAdTypeSelect(e)},className:"".concat(a.adTypeCard," ").concat(t?a.adTypeCardSelected:""," ").concat(i?a.adTypeCardDisabled:""),children:[Oa.Z[e.value]||null,(0,K.jsxs)(A.Z,{className:a.adTypeCardBody,children:[(0,K.jsx)(A.Z,{className:a.adTypeCardTitleRow,children:(0,K.jsx)(I.Z,{variant:"h6",className:a.adTypeCardTitle,children:e.label})}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",className:a.adTypeCardDescription,children:e.description})]}),t?(0,K.jsx)(c.Z,{className:"".concat(a.adTypeRadio," ").concat(a.adTypeRadioSelected)}):(0,K.jsx)(Ma.Z,{className:a.adTypeRadio})]});return(0,K.jsx)(f.Z,{item:!0,xs:12,sm:6,children:s?(0,K.jsx)(j.ZP,{title:s,placement:"top",arrow:!0,children:(0,K.jsx)("span",{style:{display:"block",height:"100%"},children:n})}):n},e.value)}))}):(0,K.jsx)(f.Z,{container:!0,spacing:2,children:g.map((e=>(0,K.jsx)(f.Z,{item:!0,xs:12,sm:6,children:(0,K.jsx)(oe.Z,{variant:"rectangular",height:112,style:{borderRadius:"12px"}})},e.value)))})]}),(0,K.jsxs)(A.Z,{style:{display:"flex",gap:"20px",width:"100%"},children:[(0,K.jsx)(A.Z,{style:{width:"50%"},children:(0,K.jsx)(Ua.Z,{isFetching:!(s||n),options:Xt.eO.filter((e=>"OUTCOME_LEADS"===e.value?"LEAD"===(null===l||void 0===l?void 0:l.type):"LEAD"!==(null===l||void 0===l?void 0:l.type)||"OUTCOME_LEADS"===e.value)),value:m,onChange:async(e,t)=>{o("adObjective",t),o("optimizationGoal",""),o("pixel",""),o("conversionEvent",""),o("leadForm","")},placeholder:"Select Ad Objective",classes:a,label:"Ad Objective",marginBottom:"16px",isDisabled:r||"LEAD"===(null===l||void 0===l?void 0:l.type)})}),(0,K.jsx)(A.Z,{style:{width:"50%"},children:(0,K.jsx)(Ua.Z,{isFetching:!(s||n),options:(null===(e=Xt.eO.find((e=>{var t;return(null===e||void 0===e?void 0:e.value)==(null===(t=m)||void 0===t?void 0:t.value)})))||void 0===e||null===(t=e.optimizationGoals)||void 0===t?void 0:t.filter((e=>{var t;return"GOALS"==e.value||(null===(t=e.conversionLocations)||void 0===t?void 0:t.includes(null===l||void 0===l?void 0:l.type))})))||[],showDescription:!0,showHeader:!0,value:d,onChange:async(e,t)=>{o("optimizationGoal",t),o("conversionEvent",""),o("pixel","")},isDisabled:!(null!==p&&void 0!==p&&p.value)||!(null!==l&&void 0!==l&&l.value)||r,placeholder:"Select data source",classes:a,label:"Performance Goal",marginBottom:"16px"})})]}),("OFFSITE_CONVERSIONS"===(null===d||void 0===d?void 0:d.value)||"VALUE"===(null===d||void 0===d?void 0:d.value))&&(0,K.jsx)(f.Z,{item:!0,xs:12,children:(()=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",style:{marginBottom:"8px"}}),s||n?(0,K.jsx)("div",{children:(0,K.jsx)(Ua.Z,{isFetching:!(s||n),options:this.props.pixels.filter((e=>"ACTIVE"===e.status)).map((e=>({label:"".concat(e.name," (").concat(e.pixelId,")"),value:e.pixelId}))),value:u,onChange:async(e,t)=>{if(o("pixel",t),null!==t&&void 0!==t&&t.value&&this.props.assistantId)try{await this.props.fetchPixelDetails({assistantId:this.props.assistantId,pixelId:t.value})}catch(a){console.error("Error fetching pixel details:",a)}},placeholder:"Select Pixel",classes:a,label:"Pixel ".concat("OFFSITE_CONVERSIONS"==(null===d||void 0===d?void 0:d.value)||"VALUE"==(null===d||void 0===d?void 0:d.value)?"":"(Optional)"),description:"Attach a Facebook Pixel ID to track conversions and optimize your ad performance",marginBottom:"16px",button:(0,K.jsx)(w.Z,{size:"small",variant:"outlined",color:"primary",onClick:()=>this.handleCreatePixel(),startIcon:(0,K.jsx)(Ra.Z,{size:16}),style:{textTransform:"none",fontSize:"13px",padding:"6px 12px"},children:"Create New Pixel"}),isDisabled:!(null!==p&&void 0!==p&&p.value)||!(null!==l&&void 0!==l&&l.value)||!(null!==d&&void 0!==d&&d.value)||r})}):(0,K.jsx)(oe.Z,{variant:"rectangular",height:40,style:{borderRadius:"10px"}})]}))()}),(null===u||void 0===u?void 0:u.value)&&("OFFSITE_CONVERSIONS"===(null===d||void 0===d?void 0:d.value)||"VALUE"===(null===d||void 0===d?void 0:d.value))&&(0,K.jsx)(f.Z,{item:!0,xs:12,style:{marginTop:"20px"},children:(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(Ua.Z,{isFetching:!(s||n),options:Xt.kg.filter((e=>e.supportedTypes.includes(null===p||void 0===p?void 0:p.value)&&!("VALUE"==(null===d||void 0===d?void 0:d.value)&&"PURCHASE"==e.value))),value:h,onChange:(e,t)=>
2{o("conversionEvent",t)},placeholder:"Select Conversion Event",classes:a,showDescription:!0,showEventType:!0,label:"Conversion Event",marginBottom:"16px",isDisabled:r})})})]}),(0,K.jsxs)(Z.Z,{open:this.state.createPixelDialogOpen,onClose:(e,t)=>{"backdropClick"!==t&&this.handleCloseCreatePixelDialog()},maxWidth:"sm",fullWidth:!0,className:a.createPixelDialog,children:[(0,K.jsxs)(T.Z,{className:a.dialogTitle,children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",children:[(0,K.jsx)(A.Z,{display:"flex",alignItems:"center",gap:5,children:(0,K.jsx)(I.Z,{variant:"h5",className:a.dialogTitleText,children:"Create Pixel"})}),(0,K.jsx)(b.Z,{onClick:this.handleCloseCreatePixelDialog,className:a.closeButton,size:"small",children:(0,K.jsx)(ct.Z,{})})]}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",className:a.dialogSubtitle,children:"Set up a new Meta Pixel to track conversions and optimize your ad performance"})]}),(0,K.jsx)(D.Z,{className:a.dialogContent,children:(0,K.jsxs)(A.Z,{className:a.contentCard,children:[(0,K.jsxs)(A.Z,{mb:2,children:[(0,K.jsx)(I.Z,{variant:"body2",className:a.inputLabel,children:"Pixel Name"}),(0,K.jsx)(_t.Z,{className:a.inputCard,elevation:0,children:(0,K.jsx)(L.Z,{variant:"outlined",fullWidth:!0,placeholder:"Enter pixel name",value:this.state.pixelName,onChange:this.handlePixelNameChange,error:!!this.state.pixelNameError,helperText:this.state.pixelNameError,classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding},endAdornment:(0,K.jsx)(Ce.Z,{position:"end",children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",className:a.charCount,children:"".concat((this.state.pixelName||"").length,"/100")})})},FormHelperTextProps:{style:{marginTop:"4px",fontSize:"12px"}}})})]}),(0,K.jsxs)(A.Z,{mb:2,children:[(0,K.jsx)(A.Z,{display:"flex",alignItems:"center",gap:1,style:{marginBottom:"8px"},children:(0,K.jsx)(I.Z,{variant:"body2",className:a.inputLabel,children:"Description"})}),(0,K.jsx)(_t.Z,{className:a.inputCard,elevation:0,children:(0,K.jsxs)(A.Z,{position:"relative",children:[(0,K.jsx)(L.Z,{variant:"outlined",fullWidth:!0,multiline:!0,rows:4,placeholder:"Describe this pixel for future reference",value:this.state.pixelDescription,onChange:this.handlePixelDescriptionChange,classes:{root:a.TextFieldRoot},InputProps:{classes:{input:a.inputPadding}}}),(0,K.jsx)(A.Z,{position:"absolute",bottom:"12px",right:"14px",style:{pointerEvents:"none"},children:(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",className:a.charCount,children:"".concat((this.state.pixelDescription||"").length,"/1024")})})]})})]})]})}),(0,K.jsxs)(B.Z,{className:a.dialogActions,children:[(0,K.jsx)(w.Z,{onClick:this.handleCloseCreatePixelDialog,variant:"outlined",className:a.cancelButton,children:"Cancel"}),(0,K.jsx)(w.Z,{onClick:this.handleCreatePixelSubmit,variant:"contained",color:"primary",disabled:!this.state.pixelName||""===this.state.pixelName.trim()||!!this.state.pixelNameError||this.state.creatingPixel,startIcon:this.state.creatingPixel?(0,K.jsx)(k.Z,{size:16,color:"inherit"}):null,children:this.state.creatingPixel?"Creating...":"Create Pixel"})]})]}),(0,K.jsx)(ht.A9,{open:this.state.snackbar.open,onClose:this.handleSnackbarClose,anchorOrigin:{vertical:"top",horizontal:"center"},severity:this.state.snackbar.severity,message:this.state.snackbar.message})]})}}const Wa=(0,o.connect)((e=>{var t,a,i,s;return{assistantDetails:e.assistantDetails.data,assistantId:(null===(t=e.login)||void 0===t||null===(a=t.user)||void 0===a?void 0:a.assistantId)||(null===(i=e.assistantDetails)||void 0===i||null===(s=i.data)||void 0===s?void 0:s.assistantId),pixels:e.audience.pixels,pixelsLoading:e.audience.pixelsLoading,pixelsError:e.audience.pixelsError,pixelsPagination:e.audience.pixelsPagination,pixelEvents:e.audience.pixelEvents,pixelEventsCustomFields:e.audience.pixelEventsCustomFields}}),{fetchPixels:za.tb,fetchPixelDetails:za.MO})(_a),Ha=(0,N.Z)((e=>({adTypeCard:{display:"flex",alignItems:"flex-start",gap:"14px",borderRadius:"12px",padding:"16px",height:"100%",boxSizing:"border-box",border:"0.5px solid #e0e0e0",background:"transparent",curs
2or:"pointer",transition:"all 0.2s"},adTypeCardSelected:{border:"0.5px solid ".concat(e.palette.primary.main),boxShadow:"0 0 0 1px ".concat(e.palette.primary.main),background:"linear-gradient(90deg, rgba(37, 211, 102, 0.07) 0%, rgba(255, 255, 255, 0) 60%)"},adTypeCardDisabled:{cursor:"not-allowed",opacity:.5},adTypeCardBody:{minWidth:0,flex:1},adTypeCardTitleRow:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},adTypeCardTitle:{fontWeight:700,fontSize:"15px",lineHeight:1.3},adTypeCardDescription:{fontSize:"13px",marginTop:"2px"},adTypeTag:{fontSize:"10px",fontWeight:700,letterSpacing:"0.4px",padding:"2px 8px",borderRadius:"10px"},adTypeTagRecommended:{backgroundColor:"rgba(37, 211, 102, 0.15)",color:"#0a7c43"},adTypeTagBeta:{backgroundColor:"rgba(124, 58, 237, 0.12)",color:"#7C3AED"},adTypeRadio:{fontSize:"22px",flexShrink:0,color:"#cfcfcf"},adTypeRadioSelected:{color:e.palette.primary.main},textFieldRoot1:{width:"100%",padding:"2px 10px",paddinTop:"4px",paddingLeft:"50px",marginTop:"4px","& input":{width:"calc(100% - 80px)",marginLeft:"80px"},background:"rgb(240,240,240)"},inputRoot:{'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-input':{padding:12},'&&[class*="MuiOutlinedInput-root"]':{padding:0},'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-inputRoot':{paddingRight:"0 !important",paddingLeft:"0 !important"}},selectRoot:{backgroundColor:"rgb(240,240,240)",borderRadius:"8px","& .MuiSelect-select":{overflow:"hidden",textOverflow:"ellipsis"}},inputPadding:{padding:"12px 10px"},adTypeInputPadding:{padding:"0px 0px"},createPixelDialog:{"& .MuiDialog-paper":{borderRadius:"12px",overflow:"hidden"}},textFieldRoot:{backgroundColor:"rgb(240,240,240)",outline:"none",border:"none",borderRadius:"8px",width:"100%",padding:"0",boxShadow:"none",boxSizing:"border-box",fontFamily:"Roboto, sans-serif",fontSize:"15px",fontWeight:500,maxHeight:"12em",overflow:"auto","&::-webkit-scrollbar":{width:"4px"}},dialogTitle:{padding:e.spacing(3,3,2),backgroundColor:"#F5F5F5",borderBottom:"none",[e.breakpoints.down("sm")]:{padding:e.spacing(2.5,2.5,1.5)},[e.breakpoints.down("xs")]:{padding:e.spacing(2,2,1.5)}},dialogTitleText:{fontWeight:600,fontSize:"1.25rem",lineHeight:1.5},dialogSubtitle:{marginTop:e.spacing(1),fontSize:"0.875rem",lineHeight:1.5},closeButton:{padding:e.spacing(.5),marginLeft:"auto"},dialogContent:{backgroundColor:"#F5F5F5"},contentCard:{backgroundColor:"white",padding:e.spacing(2.5),borderRadius:"8px",[e.breakpoints.down("sm")]:{padding:e.spacing(2)},[e.breakpoints.down("xs")]:{padding:e.spacing(1.5)}},inputLabel:{marginBottom:e.spacing(1),fontWeight:500,fontSize:"0.875rem",[e.breakpoints.down("xs")]:{fontSize:"0.8125rem",marginBottom:e.spacing(.75)}},inputCard:{backgroundColor:"transparent",padding:0,borderRadius:"8px",border:"none",boxShadow:"none","& .MuiOutlinedInput-root":{backgroundColor:"#F9F9FB","& fieldset":{border:"none"},"&:hover fieldset":{border:"none"},"&.Mui-focused fieldset":{border:"none"}},"& .MuiInputBase-root":{backgroundColor:"#F9F9FB"}},charCount:{fontSize:"12px",marginRight:"10px"},TextFieldRoot:{width:"100%",marginTop:"4px",background:"#F9F9FB"},dialogActions:{padding:e.spacing(2,3),justifyContent:"flex-end",gap:e.spacing(1),backgroundColor:"#F5F5F5",borderTop:"none",[e.breakpoints.down("sm")]:{padding:e.spacing(1.5,2.5)},[e.breakpoints.down("xs")]:{padding:e.spacing(1.5,2),flexDirection:"column-reverse","& button":{width:"100%"}}},cancelButton:{textTransform:"none",borderRadius:"8px"}})))((0,l.withRouter)(Wa));var Ga=a(72014),Va=a(67367),Qa=a(12834);const qa=a.p+"static/media/instagram.e719d8b29f452a16302d.png";var Ya=a(62206);const Ka=(0,N.Z)((e=>({platformCard:{borderRadius:"8px",padding:"16px",cursor:"pointer",transition:"background-color 0.2s",display:"flex",flexDirection:"column"},platformCardHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"},positionChip:{display:"flex",alignItems:"center",justifyContent:"center",padding:"5px 14px",borderRadius:"20px",border:"1px solid #a19a9a",cursor:"pointer",transition:"all 0.2s",minHeight:"20px",width:"fit-content","&:hover":{border:"1px solid #a19a9a"}},positionChipSelected:{backgroundColor:e.palette.primary.main,borderRadius:"20px",color:"white","&:hover":{backgroundColor:e.palette.primary.dark},"& .MuiTypography-root":{color:"white"}}})))((e=>{let{platform:t,platformIcon:a,platformTitle:i,selectedPositions:s=[],isAiSensy:n,isPlatformSelected:o=!1,onPlatformToggle:r,onPositionToggle:l,classes:d}=e;const c="facebook"===t?Xt.JR:Xt.oJ,p=s.length===c.length;return(0,K.jsxs)(A.Z,{className:d.platformCard,children:[(0,K.jsxs)(A.Z,{className:d.platformCardHeader,style:{cursor:"pointer"},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:"12px"},onClick:e=>{e.stopPropagation(),r(t,o)},children:[(0,K.jsx)(F.Z,{checked:o,onChange:e=>{e.stopPropagation(),r(t,o)},onClick:e=>{e.stopPropagation()},color:"primary",style:{padding:"4px"}}),(0,K.jsx)("img",{src:a,alt:"".concat(i," icon"),style:{width:"24px",height:"24px"}}),(0,K.jsx)(I.Z,{variant:"h6",style:{fontWeight:600},children:i})]}),o&&(0,K.jsx)(I.Z,{variant:"body2",style:{color:"#0a474c",fontSize:"12px",fontWeight:500,whiteSpace:"nowrap",cursor:"pointer"},onClick:e=>{e.stopPropagation(),r(t,p?"clear-all":"select-all")},children:p?"Clear All":"Select All"})]}),o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:"12px"},children:[s.length," placements"]}),(0,K.jsx)(f.Z,{container:!0,spacing:1,style:{flex:1,alignContent:"flex-start"},children:c.map((e=>{const a=s.includes(e.value);return(0,K.jsx)(f.Z,{item:!0,style:{width:"auto"},children:(0,K.jsx)(j.ZP,{title:e.description||e.label,placement:"top",children:(0,K.jsxs)(A.Z,{className:"".concat(d.positionChip," ").concat(a?d.positionChipSelected:""),onClick:a=>{a.stopPropagation(),l(t,e.value)},children:[a&&(0,K.jsx)(Ve.Z,{size:12,style:{marginRight:"3px"}}),(0,K.jsx)(I.Z,{variant:"body2",style:{fontSize:"11px",whiteSpace:"nowrap"},children:e.label})]})})},e.value)}))})]})]})}));var Ja=a(52232),Xa=a(59163),$a=a(72619),ei=a(48212);const{isAiSensy:ti}=(0,Y.K)(),ai=new Array(54).fill(1).map(((e,t)=>"".concat(t+13)));class ii extends r.Component{constructor(e){var t,a,s;super(e),t=this,this.isDuplicateAd=window.location.pathname.includes("duplicate"),this.isCreateAd=window.location.pathname.includes("create"),this.debounce=(e,t)=>{let a;return function(){for(var i=arguments.length,s=new Array(i),n=0;n<i;n++)s[n]=arguments[n];clearTimeout(a),a=setTimeout((()=>e(...s)),t)}},this.debouncedLogHi=n().debounce((e=>{let{selectedMetaAdAccountId:t,assistantId:a}=this.props.assistantDetails;t||(t=this.props.adSetupDetails.selectedMetaAdAccountId),i.Z.post("".concat(W.URL,"/meta-ads/location-search"),{assistantId:a,adAccountId:t,text:e}).then((e=>{var t;const a=(0,Ja.nH)(null===e||void 0===e||null===(t=e.data)||void 0===t?void 0:t.data);this.setState({searchLocation:a,isLoading:!1})}
2)).catch((e=>{console.error(e),this.setState({isLoading:!1,searchLocation:[]})}))}),500),this.debouncedAudienceSearch=n().debounce((e=>{let{selectedMetaAdAccountId:t,assistantId:a}=this.props.assistantDetails;t||(t=this.props.adSetupDetails.selectedMetaAdAccountId),this.props.fetchAudiences({assistantId:a,page:1,searchTerm:e,type:"ALL",limit:50,source:"META_ADS_TWO_TIER"})}),500),this.onSnackbarClose=()=>{this.setState({snack:!1})},this.onCreateAudienceSnackClose=()=>{this.setState({createAudienceSnack:{...this.state.createAudienceSnack,show:!1}})},this.refreshAudiencesList=async()=>{var e;const{assistantDetails:t,adSetupDetails:a}=this.props,i=(null===t||void 0===t||null===(e=t.adSetupDetails)||void 0===e?void 0:e.selectedMetaAdAccountId)||(null===a||void 0===a?void 0:a.selectedMetaAdAccountId);if(i)try{await this.props.syncAudiences({assistantId:null===t||void 0===t?void 0:t.assistantId,adAccountId:i})}catch(s){}this.props.fetchAudiences({assistantId:null===t||void 0===t?void 0:t.assistantId,page:1,searchTerm:"",type:"ALL",limit:50,source:"META_ADS_TWO_TIER"})},this.handleChangeD=(e,t,a)=>{this.debouncedLogHi(e.target.value),this.setState({isLoading:!0})},this.debouncedTargetSearch=n().debounce((e=>{let{selectedMetaAdAccountId:t,assistantId:a}=this.props.assistantDetails||{};if(t||(t=this.props.adSetupDetails.selectedMetaAdAccountId),t&&a){const s=(0,Xt.gK)(this.props.geoLocations);i.Z.post("".concat(W.URL,"/meta-ads/target-search"),{assistantId:a,adAccountId:t,text:e,countries:s}).then((e=>{this.setState({advanceSearchOptions:(0,Xt.Tc)(e.data.data,s),advanceTargetLoading:!1})})).catch((e=>{console.error(e),this.setState({advanceTargetLoading:!1})}))}}),700),this.handleAdvanceTargetChange=e=>{this.state.advanceTargetLoading||this.setState({advanceTargetLoading:!0}),this.debouncedTargetSearch(e.target.value)},this.verifyGeoLocations=(e,t,a)=>{try{const i=t.option.value;if(n().isEmpty(i))return;const{type:s,key:o}=i,{geoLocations:r,excludedGeoLocations:l}=this.props,{cities:d=[],places:c=[]}=r,p=Ja.n5[s]||"cities",u=r[p]||[];if("select-option"===a){if((0,Ja.r6)(s,o,l))return void this.setState({snack:!0});if(s&&Ja.M3.includes(s)){const e=("city"===s?d:c).find((e=>e.key===o));e&&e.radius?(i.radius=e.radius,i.distance_unit=e.distance_unit||Ja.Wy):(i.radius=Ja.J_[s],i.distance_unit=Ja.Wy),this.setState((e=>({locationRadiusMap:{...e.locationRadiusMap,[o]:i.radius}})))}const e=(0,Ja.uy)(s,i),t={...r,[p]:[...u,e]};this.props.changeState("geoLocations",t)}else if("remove-option"===a){const e=u.filter((e=>o!==((null===e||void 0===e?void 0:e.key)||e))),t={...r,[p]:e};this.props.changeState("geoLocations",t)}return e=e.filter(((e,t,a)=>t===a.findIndex((t=>t.label===e.label)))),void this.props.changeState("selectedLocations",e)}catch(i){console.log({error:i})}},this.verifyExcludedGeoLocations=(e,t,a)=>{try{const i=t.option.value;if(n().isEmpty(i))return;const{type:s,key:o}=i,{geoLocations:r,excludedGeoLocations:l}=this.props,d=Ja.n5[s]||"cities",c=l[d]||[];if("select-option"===a){if((0,Ja.r6)(s,o,r))return void this.setState({snack:!0});const e=(0,Ja.uy)(s,i),t={...l,[d]:[...c,e]};this.props.changeState("excludedGeoLocations",t)}else if("remove-option"===a){const e=c.filter((e=>o!==((null===e||void 0===e?void 0:e.key)||e))),t={...l,[d]:e};this.props.changeState("excludedGeoLocations",t)}return e=e.filter(((e,t,a)=>t===a.findIndex((t=>t.label===e.label)))),void this.props.changeState("excludedSelectedLocations",e)}catch(i){console.log({error:i})}},this.setAdvanceFilterOptions=e=>{const t=e.map((e=>{let{label:t,value:a}=e;const{id:i,type:s}=a||{};return"".concat(s,"-").concat(i)}));this.setState({advanceFilterOptions:t})},this.handleAdvanceTargetSelection=function(e){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];t.setAdvanceFilterOptions(a);const i=a.reduce(((e,t)=>{const{value:a}=t||{},{type:i}=a||{};return i?(e[i]?e[i].push(a):e[i]=[a],e):e}),{});t.props.changeState("advanceTargets",i),t.props.changeState("selectedAdvanceTargets",a),setTimeout((()=>{const e=document.querySelector(".advanced-targeting-autocomplete");if(e){const t=e.getBoundingClientRect();t.top>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)||e.scrollIntoView({behavior:"smooth",block:"center"})}}),100)},this.handleRadiusClick=(e,t,a)=>
2{this.setState({radiusAnchorEl:e.currentTarget,selectedLocationId:t,locationRadiusMap:{...this.state.locationRadiusMap,[t]:a}})},this.handleRadiusClose=()=>{this.setState({radiusAnchorEl:null,selectedLocationId:null})},this.handleRadiusChange=(e,t)=>{var a,i;const{selectedLocationId:s}=this.state,n=null===(a=this.props)||void 0===a||null===(i=a.selectedLocations)||void 0===i?void 0:i.find((e=>e.value.key===s));if(!n)return;const o=n.value.type,r=Math.round(t);if(!Ja.M3.includes(o))return;const l=Ja.LE[o],d=Ja.pg[o];if(r<l||r>d)return;this.setState((e=>({locationRadiusMap:{...e.locationRadiusMap,[s]:r}})));const c=(this.props.selectedLocations||[]).map((e=>{if(e.value.key===s){const t={...e,value:{...e.value,radius:r,distance_unit:e.value.distance_unit||Ja.Wy}},{geoLocations:a}=this.props,i=Ja.n5[e.value.type]||"cities",n=(a[i]||[]).map((e=>e.key===s?{...e,radius:r,distance_unit:"kilometer"}:e));return this.props.changeState("geoLocations",{...a,[i]:n}),t}return e}));this.props.changeState("selectedLocations",c)},this.handleLocationOptions=e=>{let{label:t,value:a}=e;return(0,K.jsxs)(A.Z,{width:"100%",style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)(A.Z,{width:"70%",pr:1,children:(0,K.jsx)(I.Z,{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t||""})}),(0,K.jsx)(A.Z,{width:"30%",style:{display:"flex",justifyContent:"flex-end",color:"#95a5a6",fontSize:"13px",alignItems:"center"},children:(0,Ja.w0)(a.type)})]})},this.targetOptionComponent=e=>{let{label:t,value:a}=e;const i={Behaviours:"#28c152",Behaviors:"#28c152",Interests:"#efa95e",Demographics:"#8859e7"},{path:s,audience_size_lower_bound:o,audience_size_upper_bound:r}=a,l=s[0];let d=[];o&&d.push(o.toLocaleString()),r&&d.push(r.toLocaleString()),d=d.join(" - ");const c={...a,audience:d};return(0,K.jsx)(j.ZP,{placement:"left",title:(0,K.jsx)(A.Z,{p:1.5,children:["name","type","audience","description"].map((e=>c[e]?(0,K.jsxs)(I.Z,{variant:"body2",gutterBottom:!0,children:[(0,K.jsx)("b",{children:"".concat(n().startCase(e)," : ")}),"type"!==e?c[e]:n().startCase(c[e])]}):(0,K.jsx)(K.Fragment,{})))}),arrow:!0,classes:{arrow:this.props.classes.arrow},children:(0,K.jsxs)(A.Z,{width:"100%",style:{display:"flex"},children:[(0,K.jsx)(A.Z,{width:"70%",pr:1,children:(0,K.jsx)(I.Z,{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t})}),(0,K.jsx)(A.Z,{width:"30%",style:{display:"flex",justifyContent:"end"},children:(0,K.jsx)(Wt.Z,{style:{borderRadius:"6px",color:i[l]?i[l]:"",borderColor:i[l]?i[l]:"",fontWeight:600,fontSize:"0.8em",alignItems:"center"},label:l,size:"small",variant:"outlined"})})]})})},this.MapPin=e=>{let{className:t,fill:a}=e;return(0,K.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"32",height:"32",fill:a,viewBox:"0 0 256 256",className:t,children:(0,K.jsx)("path",{d:"M128,16a88.1,88.1,0,0,0-88,88c0,75.3,80,132.17,83.41,134.55a8,8,0,0,0,9.18,0C136,236.17,216,179.3,216,104A88.1,88.1,0,0,0,128,16Zm0,56a32,32,0,1,1-32,32A32,32,0,0,1,128,72Z"})})},this.AudiencesIcon=e=>{let{className:t,fill:a}=e;return(0,K.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"32",height:"32",fill:a,viewBox:"0 0 256 256",className:t,children:(0,K.jsx)("path",{d:"M117.25,157.92a60,60,0,1,0-66.5,0A95.83,95.83,0,0,0,3.53,219.2a8,8,0,1,0,13.4,8.81,80,80,0,0,1,134.14,0,8,8,0,0,0,13.4-8.81A95.83,95.83,0,0,0,117.25,157.92ZM84,108a44,44,0,1,1,44,44A44.05,44.05,0,0,1,84,108Zm139.81,98.29a8,8,0,0,1-11.12,2.29A79.83,79.83,0,0,0,172,172a8,8,0,0,1,0-16,44,44,0,1,0-16.34-84.87,8,8,0,1,1-5.94-14.85,60,60,0,0,1,55.53,105.64,95.83,95.83,0,0,1,23.31,19.67A8,8,0,0,1,223.81,206.29Z"})})},this.debouncedAudienceSearch=n().debounce((e=>{const{assistantId:t}=this.props.assistantDetails;i.Z.post("".concat(W.ADS_REST_API_URL,"/meta/audiences/saved/search"),{assistantId:t,text:e}).then((e=>{this.setState({savedAudiences:e.data,audienceSearchLoading:!1})})).catch((e=>{console.error("Error searching audiences:",e),this.setState({audienceSearchLoading:!1})}))}),500),this.loadLatestAudiences=()=>{const{assistantId:e}=this.props.assistantDetails;
2this.setState({audienceSearchLoading:!0}),i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/audiences/saved/latest"),{params:{assistantId:e}}).then((e=>{this.setState({savedAudiences:e.data,audienceSearchLoading:!1,hasLoadedInitialAudiences:!0})})).catch((e=>{console.error("Error loading latest audiences:",e),this.setState({audienceSearchLoading:!1,hasLoadedInitialAudiences:!0})}))},this.handleAudienceSearch=e=>{const t=e.target.value;""!==t?(this.setState({audienceSearchLoading:!0}),this.debouncedAudienceSearch(t)):this.loadLatestAudiences()},this.handleAudienceSelect=(e,t)=>{var a,i;if(!t)return this.setState((e=>({audienceKey:e.audienceKey+1}))),this.props.changeState("gender","ALL"),this.props.changeState("FromAge","18"),this.props.changeState("ToAge","65"),this.props.changeState("selectedPlatforms","whatsapp_status"===(null===(a=this.props.parentState)||void 0===a||null===(i=a.adType)||void 0===i?void 0:i.value)?["instagram","whatsapp"]:[]),this.props.changeState("selectedAudience",null),this.props.changeState("audienceName",""),this.props.changeState("selectedLocations",[]),this.props.changeState("geoLocations",{}),this.props.changeState("excludedSelectedLocations",[]),this.props.changeState("excludedGeoLocations",{}),this.props.changeState("selectedAdvanceTargets",[]),this.props.changeState("advanceTargets",{}),void(this.props.getEstimatedDeliveryUsers&&this.props.getEstimatedDeliveryUsers());this.changeAudience(t)},this.bucketizeAudienceLocations=function(){const e={countries:[],cities:[],regions:[],places:[],zips:[]};return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).forEach((t=>{const{type:a}=t.value,i=Ja.n5[a]||"cities";e[i].push((0,Ja.uy)(a,t.value))})),e},this.changeAudience=e=>{var t,a;const{gender:i,minAge:s,maxAge:n,geoLocation:o,excludedGeoLocation:r,advanceTargets:l,selectedPlatforms:d}=e;if(this.props.changeState("gender",i),this.props.changeState("FromAge",s),this.props.changeState("ToAge",n),this.props.changeState("selectedPlatforms","whatsapp_status"===(null===(t=this.props.parentState)||void 0===t||null===(a=t.adType)||void 0===a?void 0:a.value)?["instagram","whatsapp"]:d||[]),this.props.changeState("selectedAudience",e),this.props.changeState("audienceName",e.audienceName),this.props.changeState("selectedLocations",o),this.props.changeState("geoLocations",this.bucketizeAudienceLocations(o)),this.props.changeState("excludedSelectedLocations",r||[]),this.props.changeState("excludedGeoLocations",this.bucketizeAudienceLocations(r||[])),l){const e=Object.entries(l).reduce(((e,t)=>{let[a,i]=t;return[...e,...i.map((e=>({label:e.name,value:e})))]}),[]);this.props.changeState("selectedAdvanceTargets",e),this.props.changeState("advanceTargets",l)}else this.props.changeState("selectedAdvanceTargets",[]),this.props.changeState("advanceTargets",{});this.props.getEstimatedDeliveryUsers&&this.props.getEstimatedDeliveryUsers()},this.handlePlatformToggle=(e,t)=>{const{adPlacements:a={},selectedPlatforms:i=[]}=this.props.parentState,{facebookPositions:s,instagramPositions:n}=a,o={facebook:{positions:Xt.JR,positionKey:"facebookPositions",positionsArray:s},instagram:{positions:Xt.oJ,positionKey:"instagramPositions",positionsArray:n}}[e];if(!o)return;(Array.isArray(o.positionsArray)&&o.positionsArray.length>0?o.positionsArray:i.includes(e)?o.positions.map((e=>e.value)):[]).length,o.positions.length;const r=i.includes(e);if("select-all"===t){const e=o.positions.map((e=>e.value));this.props.changeState("adPlacements",{...a,[o.positionKey]:e})}else if("clear-all"===t)this.props.changeState("".concat(e,"_positions"),[]),this.props.changeState("selectedPlatforms",i.filter((t=>t!==e))),this.props.changeState("adPlacements",{...a,[o.positionKey]:[]});else if(!0===t)this.props.changeState("".concat(e,"_positions"),[]),this.props.changeState("selectedPlatforms",i.filter((t=>t!==e))),this.props.changeState("adPlacements",{...a,[o.positionKey]:[]});else{const t=o.positions.map((e=>e.value)),s=r?i:[...i,e];this.props.changeState("selectedPlatforms",s),this.props.changeState("adPlacements",{...a,[o.positionKey]:t})}},this.handlePositionToggle=(e,t)=>
2{const{adPlacements:a,selectedPlatforms:i=[]}=this.props.parentState,{facebookPositions:s,instagramPositions:n}=a;if("facebook"===e){const e=Array.isArray(s)&&s.length>0?[...s]:i.includes("facebook")?Xt.JR.map((e=>e.value)):[],n=e.indexOf(t);n>-1?e.splice(n,1):e.push(t),this.props.changeState("adPlacements",{...a,facebookPositions:e});const o=this.props.parentState.selectedPlatforms||[];0===e.length?this.props.changeState("selectedPlatforms",o.filter((e=>"facebook"!==e))):o.includes("facebook")||this.props.changeState("selectedPlatforms",[...o,"facebook"])}else if("instagram"===e){const e=Array.isArray(n)&&n.length>0?[...n]:i.includes("instagram")?Xt.oJ.map((e=>e.value)):[],s=e.indexOf(t);s>-1?e.splice(s,1):e.push(t),this.props.changeState("adPlacements",{...a,instagramPositions:e});const o=this.props.parentState.selectedPlatforms||[];0===e.length?this.props.changeState("selectedPlatforms",o.filter((e=>"instagram"!==e))):o.includes("instagram")||this.props.changeState("selectedPlatforms",[...o,"instagram"])}},this.renderLockedPlacementCard=e=>{let{icon:t,title:a,positionLabel:i}=e;return(0,K.jsxs)(A.Z,{style:{borderRadius:"8px",padding:"16px",display:"flex",flexDirection:"column"},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",gap:"12px"},children:[(0,K.jsx)(j.ZP,{title:"Required by Meta for WhatsApp Status ads",children:(0,K.jsx)("span",{children:(0,K.jsx)(F.Z,{checked:!0,color:"primary",style:{padding:"4px",pointerEvents:"none"},inputProps:{"aria-label":"".concat(a," placement (required)")}})})}),(0,K.jsx)("img",{src:t,alt:"".concat(a," icon"),style:{width:"24px",height:"24px"}}),(0,K.jsx)(I.Z,{variant:"h6",style:{fontWeight:600},children:a})]}),(0,K.jsx)(I.Z,{variant:"body2",style:{color:"#0a474c",fontSize:"12px",fontWeight:500,whiteSpace:"nowrap"},children:"Required"})]}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:"12px"},children:"1 placement"}),(0,K.jsx)(f.Z,{container:!0,spacing:1,style:{flex:1,alignContent:"flex-start"},children:(0,K.jsx)(f.Z,{item:!0,style:{width:"auto"},children:(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"5px 14px",borderRadius:"20px",border:"1px solid #a19a9a",minHeight:"20px",width:"fit-content",backgroundColor:"#0a474c",color:"white"},children:[(0,K.jsx)(Ve.Z,{size:12,style:{marginRight:"3px"}}),(0,K.jsx)(I.Z,{variant:"body2",style:{fontSize:"11px",whiteSpace:"nowrap",color:"white"},children:i})]})})})]})},this.state={allFiltersLocal:null,isLoading:!1,advanceTargetLoading:!1,value:[18,65],age:[],searchLocation:[],selectedLocation:[],LocationValue:[],type:"",country_code:"",region_id:"",key:"",snack:!1,severity:"",advanceSearchOptions:[],advanceFilterOptions:[],radiusAnchorEl:null,selectedLocationId:null,locationRadiusMap:{},savedAudiences:[],audienceSearchLoading:!1,hasLoadedInitialAudiences:!1,audienceKey:0,createAudienceOpen:!1,createAudienceType:"custom",createAudienceMenuAnchor:null,createAudienceSnack:{show:!1,severity:"success",msg:""},showExcludeAudiences:((null===(a=this.props.parentState)||void 0===a?void 0:a.excludedCustomAndLookalikeAudiences)||[]).length>0,showExcludeLocations:((null===(s=this.props.parentState)||void 0===s?void 0:s.excludedSelectedLocations)||[]).length>0},this.handleLocationChange=this.handleLocationChange.bind(this)}componentDidUpdate(e){var t,a,i,s;this.state.showExcludeAudiences||!n().isEmpty(null===(t=e.parentState)||void 0===t?void 0:t.excludedCustomAndLookalikeAudiences)||n().isEmpty(null===(a=this.props.parentState)||void 0===a?void 0:a.excludedCustomAndLookalikeAudiences)||this.setState({showExcludeAudiences:!0}),this.state.showExcludeLocations||!n().isEmpty(null===(i=e.parentState)||void 0===i?void 0:i.excludedSelectedLocations)||n().isEmpty(null===(s=this.props.parentState)||void 0===s?void 0:s.excludedSelectedLocations)||this.setState({showExcludeLocations:!0})}componentDidMount(){if(this.props.parentState.selectedAudience?this.setState({savedAudiences:[this.props.parentState.selectedAudience],hasLoadedInitialAudiences:!0}):this.loadLatestAudiences(),n().isEmpty(this.props.selectedAdvanceTargets)||this.setAdvanceFilterOptions(this.props.selectedAdvanceTargets),!n().isEmpty(this.props.selectedLocations)){const e={};this.props.selectedLocations.forEach((t=>{var a;null!==t&&void 0!==t&&null!==(a=t.value)&&void 0!==a&&a.type&&Ja.M3.includes(t.value.type)&&t.value.radius&&(e[t.value.key]=t.value.radius)})),this.setState({locationRadiusMap:e})}const{assistantDetails:e}=this.props;this.props.fetchAudiences({assistantId:null===e||void 0===e?void 0:e.assistantId,page:1,searchTerm:"",type:"ALL",limit:50,source:"META_ADS_TWO_TIER"})}componentWillUnmount(){this.debouncedLogHi.cancel(),this.debouncedTargetSearch.cancel()}handleLocationChange(e){let{position:t,address:a,places:i}=e;this.setState({position:t,address:a})}render(){var e;const{classes:t,selectedPlatforms:a,agent:i,adSetupDetails:s}=this.props,{isLoading:o,snack:l,advanceTargetLoading:d,advanceSearchOptions:c,advanceFilterOptions:p}=this.state,{gender:u,selectedLocations:h,excludedSelectedLocations:m,FromAge:g,ToAge:x,selectedAdvanceTargets:v,geoLocations:y,excludedGeoLocations:S,adPlacements:Z,customAndLookalikeAudiences:T,excludedCustomAndLookalikeAudiences:D,adType:P}=this.props.parentState,B="whatsapp_status"===(null===P||void 0===P?void 0:P.value),E=window.innerWidth<=960,N=e=>n().groupBy(e,(e=>{var t,a,i;if(null!==e&&void 0!==e&&null!==(t=e.value)&&void 0!==t&&t.country_name)return e.value.country_name;const s=(null===e||void 0===e||null===(a=e.value)||void 0===a?void 0:a.country_code)||(null===e||void 0===e||null===(i=e.value)||void 0===i?void 0:i.country);if(s){const e=Va.ZP.find((e=>e.isoCode===s));return e?e.name:"Others"}return"Others"})),F=N(h),M=N(m),{facebookPositions:R,instagramPositions:O}=Z,U=Array.isArray(O)&&O.length>0?O:a.includes("instagram")?Xt.oJ.map((e=>e.value)):[],z=Array.isArray(R)&&R.length>0?R:a.includes("facebook")?Xt.JR.map((e=>e.value)):[],_=[...T,...D];return(0,K.jsxs)(f.Z,{container:!0,marginTop:"3em",children:[(0,K.jsx)(f.Z,{xs:12,md:12,children:(0,K.jsxs)(f.Z,{item:!0,xs:!0,style:{flexDirection:"column",justifyContent:"center",minWidth:"221px"},children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,className:t.bottomMargin,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Use Saved Audiences"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,style:{color:"#6E6E6E",marginBottom:"16
2px"},children:"Quickly target the right audience by applying pre-saved settings tailored to your needs"}),(0,K.jsx)(A.Z,{style:{maxWidth:"480px"},children:(0,K.jsx)(q.ZP,{options:this.state.savedAudiences,getOptionLabel:e=>e.audienceName,onChange:this.handleAudienceSelect,value:this.props.parentState.selectedAudience,loading:this.state.audienceSearchLoading,onFocus:e=>{this.state.hasLoadedInitialAudiences&&""!==e.target.value||this.loadLatestAudiences()},clearOnBlur:!1,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",placeholder:"Search saved audiences",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps,startAdornment:(0,K.jsx)(Ce.Z,{position:"start",children:(0,K.jsx)(Oe.Z,{size:20,className:t.searchIcon})}),endAdornment:(0,K.jsxs)(r.Fragment,{children:[this.state.audienceSearchLoading?(0,K.jsx)(k.Z,{size:20,style:{marginRight:60}}):null,e.InputProps.endAdornment]})},onChange:this.handleAudienceSearch}),renderOption:e=>{var t;return(0,K.jsxs)(A.Z,{onClick:t=>{e===this.props.parentState.selectedAudience&&this.changeAudience(e)},width:"100%",children:[(0,K.jsxs)(I.Z,{variant:"body1",style:{display:"flex",alignItems:"center"},children:[e.audienceName,e.changed&&(0,K.jsx)(I.Z,{variant:"caption",style:{marginLeft:"8px",color:"#f39c12",backgroundColor:"#fef5e7",padding:"2px 6px",borderRadius:"4px",fontSize:"11px"},children:"Modified"})]}),(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",children:"Gender: ".concat("ALL"===e.gender?"Male, Female":e.gender," \u2022 Age: ").concat(e.minAge,"-").concat(e.maxAge," \u2022 Platforms: ").concat((null===(t=e.selectedPlatforms)||void 0===t?void 0:t.map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(", "))||"")})]})},classes:{inputRoot:t.inputRoot}},this.state.audienceKey)})]}),(0,K.jsxs)(f.Z,{item:!0,xs:!0,className:t.bottomMargin,children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",mb:1,children:[(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,style:{marginBottom:0},children:"Select Custom or Lookalike Audience"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,style:{color:"#6E6E6E",marginBottom:"16px"},children:"Select multiple custom or lookalike audience to target your ads to."})]}),(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",style:{gap:"12px"},children:[(0,K.jsx)(w.Z,{size:"small",variant:"outlined",color:"primary",startIcon:(0,K.jsx)(Ra.Z,{size:16}),style:{textTransform:"none",fontSize:"13px",padding:"6px 12px"},onClick:e=>this.setState({createAudienceMenuAnchor:e.currentTarget}),children:"Create Custom or Lookalike Audience"}),(0,K.jsx)(j.ZP,{title:this.state.showExcludeAudiences&&!n().isEmpty(D)?"Remove the excluded audiences to hide this section":"",children:(0,K.jsx)("span",{children:(0,K.jsx)(w.Z,{size:"small",variant:"outlined",color:"primary",disabled:this.state.showExcludeAudiences&&!n().isEmpty(D),style:{textTransform:"none",fontSize:"13px",padding:"6px 12px"},onClick:()=>this.setState({showExcludeAudiences:!this.state.showExcludeAudiences}),children:this.state.showExcludeAudiences?"Hide Excluded Audiences":"Exclude Audiences"})})})]}),(0,K.jsxs)(Yt.Z,{anchorEl:this.state.createAudienceMenuAnchor,open:Boolean(this.state.createAudienceMenuAnchor),onClose:()=>this.setState({createAudienceMenuAnchor:null}),getContentAnchorEl:null,anchorOrigin:{vertical:"bottom",horizontal:"left"},children:[(0,K.jsx)(de.Z,{onClick:()=>this.setState({createAudienceMenuAnchor:null,createAudienceType:"custom",createAudienceOpen:!0}),children:"Custom Audience"}),(0,K.jsx)(de.Z,{onClick:()=>this.setState({createAudienceMenuAnchor:null,createAudienceType:"lookalike",createAudienceOpen:!0}),children:"Lookalike Audience"})]})]}),(0,K.jsxs)(A.Z,{style:{width:"100%"},children:[(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsx)(q.ZP,{multiple:!0,options:this.props.audiences.filter((e=>!_.find((t=>t.audienceId==e.audienceId)))).filter(((e,t,a)=>t===a.findIndex((t=>t.audienceId===e.audienceId)))).map((e=>{const{name:t,audienceId:a}=e;return{label:n().compact([t,"(".concat(a,")")]).join(" "),value:e}})),getOptionLabel:e=>e.label||e,value:T,onChange:(e,t,a,i)=>{var s;const{name:n,audienceId:o,accountId:r,type:l}=null===i||void 0===i||null===(s=i.option)||void 0===s?void 0:s.value;T.find((e=>e.audienceId==o))||this.props.changeState("customAndLookalikeAudiences",[...T,{name:n,audienceId:o,accountId:r,type:l}])},loading:o,className:t.autocompletePadding,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",placeholder:n().isEmpty(T)?"Search Custom or Lookalike Audiences":"",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps,startAdornment:(0,K.jsx)(Ce.Z,{position:"start",children:(0,K.jsx)(Oe.Z,{size:20,className:t.
2searchIcon})}),endAdornment:(0,K.jsx)(r.Fragment,{children:(0,K.jsx)(Ce.Z,{children:o?(0,K.jsx)(b.Z,{children:(0,K.jsx)(k.Z,{size:16})}):(0,K.jsx)(K.Fragment,{})})})},onChange:e=>this.debouncedAudienceSearch(e.target.value),onKeyDown:e=>{"Backspace"===e.key&&""===e.target.value&&e.stopPropagation()},name:"location"}),renderOption:e=>{let{label:t,value:a}=e;return(0,K.jsxs)(A.Z,{width:"100%",style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)(A.Z,{width:"70%",pr:1,children:(0,K.jsx)(I.Z,{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t||""})}),(0,K.jsxs)(A.Z,{width:"30%",style:{display:"flex",justifyContent:"flex-end",color:"#95a5a6",fontSize:"13px",alignItems:"center"},children:[(null===a||void 0===a?void 0:a.accountId)==(null===s||void 0===s?void 0:s.selectedMetaAdAccountId)?"Owned":"Fetched"," ","- ",n().startCase(null===a||void 0===a?void 0:a.type)]})]})},renderTags:()=>null,classes:{inputRoot:t.inputRoot,input:t.autocompleteInput}})}),!n().isEmpty(T)&&(0,K.jsx)("div",{className:t.locationMainContainer,children:T.filter(((e,t,a)=>t===a.findIndex((t=>t.audienceId===e.audienceId)))).map(((e,a)=>(0,K.jsxs)("div",{className:t.locationItem,children:[(0,K.jsxs)("div",{className:t.locationInfo,children:[(0,K.jsx)(this.AudiencesIcon,{className:t.locationPin,fill:"#28c153"}),(0,K.jsx)("div",{className:t.locationNameGroup,children:(0,K.jsxs)(I.Z,{className:t.locationName,style:{width:"100%"},children:[null===e||void 0===e?void 0:e.name," (",null===e||void 0===e?void 0:e.audienceId,")"]})})]}),(0,K.jsxs)("div",{className:t.rightSection,children:[(0,K.jsxs)(I.Z,{className:t.locationType,children:[(null===e||void 0===e?void 0:e.accountId)==(null===s||void 0===s?void 0:s.selectedMetaAdAccountId)?"Owned":"Fetched"," ","- ",n().startCase(null===e||void 0===e?void 0:e.type)]}),(0,K.jsx)(b.Z,{size:"small",className:t.removeButton,onClick:()=>{const t=T.filter((t=>t.audienceId!==e.audienceId));this.props.changeState("customAndLookalikeAudiences",t)},children:(0,K.jsx)(Le.Z,{size:16,className:t.removeIcon})})]})]},null===e||void 0===e?void 0:e.audienceId)))})]}),this.state.showExcludeAudiences&&(0,K.jsxs)(A.Z,{style:{width:"100%",marginTop:"24px"},children:[(0,K.jsx)(I.Z,{children:"Exclude Custom or Lookalike Audiences"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,style:{color:"#6E6E6E",marginBottom:"16px"},children:"Select custom or lookalike audience to exclude from your ads."}),(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsx)(q.ZP,{multiple:!0,options:this.props.audiences.filter((e=>!_.find((t=>t.audienceId==e.audienceId)))).filter(((e,t,a)=>t===a.findIndex((t=>t.audienceId===e.audienceId)))).map((e=>{const{name:t,audienceId:a}=e;return{label:n().compact([t,"(".concat(a,")")]).join(" "),value:e}})),getOptionLabel:e=>e.label||e,value:D,onChange:(e,t,a,i)=>{var s;const{name:n,audienceId:o,accountId:r,type:l}=null===i||void 0===i||null===(s=i.option)||void 0===s?void 0:s.value;_.find((e=>e.audienceId==o))||this.props.changeState("excludedCustomAndLookalikeAudiences",[...D,{name:n,audienceId:o,accountId:r,type:l}])},loading:o,className:t.autocompletePadding,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",placeholder:n().isEmpty(D)?"Search Custom or Lookalike Audiences":"",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps,startAdornment:(0,K.jsx)(Ce.Z,{position:"start",children:(0,K.jsx)(Oe.Z,{size:20,className:t.searchIcon})}),endAdornment:(0,K.jsx)(r.Fragment,{children:(0,K.jsx)(Ce.Z,{children:o?(0,K.jsx)(b.Z,{children:(0,K.jsx)(k.Z,{size:16})}):(0,K.jsx)(K.Fragment,{})})})},onChange:e=>this.debouncedAudienceSearch(e.target.value),onKeyDown:e=>{"Backspace"===e.key&&""===e.target.value&&e.stopPropagation()},name:"location"}),renderOption:e=>{let{label:t,value:a}=e;return(0,K.jsxs)(A.Z,{width:"100%",style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)(A.Z,{width:"70%",pr:1,children:(0,K.jsx)(I.Z,{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t||""})}),(0,K.jsxs)(A.Z,{width:"30%",style:{display:"flex",justifyContent:"flex-end",color:"#95a5a6",fontSize:"13px",alignItems:"center"},children:[(null===a||void 0===a?void 0:a.accountId)==(null===s||void 0===s?void 0:s.selectedMetaAdAccountId)?"Owned":"Fetched"," ","- ",n().startCase(null===a||void 0===a?void 0:a.type)]})]})},renderTags:()=>null,classes:{inputRoot:t.inputRoot,input:t.autocompleteInput}})}),!n().isEmpty(D)&&(0,K.jsx)("div",{className:t.locationMainContainer,children:D.filter(((e,t,a)=>t===a.findIndex((t=>
2t.audienceId===e.audienceId)))).map(((e,a)=>(0,K.jsxs)("div",{className:t.locationItem,children:[(0,K.jsxs)("div",{className:t.locationInfo,children:[(0,K.jsx)(this.AudiencesIcon,{className:t.locationPin,fill:"#28c153"}),(0,K.jsx)("div",{className:t.locationNameGroup,children:(0,K.jsxs)(I.Z,{className:t.locationName,style:{width:"100%"},children:[null===e||void 0===e?void 0:e.name," (",null===e||void 0===e?void 0:e.audienceId,")"]})})]}),(0,K.jsxs)("div",{className:t.rightSection,children:[(0,K.jsxs)(I.Z,{className:t.locationType,children:[(null===e||void 0===e?void 0:e.accountId)==(null===s||void 0===s?void 0:s.selectedMetaAdAccountId)?"Owned":"Fetched"," ","- ",n().startCase(null===e||void 0===e?void 0:e.type)]}),(0,K.jsx)(b.Z,{size:"small",className:t.removeButton,onClick:()=>{const t=D.filter((t=>t.audienceId!==e.audienceId));this.props.changeState("excludedCustomAndLookalikeAudiences",t)},children:(0,K.jsx)(Le.Z,{size:16,className:t.removeIcon})})]})]},null===e||void 0===e?void 0:e.audienceId)))})]})]}),(0,K.jsxs)(f.Z,{item:!0,xs:!0,className:t.bottomMargin,children:[(0,K.jsxs)(A.Z,{display:"flex",alignItems:"center",justifyContent:"space-between",mb:1,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,style:{marginBottom:0},children:"Select Locations"}),(0,K.jsx)(j.ZP,{title:this.state.showExcludeLocations&&!n().isEmpty(m)?"Remove the excluded locations to hide this section":"",children:(0,K.jsx)("span",{children:(0,K.jsx)(w.Z,{size:"small",variant:"outlined",color:"primary",disabled:this.state.showExcludeLocations&&!n().isEmpty(m),style:{textTransform:"none",fontSize:"13px",padding:"6px 12px"},onClick:()=>this.setState({showExcludeLocations:!this.state.showExcludeLocations}),children:this.state.showExcludeLocations?"Hide Excluded Locations":"Exclude Locations"})})})]}),(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsx)(q.ZP,{multiple:!0,options:this.state.searchLocation.map((e=>{const{name:t,country_name:a,region:i}=e;return{label:n().compact([t,i,a]).join(", "),value:e}})),getOptionLabel:e=>e.label||e,value:h,onChange:(e,t,a,i)=>{this.verifyGeoLocations(t,i,a)},loading:o,className:t.autocompletePadding,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",placeholder:n().isEmpty(h)?"Search cities, regions, countries, pin codes":"",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps,startAdornment:(0,K.jsx)(Ce.Z,{position:"start",children:(0,K.jsx)(Oe.Z,{size:20,className:t.searchIcon})}),endAdornment:(0,K.jsx)(r.Fragment,{children:(0,K.jsx)(Ce.Z,{children:o?(0,K.jsx)(b.Z,{children:(0,K.jsx)(k.Z,{size:16})}):(0,K.jsx)(K.Fragment,{})})})},onChange:this.handleChangeD,onKeyDown:e=>{"Backspace"===e.key&&""===e.target.value&&e.stopPropagation()},name:"location"}),renderOption:this.handleLocationOptions,renderTags:()=>null,classes:{inputRoot:t.inputRoot,input:t.autocompleteInput}})}),!n().isEmpty(h)&&(0,K.jsxs)("div",{className:t.locationMainContainer,children:[Object.entries(F).map((e=>{let[a,i]=e;return(0,K.jsxs)("div",{children:[(0,K.jsx)(I.Z,{className:t.countryTitle,variant:"h5",gutterBottom:!0,children:a}),i.map((e=>{var a,i,s,n,o;return(0,K.jsxs)("div",{className:t.locationItem,children:[(0,K.jsxs)("div",{className:t.locationInfo,children:[(0,K.jsx)(this.MapPin,{className:t.locationPin,fill:"#28c153"}),(0,K.jsxs)("div",{className:t.locationNameGroup,children:[(0,K.jsx)(j.ZP,{title:"zip"===(null===e||void 0===e||null===(a=e.value)||void 0===a?void 0:a.type)&&null!==e&&void 0!==e&&null!==(i=e.value)&&void 0!==i&&i.region?"".concat(e.value.name,", ").concat(e.value.region):null===e||void 0===e||null===(s=e.value)||void 0===s?void 0:s.name,children:(0,K.jsx)(I.Z,{className:t.locationName,children:"zip"===(null===e||void 0===e||null===(n=e.value)||void 0===n?void 0:n.type)&&null!==e&&void 0!==e&&null!==(o=e.value)&&void 0!==o&&o.region?"".concat(e.value.name,", ").concat(e.value.region):e.value.name})}),Ja.M3.includes(e.value.type)&&(0,K.jsxs)(w.Z,{endIcon:(0,K.jsx)(Be.Z,{size:16}),variant:"text",className:t.radiusButton,onClick:t=>this.handleRadiusClick(t,e.value.key,e.value.radius),children:["+",e.value.radius," km"]})]})]}),(0,K.jsxs)("div",{className:t.rightSection,children:[(0,K.jsx)(I.Z,{className:t.locationType,children:(0,Ja.w0)(e.value.type)}),(0,K.jsx)(b.Z,{size:"small",className:t.removeButton,onClick:()=>{var t;const a=h.filter((t=>t.value.key!==e.value.key));this.props.changeState("selectedLocations",a),this.setState((t=>{const a={...t.locationRadiusMap};return delete a[e.value.key],{locationRadiusMap:a}}));const{geoLocations:i}=this.props,s=Ja.n5[null===e||void 0===e||null===(t=e.value)||void 0===t?void 0:t.type]||"cities",n=i[s].filter((t=>(t.key||t)!==e.value.key));this.props.changeState("geoLocations",{...i,[s]:n})},children:(0,K.jsx)(Le.Z,{size:16,className:t.removeIcon})})]})]},e.value.key)}))]},a)}
2)),(0,K.jsx)(Qa.ZP,{open:Boolean(this.state.radiusAnchorEl),anchorEl:this.state.radiusAnchorEl,onClose:this.handleRadiusClose,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},PaperProps:{elevation:2},children:(0,K.jsxs)("div",{className:t.radiusPopover,children:[(0,K.jsx)(I.Z,{className:t.radiusTitle,children:"Select Radius"}),(0,K.jsx)("div",{className:t.radiusSliderContainer,children:(()=>{var e;const a=this.props.selectedLocations.find((e=>e.value.key===this.state.selectedLocationId)),i=null===a||void 0===a||null===(e=a.value)||void 0===e?void 0:e.type;return(0,K.jsx)(Ga.Z,{className:t.radiusSlider,value:this.state.locationRadiusMap[this.state.selectedLocationId]||Ja.J_[i]||40,onChange:this.handleRadiusChange,min:Ja.LE[i],max:Ja.pg[i],step:1,marks:[{value:Ja.LE[i],label:"".concat(Ja.LE[i]||1,"km")},{value:Ja.pg[i],label:"".concat(Ja.pg[i]||80,"km")}],valueLabelDisplay:"auto"})})()})]})})]})]}),this.state.showExcludeLocations&&(0,K.jsxs)(f.Z,{item:!0,xs:!0,className:t.bottomMargin,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Exclude Locations"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"People in these locations will not be shown this ad"}),(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsx)(q.ZP,{multiple:!0,options:this.state.searchLocation.map((e=>{const{name:t,country_name:a,region:i}=e;return{label:n().compact([t,i,a]).join(", "),value:e}})),getOptionLabel:e=>e.label||e,value:m,onChange:(e,t,a,i)=>{this.verifyExcludedGeoLocations(t,i,a)},loading:o,className:t.autocompletePadding,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",placeholder:n().isEmpty(m)?"Search cities, regions, countries, pin codes":"",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps,startAdornment:(0,K.jsx)(Ce.Z,{position:"start",children:(0,K.jsx)(Oe.Z,{size:20,className:t.searchIcon})}),endAdornment:(0,K.jsx)(r.Fragment,{children:(0,K.jsx)(Ce.Z,{children:o?(0,K.jsx)(b.Z,{children:(0,K.jsx)(k.Z,{size:16})}):(0,K.jsx)(K.Fragment,{})})})},onChange:this.handleChangeD,onKeyDown:e=>{"Backspace"===e.key&&""===e.target.value&&e.stopPropagation()},name:"excludedLocation"}),renderOption:this.handleLocationOptions,renderTags:()=>null,classes:{inputRoot:t.inputRoot,input:t.autocompleteInput}})}),!n().isEmpty(m)&&(0,K.jsx)("div",{className:t.locationMainContainer,children:Object.entries(M).map((e=>{let[a,i]=e;return(0,K.jsxs)("div",{children:[(0,K.jsx)(I.Z,{className:t.countryTitle,variant:"h5",gutterBottom:!0,children:a}),i.map((e=>{var a,i,s,n,o;return(0,K.jsxs)("div",{className:t.locationItem,children:[(0,K.jsxs)("div",{className:t.locationInfo,children:[(0,K.jsx)(this.MapPin,{className:t.locationPin,fill:"#e05e5e"}),(0,K.jsx)("div",{className:t.locationNameGroup,children:(0,K.jsx)(j.ZP,{title:"zip"===(null===e||void 0===e||null===(a=e.value)||void 0===a?void 0:a.type)&&null!==e&&void 0!==e&&null!==(i=e.value)&&void 0!==i&&i.region?"".concat(e.value.name,", ").concat(e.value.region):null===e||void 0===e||null===(s=e.value)||void 0===s?void 0:s.name,children:(0,K.jsx)(I.Z,{className:t.locationName,children:"zip"===(null===e||void 0===e||null===(n=e.value)||void 0===n?void 0:n.type)&&null!==e&&void 0!==e&&null!==(o=e.value)&&void 0!==o&&o.region?"".concat(e.value.name,", ").concat(e.value.region):e.value.name})})})]}),(0,K.jsxs)("div",{className:t.rightSection,children:[(0,K.jsx)(I.Z,{className:t.locationType,children:(0,Ja.w0)(e.value.type)}),(0,K.jsx)(b.Z,{size:"small",className:t.removeButton,onClick:()=>{var t;const a=m.filter((t=>t.value.key!==e.value.key));this.props.changeState("excludedSelectedLocations",a);const i=Ja.n5[null===e||void 0===e||null===(t=e.value)||void 0===t?void 0:t.type]||"cities",s=(S[i]||[]).filter((t=>(t.key||t)!==e.value.key));this.props.changeState("excludedGeoLocations",{...S,[i]:s})},children:(0,K.jsx)(Le.Z,{size:16,className:t.removeIcon})})]})]},e.value.key)}))]},a)}))})]}),(0,K.jsx)(f.Z,{container:!0,style:{display:"flex",gap:"20px",marginTop:"24px"},className:t.bottomMargin,children:(0,K.jsxs)(f.Z,{container:!0,spacing:2,direction:E?"column":"row",children:[(0,K.jsxs)(f.Z,{item:!0,xs:12,md:6,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Select Gender"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Choose target gender preference"}),(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsx)(q.ZP,{disableClearable:!0,autoHighlight:!0,options:["MALE","FEMALE","ALL"],onChange:(e,t,a)=>{this.props.changeState("gender",t)},value:u,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps},placeholder:"Select Gender",name:"gender",value:u}),classes:{inputRoot:t.inputRoot}})})]}),(0,K.jsxs)(f.Z,{item:!0,xs:12,sm:6,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:"Select age group"}),(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",children:"Pick specific target age group"}),(0,K.jsxs)(f.Z,{container:!0,spacing:1,children:[(0,K.jsx)(f.Z,{item:!0,xs:5,children:(0,K.jsx)(q.ZP,{disableClearable:!0,autoHighlight:!0,options:ai.slice(0,-1),getOptionLabel:e=>
2"66"===e?"65+":e,onChange:(e,t,a)=>{this.props.changeState("FromAge",t)},value:g,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps},placeholder:"Select",name:"FromAge",value:g}),classes:{inputRoot:t.inputRoot}})}),(0,K.jsx)(f.Z,{item:!0,xs:2,style:{display:"flex",alignItems:"center",justifyContent:"center"},children:(0,K.jsx)(I.Z,{children:"To"})}),(0,K.jsx)(f.Z,{item:!0,xs:5,children:(0,K.jsx)(q.ZP,{disableClearable:!0,autoHighlight:!0,options:ai.filter((e=>e>=g)),getOptionLabel:e=>"66"===e?"65+":e,onChange:(e,t,a)=>{this.props.changeState("ToAge",t)},value:x,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",classes:{root:t.textFieldRoot},InputProps:{...e.InputProps},placeholder:"Select",name:"toAge",value:x}),classes:{inputRoot:t.inputRoot}})})]})]})]})}),(0,K.jsxs)(f.Z,{item:!0,xs:!0,className:t.bottomMargin,children:[(0,K.jsx)(I.Z,{variant:"h5",gutterBottom:!0,children:ti?"Platforms & Placements":"Platforms"}),B?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",style:{marginBottom:"16px"},children:"WhatsApp Status ads also appear on Instagram Stories \u2014 Meta requires both placements, so they're pre-selected for you."}),(0,K.jsxs)(f.Z,{container:!0,spacing:1,children:[(0,K.jsx)(f.Z,{item:!0,xs:12,md:6,children:this.renderLockedPlacementCard({icon:Ya,title:"WhatsApp",positionLabel:"Status"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,md:6,children:this.renderLockedPlacementCard({icon:qa,title:"Instagram",positionLabel:"Stories"})})]})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(I.Z,{variant:"body2",gutterBottom:!0,color:"textSecondary",style:{marginBottom:"16px"},children:ti?"Select platforms and specific placements to target your ads":"Select platforms to target your ads"}),(0,K.jsxs)(f.Z,{container:!0,spacing:1,children:[(0,K.jsx)(f.Z,{item:!0,xs:12,md:6,children:(0,K.jsx)(Ka,{platform:"instagram",platformIcon:qa,platformTitle:"Instagram",selectedPositions:U,isAiSensy:ti,isPlatformSelected:Array.isArray(this.props.parentState.selectedPlatforms)&&this.props.parentState.selectedPlatforms.includes("instagram"),onPlatformToggle:this.handlePlatformToggle,onPositionToggle:this.handlePositionToggle})}),(0,K.jsx)(f.Z,{item:!0,xs:12,md:6,children:(0,K.jsx)(Ka,{platform:"facebook",platformIcon:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAABhLSURBVHic7d1drNz1fefxzxn7HD8c2xh8IPJgSLAlHqIOMi0EAukDtClpSVmJUFolDpBGbdVk26o3nBu36224mfSqD5vsDa2EyQppk4sKRUuUVZCqshugu6QcrXiQskpCOq0QSlwTwDXLOXsxY2MbbJ+Hmf9v5vxeLylxYuxzvoDGv/f/N7/5/6eWlpay3rTnF7YnuTLJ1UmuSrIvyc4kO5JsP+PHmUJjAlDW8SRHk7x2xo9Hknw3yYtJXkjyUq/bea3UkKMyNekB0J5f2JrkliS3Jbkx/QW/XXQoANabXvpB8FSSbyV5stftvFF2pLWZuABozy9Mp7/g35r+ov+huIoHoFnHkzydfgw8kX4QvFV2pJWZmABozy/ckOTeJL+ZZK7wOABwqleTPJrk4V6380zpYZZjrAOgPb9wWZIDST6d5JrC4wDAcjyf5HCSR3rdzsulhzmbsQyA9vzCtUkOJvlEklbhcQBgNRaTfC3Jg71u57nSw5xprAJgsM1/MMmvJZkqPA4ADMNSksfSD4GxeXtgLAKgPb9wU5JDSW4vPAoAjNI3khzqdTvfLj1I0QBozy9ckuSL6R/uc8UPQA2Wkjyc5IFet/NKqSGKBEB7fqGV5PeSPJj+DXoAoDZH0n/b+8u9bmex6W/eeAAMtvu/lOS6Rr8xAIynZ5N8rum3BRoLgMFV/58k+eM42Q8Ap1pM8oUkf9rUbkAjAdCeX9id5Cvp370PAHhvTyT5VK/b+edRf6ORX4m35xc+muQ7sfgDwPncmuQ7g7VzpEa2A9CeX5hK/6N9B2PLHwBWYjH9g/KHet3OSBbqkQTA4IE9D6V/C18AYHUOJ/nsKB40NPQAaM8vzCb5apKPDfULA0CdHk9yd6/beX2YX3SoAdCeX5hL8vX0H9ELAAzH00nu6HU7rw7rCw4tANrzC5cn+WaSK4fyBQGAU72U5KO9bucHw/hiQwmAwZX/k7H4A8AovZTklmHsBKz5dP7gPf+vx+IPAKN2ZZKvD9beNVlTAAxO+3813vMHgKZ8KMlXB2vwqq06AAaf838oTvsDQNM+luShwVq8KmvZATgUn/MHgFI+nf5avCqrOgQ4uEXh43GHPwAoaTHJx3rdzjdX+htXHACDB/t8J8klK/1mAMDQvZJk/0ofILSiK/jBI32/Eos/AIyLS5J8ZbBGL9tKt/D/JJ7qBwDj5tb01+hlW/ZbAO35hZvSv9mP9/0BYPwspn+ToG8v5xcvKwAG2wr/kOS6tc0GAIzQs0mu73U7i+f7hcu9mv+9WPwBYNxdl/6afV7n3QFozy9ckuTFJDvXPhcAMGJHklzV63ZeOdcvWs4OwBdj8QeASbEz/bX7nM65AzA4+Pc/kqz6VoMAQOOWktx8rgOB59sBOBSLPwBMmqmc5zbBZ90BaM8v3JDk6eHPBAA05EO9bueZ9/oL59oBODiiYQCAZpx1LX/PHYD2/MK16d/v3/Y/AEyupfSfE/DcmX/hbDsAB2PxB4BJN5Wz7AK8awegPb9wWZLvxS1/AWA9WEzygV638/KpP/lei/yBs/w8ADB5Wumv7e/6yTN9evSzAAANetfafloADD76d01j4wAATbhmsMafdOYOwL0NDgMANOe0Nf7kIcD2/MJ0kl6SuQJDAQCj9WqSdq/beSs5fQfgllj8AWC9mkt/rU9yegDc2vwsAECDTq71pwbAbQUGAQCac3Ktn1paWkp7fmFrkh8nmSk3EwAwYseTXNjrdt44sQNwSyz+ALDezWRwDuBEANj+B4A63Ja8EwA3FhwEAGjOjck7AXBVwUEAgOZclSRTux94bnuSo4WHAQCas6OV5MrSUwAAjbqyleTq0lMAAI26uhXv/wNAba5qJdlXegoAoFH7Wkl2lp4CAGjUzlaSHaWnAAAataOVZHvpKQCARm23AwAA9bEDAAAVsgMAABXa0YrHAANAbWZa5/81AMB6IwAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqJAAAoEICAAAqtLH0AADrwcXbNmbv3Ez2zs3k0p3T2bapldlNrf6PM613/v/MOz8/vWGq9NhFvf/gC6VHqJoAAFimzdNT2Tu3KfvmZnLF3Ez2DRb8vXMz2bbJhiqTRQAAnMXMxqn89GVbcvPerbl572yu27M5Gyu/amf9EAAAAxtbU+lcunmw4G/N9ZdvzeZpCz7rkwAAqrZ5eiq/fM323Hntjtx8xdbM2sqnEgIAqM7UVHLjB7bmE/svyK/+1Hbv31MlAQBUY+/cTO7af0Hu2r8jl+6cLj0OFCUAgHVtZuNU7r7ugvzGz+zM/j2bS48DY0MAAOvSlulWPnnDzvzuz16U9233Rx2cyasCWFdmN7Vy740X5rdvuSi7ZjeUHgfGlgAA1oULtmzIZz58YX7rwxfmgi0WfjgfAQBMtNlNrXz+53bl/psu9BE+WAEBAEysO6
2/dkYO/con3+GEVvGqAibPv4pl84ePvyy37ZkuPAhNLAAATY8t0K7//C7vyOx+5qPon6cFaCQBgItx+zfYcuuOStN3AB4ZCAABjbdfshvzZXbvzi1dtKz0KrCsCABhbN12xNX95TzuXOOQHQ+dVBYyd1lTyB7fO5Q9vnUvLW/0wEgIAGCsXb9uYv7innZv3bi09CqxrAgAYGx/ZN5s///XdmdvmjyYYNa8yoLgNreSPbrs4n//5Xbb8oSECAChqZuNU/uqedm7/4PbSo0BVBABQzLZNrTx0YE9uusL7/dA0AQAUMbdtYw7ftycf3L259ChQJQEANO7yi6bzyP2X5/0XuasflCIAgEZ9cPfmHL5vj5P+UJhXINCYm67YmocO7Mm2Ta3So0D1BADQiJuu2JqH77ssmzb6nB+MAxkOjNwHd2/OQwf2WPxhjAgAYKQuv2g6h++z7Q/jxisSGJm5bRvzyP2XO/AHY0gAACOxbVMrh+/b46N+MKYEADB0Mxun8tABN/mBcSYAgKHa0Er+6p622/vCmBMAwFD90W0Xe7APTAABAAzNR/bN5vM/v6v0GMAyCABgKC7etjF//uu70/JRf5gIAgBYs9ZU8hf3tH3cDyaIAADW7A9uncvNex36g0kiAIA1uemKrfnDW+dKjwGskAAAVm3X7Ib85T1t7/vDBBIAwKr92V27c8l27/vDJBIAwKrcfs32/OJV20qPAaySAABWbMt0K4fuuKT0GMAaCABgxX7/F3alvdNDfmCSCQBgRfZdPJPf+chFpccA1kgAACvyhY+/L9MbHPuHSScAgGW789oduWXfbOkxgCEQAMCyzG5q5eCvOPgH64UAAJbl8z+3K+/zmX9YNwQAcF4XbNmQ+2+6sPQYwBAJAOC8PvPhCzO7yR8XsJ54RQPnNLupld/6sKt/WG8EAHBO9954YS7YsqH0GMCQCQDgrLZMt/Lbt7jpD6xHAgA4q0/esDO7Zl39w3okAID3NLNxKr/7s67+Yb0SAMB7uvu6C3zuH9YxAQC8p9/4mZ2lRwBGSAAA77J3bib792wuPQYwQgIAeJe79l9QegRgxAQAcJqpqeSu/TtKjwGMmAAATnPjB7bm0p3TpccARkwAAKf5hO1/qIIAAE7aPD2VX/2p7aXHABogAICTfvma7dnmqX9QBa904KQ7r3X4D2ohAIAkycbWVG6+YmvpMYCGCAAgSdK5dHNmbf9DNbzagSTJzXtd/UNNBACQRABAbQQAkJmNU7n+cgEANREAQH76si3ZPD1VegygQQIAsP0PFRIAQG7eO1t6BKBhAgAqt3l6Ktft2Vx6DKBhAgAqt3duUzZu8P4/1EYAQOX2zc2UHgEoQABA5a4QAFCljaUHAMqyAzAZjh57Owv/dCzP/dOx/N9Xj+fIm2/nX99czJE3386RN97O0WOLeXtpKUtL/V+/dPK/kqWc/vMn/jd1EwBQub0CYGw9+/KbOfz0kfzvH7yZ7/3ouIWboRIAUDkBMH6eeOkn+fLf/ShPfe+N0qOwjgkAqNjF2zZmmycAjo2jx97OZw7/MP/w/TdLj0IFBABUzNX/+Djy5ts58DcvZ6F3rPQoVEIAQMUEwHj40Rtv55N//YM8/y//VnoUKmLvDyp26c7p0iOQ5I8f+xeLP40TAFAx7/+X98Mfv5X/9n9eKz0GFfLqh4rNCoDi/vp//jhvL5aeghp59UPF7ACU9dqxxTz6v46UHoNKefVDxWZn/BFQ0n9/4Sd5/d9c/lOGVz9UzA5AWT888lbpEaiYVz9UzBmAsnr/KgAox6sfKrbNWwBFCQBK8uqHitkBKKt35P+VHoGKefVDxZwBKMsOACV59UPFpjdMlR6haj/xCQAKEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUCEBAAAVEgAAUKGp3Q88t1R6CCjl+w9eXXoEYBUWesfy8S99r/QYE80OAAAT5788c6T0CBNPAAAwUV4/vpi//cejpceYeAIAgInyt/94NK8fXyw9xsQTAABMFNv/wyEAAJgYC71jWegdKz3GuiAAAJgYrv6HRwAAMBEc/hsuAQDARHD4b7gEAAATwfb/cAkAAMaew3/DJwAAGHuu/odPAAAw1hz+Gw0BAMBYc/hvNAQAAGPN9v9oCAAAxpbDf6MjAAAYW67+R0cAADCWHP4bLQEAwFhy+G+0BAAAY8n2/2gJAADGjsN/oycAABg7rv5HTwAAMFYc/muGAABgrDj81wwBAMBYsf3fDAEAwNhw+K85AgCAseHqvzkCAICx4PBfswQAAGPB4b9mCQAAxoLt/2YJAACKc/iveQIAgOJc/TdPAABQlMN/ZQgAAIpy+K8MAQBAUbb/yxAAABTj8F85AgCAYlz9lyMAACjC4b+yBAAARTj8V5YAAKAI2/9lCQAAGufwX3kCAIDGufovTwAA0CiH/8aDAACgUQ7/jQcBAECjbP+PBwEAQGMc/hsfAgCAxrj6Hx8CAIBGOPw3XgQAAI1w+G+8CAAAGmH7f7wIAABGzuG/8SMAABg5V//jRwAAMFIO/40nAQDASDn8N54EAAAjZft/PAkAAEbG4b/xJQAAGBlX/+NLAAAwEg7/jTcBAMBIOPw33gQAACNh+3+8CQAAhs7hv/EnAAAYOlf/408AADBUDv9NBgEAwFA5/DcZBAAAQ2X7fzIIAACGxuG/ySEAABgaV/+TQwAAMBQO/00WAQDAUDj8N1kEAABDYft/sggAANbM4b/JIwAAWDNX/5NHAACwJg7/TSYBAMCaOPw3mQQAAGti+38yCQAAVs3hv8klAABYNVf/k0sAALAqDv9NNgEAwKo4/DfZBAAAq2L7f7JN7X7guaXSQwBlfP/Bq0uPULX3H3yh9AhUzA4AAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFRIAABAhQQAAFSoleR46SEAgEYdbyU5WnoKAKBRR1tJXis9BQDQqNfsAABAfewAAECF7AAAQIWOtpIcKT0FANCoI60k3y09BQDQqO+2krxYegoAoFEvtpK8UHoKAKBRL7SSvFR6CgCgUS+1et3Oa0l6pScBABrR63U7r514GJBzAABQhxeTd54G+FTBQQCA5jyVvBMA3yo4CADQnG8l7wTAk/FYYABY746nv+b3A6DX7byR5OmSEwEAI/f0YM0/uQOQeBsAANa7k2v9qQHwRIFBAIDmnFzrTw2AJ5O82vwsAEADXs3g/f/klADodTtvJXm0xEQAwMg9Oljrk5y+A5AkDzc8DADQjNPW+NMCoNftPJPk+UbHAQBG7fnBGn/SmTsASXK4oWEAgGa8a21/rwB4JMni6GcBABqwmP7afpp3BUCv23k5ydeamAgAGLmvDdb207zXDkCSPJhkabTzAAAjtpT+mv4u7xkAvW7nuSSPjXIiAGDkHhus6e9yth2A5CzFAABMjLOu5WcNgMHHBb4xknEAgFH7xpkf/TvVuXYAkuRQnAUAgEmzlP4aflbnDIBet/PtuDsgAEyahwdr+FmdbwcgSR5IcmQ48wAAI3Yk/bX7nM4bAL1u55UkB4cxEQAwcgcHa/c5LWcHIEm+nOTZtc0DAIzYs+mv2ee1rADodTuLST4XtwgGgHG1mORzgzX7vJa7A3DiQOAXVjsVADBSXzjfwb9TLTsABv40yRMr/D0AwGg9kf4avWwrCoDBtsKnkpz3cAEA0IhXknxquVv/J6x0ByC9buefkxyI8wAAUNpikgODtXlFVhwASdLrdr4ZzwoAgNIeHKzJK7aqABg4lOTwGn4/ALB6h3Oe2/2ey6oDoNftLCX5bJLHV/s1AIBVeTzJZwdr8aqsZQcgvW7nrSR3J3l6LV8HAFi2p5PcPViDV21NAZAkvW7n9SR3JHlprV8LADinl5LcMVh712TNAZAkvW7n1SQfjQgAgFF5KclHB2vumg0lAJKk1+38IMkt8XYAAAzb00luGay1QzG0AEhO7gTcFgcDAWBYHk9y27Cu/E8YagAkJ88E3BkfEQSAtTqc5M5hvOd/pqEHQHLy0wH3pX9fYncMBICVWUx/Db1vraf9z2bjKL5ocvI+Af+hPb/w90keSXLJqL4XAKwjr6R/e99V3eFvuUayA3Cqwd
2/A/niKIACczxNJ9o968U8aCIDk5AOEfinJf4y3BADgTIvpr5G/tJoH+6zGyN4CONPgMYWH2vMLjyf5UpLrmvreADDGnk3yuV638+0mv2kjOwCnGvwNXp/k3yc50vT3B4AxcST9tfD6phf/pMEdgFMNdgP+U3t+4b8m+WKSe5NMlZgFABq2lOThJA/0up1XSg1RJABOGPyN39+eX/jP6T/S8PaS8wDAiH0jyaESV/xnKhoAJwz+QXysPb9wQ5KDSX4tdgQAWB+WkjyW5MFet/NM6WFOGIsAOGHwD+bftecXrk0/BD6RAucUAGAIFpN8Lf2F/7nSw5xprALghME/qHva8wuXJTmQ5NNJrik7FQAsy/Pp38L3kV6383LpYc5mamlpqfQMyzJ4e+DeJL+ZZK7wOLAufP/Bq0uPULX3H3yh9AgMz6tJHk3y8Dht85/LxATACe35hen0Hzt8a/pPHvxQkpmiQ8GEEgBlCYCJdjz9R/R+K/279z05qnv2j8rEBcCZ2vMLW9MPgtuS3JjkqiTtokPBhBAAZQmAidJL8mKSp9Jf9J/sdTtvlB1pbcbyDMBKDP4FfHPwnyRJe35he5Irk1ydfhDsS7IzyY4k28/40e4BQJ2OJzma5LUzfjyS5LvpL/gvJHmp1+28VmrIUfn/d6LtDhl1jFQAAAAASUVORK5CYII=",platformTitle:"Facebook",selectedPositions:z,isAiSensy:ti,isPlatformSelected:Array.isArray(this.props.parentState.selectedPlatforms)&&this.props.parentState.selectedPlatforms.includes("facebook"),onPlatformToggle:this.handlePlatformToggle,onPositionToggle:this.handlePositionToggle})})]})]})]}),null!==(e=this.props.deprecatedAdvanceTargets)&&void 0!==e&&e.length?this.props.deprecatedAdvanceTargets.some((e=>!n().isEmpty(v)&&v.some((t=>t.value.id===e.id))))&&(0,K.jsx)("div",{className:t.bottomMargin,children:(0,K.jsx)(si,{})}):null,(0,K.jsxs)(f.Z,{item:!0,xs:!0,className:t.bottomMargin,children:[(0,K.jsxs)("div",{className:t.targetTitleContainer,children:[(0,K.jsx)(I.Z,{variant:"h5",style:{marginBottom:"0.35em"},children:"Advanced Targeting"}),(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)("div",{className:t.colorDot,style:{backgroundColor:"#efa95e"}}),(0,K.jsx)(I.Z,{variant:"body2",className:t.targetTypeText,children:"Interests"})]}),(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)("div",{className:t.colorDot,style:{backgroundColor:"#8859E7"}}),(0,K.jsx)(I.Z,{variant:"body2",className:t.targetTypeText,children:"Demographics"})]}),(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,K.jsx)("div",{className:t.colorDot,style:{backgroundColor:"#28c152"}}),(0,K.jsx)(I.Z,{variant:"body2",className:t.targetTypeText,children:"Behaviors"})]})]})]}),!n().isEmpty(v)&&(0,K.jsx)("div",{className:t.targetMainContainer,children:v.map((e=>{var a,i,s,n,o,r,l,d,c,p,u,h;const m=this.props.deprecatedAdvanceTargets.some((t=>t.id===e.value.id));return(0,K.jsxs)("div",{className:"".concat(t.targetItem," ").concat(m?t.deprecated:null!==e&&void 0!==e&&null!==(a=e.value)&&void 0!==a&&a.path&&"Interests"===(null===e||void 0===e||null===(i=e.value)||void 0===i?void 0:i.path[0])?t.interests:null!==e&&void 0!==e&&null!==(s=e.value)&&void 0!==s&&s.path&&"Demographics"===(null===e||void 0===e||null===(n=e.value)||void 0===n?void 0:n.path[0])?t.demographics:null!==e&&void 0!==e&&null!==(o=e.value)&&void 0!==o&&o.path&&"Behaviors"===(null===e||void 0===e||null===(r=e.value)||void 0===r?void 0:r.path[0])?t.behaviors:""),children:[(0,K.jsx)("div",{className:t.targetInfo,children:(0,K.jsx)("div",{className:t.targetNameGroup,children:(0,K.jsx)(j.ZP,{title:e.label,children:(0,K.jsxs)(I.Z,{className:t.targetName,children:[m&&(0,K.jsx)($a.Z,{style:{width:"15px",marginRight:"5px"}}),e.label,m&&(0,K.jsx)(Wt.Z,{label:"DEPRECATED",className:t.deprecatedChip,component:"span"})]})})})}),(0,K.jsx)("div",{className:t.rightSection,children:(0,K.jsx)(b.Z,{size:"small",className:t.removeButton,onClick:()=>{const t=v.filter((t=>t.value.id!==e.value.id));this.handleAdvanceTargetSelection(null,t)},children:(0,K.jsx)(Le.Z,{size:16,className:"".concat(m?t.deprecatedRemoveIcon:null!==e&&void 0!==e&&null!==(l=e.value)&&void 0!==l&&l.path&&"Interests"===(null===e||void 0===e||null===(d=e.value)||void 0===d?void 0:d.path[0])?t.interestsRemoveIcon:null!==e&&void 0!==e&&null!==(c=e.value)&&void 0!==c&&c.path&&"Demographics"===(null===e||void 0===e||null===(p=e.value)||void 0===p?void 0:p.path[0])?t.demographicsRemoveIcon:null!==e&&void 0!==e&&null!==(u=e.value)&&void 0!==u&&u.path&&"Behaviors"===(null===e||void 0===e||null===(h=e.value)||void 0===h?void 0:h.path[0])?t.behaviorsRemoveIcon:"")})})})]},"".concat(e.value.type,"-").concat(e.value.id))}
2))}),(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsx)(q.ZP,{multiple:!0,value:v,onChange:this.handleAdvanceTargetSelection,loading:d,className:"".concat(t.autocompletePadding," ").concat(v.length>0?"advanced-targeting-autocomplete":""),style:{borderRadius:"0 0 8px 8px"},options:c.filter((e=>null===e||void 0===e?void 0:e.type)).map((e=>{const{name:t}=e;return{label:t,value:e}})),filterOptions:e=>e.filter((e=>{const{value:t}=e,{id:a,type:i}=t||{};return!(null!==p&&void 0!==p&&p.includes("".concat(i,"-").concat(a)))})),getOptionLabel:e=>e.label||e,renderOption:this.targetOptionComponent,renderInput:e=>(0,K.jsx)(L.Z,{...e,variant:"outlined",placeholder:"Type Interests, Demographics or behaviours and press enter to add",classes:{root:"".concat(t.textFieldRoot," ").concat(v.length>0?t.noTopRadius:"")},InputProps:{...e.InputProps,endAdornment:(0,K.jsx)(r.Fragment,{children:(0,K.jsx)(Ce.Z,{children:d?(0,K.jsx)(b.Z,{children:(0,K.jsx)(k.Z,{size:16})}):null})})},onChange:this.handleAdvanceTargetChange,onKeyDown:e=>{"Backspace"===e.key&&""===e.target.value&&e.stopPropagation()},name:"advanceTargets"}),renderTags:()=>null,classes:{inputRoot:t.inputRoot}})}),(0,K.jsxs)(A.Z,{style:{marginTop:24,display:"block"},children:[(0,K.jsxs)(I.Z,{variant:"h5",gutterBottom:!0,style:{marginBottom:8,display:"flex",alignItems:"center"},children:["Audience expansion",(0,K.jsx)(j.ZP,{title:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(I.Z,{variant:"body2",display:"block",style:{marginBottom:4},children:[(0,K.jsx)("strong",{children:"On:"})," Meta can show your ad to more people similar to your targeting. Location, age, language and exclusions stay fixed. Often improves performance."]}),(0,K.jsxs)(I.Z,{variant:"body2",display:"block",children:[(0,K.jsx)("strong",{children:"Off:"})," Ad is shown only to your selected audience\u2014no expansion beyond your targeting."]})]}),arrow:!0,placement:"right",children:(0,K.jsx)($a.Z,{style:{width:"16px",marginLeft:"6px",color:"#666",cursor:"pointer"}})})]}),(0,K.jsx)(zt.Z,{control:(0,K.jsx)(C.Z,{color:"primary",checked:!0===this.props.parentState.advantageAudience,disabled:!0===this.props.parentState.advantageAudienceLocked,onChange:e=>this.props.changeState("advantageAudience",e.target.checked)}),label:(0,K.jsx)(I.Z,{variant:"body2",component:"span",children:"Allow Meta to expand audience"})}),!0===this.props.parentState.advantageAudienceLocked&&(0,K.jsx)(I.Z,{variant:"caption",component:"p",style:{color:"#666",marginTop:"-4px"},children:"Advantage+ audience can\u2019t be turned off after an ad is created. Create a new ad to set detailed targeting, lookalikes or custom audiences as controls."})]})]})]})}),(0,K.jsx)(ht.A9,{open:l,onClose:this.onSnackbarClose,anchorOrigin:{vertical:"top",horizontal:"center"},severity:"error",message:"Locations are overlaping"}),(0,K.jsx)(Xa.Z,{open:this.state.createAudienceOpen,onClose:()=>this.setState({createAudienceOpen:!1,createAudienceType:"custom"}),audienceType:this.state.createAudienceType,assistantDetails:this.props.assistantDetails,onSuccess:e=>{this.setState({createAudienceOpen:!1,createAudienceType:"custom",createAudienceSnack:{show:!0,severity:"success",msg:e}}),this.refreshAudiencesList()},onError:e=>{this.setState({createAudienceSnack:{show:!0,severity:"error",msg:e}})}}),(0,K.jsx)(ht.A9,{open:this.state.createAudienceSnack.show,onClose:this.onCreateAudienceSnackClose,anchorOrigin:{vertical:"top",horizontal:"center"},severity:this.state.createAudienceSnack.severity,message:this.state.createAudienceSnack.msg})]})}}const si=()=>(0,K.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:"16px",padding:"16px",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px"},children:[(0,K.jsx)(ei.aN,{style:{color:"#ef4444"}}),(0,K.jsxs)("div",{style:{flex:1},children:[(0,K.jsx)("div",{style:{display:"flex",alignItems:"center",marginBottom:"4px"},children:(0,K.jsx)(I.Z,{variant:"subtitle2",style:{fontSize:"0.875rem",fontWeight:600,color:"#991b1b"},children:"Deprecated Targeting Detected"})}),(0,K.jsx)(I.Z,{variant:"body2",style:{fontSize:"0.875rem",color:"#b91c1c"},children:"Some of your selected advanced targets are no longer supported by the platform. Please remove or replace them to ensure your Ad can be published."})]})]}),ni=(0,o.connect)((e=>({pageDetails:e.ads.pageDetails,allFilters:e.filters.allFilters,filename:e.ads.filename,details:e.ads.details,previewImageUrl:e.ads.previewImageUrl,assistantDetails:e.assistantDetails.data,adSetupDetails:e.assistantDetails.adSetupDetails,agent:e.login.user,audiences:e.audience.audiences})),{fetchAudiences:za.I$,syncAudiences:za.Ah})(ii),oi=(0,N.Z)((e=>({root:{width:"100%",padding:"20px 10px",marginTop:"5%"},bottomMargin:{marginBottom:e.spacing(4)},filterTypeContainer:{borderRadius:"5px",minHeight:100},ad:{display:"flex",marginTop:"1.35em",marginBottom:"2em",justifyContent:"center",[e.breakpoints.up("md")]:{minWidth:"315px"}},textFieldRoot:{backgroundColor:"rgb(240,240,240)",outline:"none",border:"none",borderRadius:"8px",width:"100%",padding:"0",boxShadow:"none",boxSizing:"border-box",fontFamily:"Roboto, sans-serif",fontSize:"15px",fontWeight:500,maxHeight:"12em",overflow:"auto","&::-webkit-scrollbar":{width:"4px"}},inputPadding:{padding:"12px 10px"},inputRoot:{'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-input':{padding:12},'&&[class*="MuiOutlinedInput-root"]':{padding:0},'&[class*="MuiOutlinedInput-root"].MuiAutocomplete-inputRoot':{paddingRight:"0 !important",paddingLeft:"0 !important"}},snackbar:{zIndex:5e3},arrow:{color:"white"}
2,qualityStatus:{"& .MuiChip-label":{color:"white",fontSize:"0.9em"}},locationMainContainer:{backgroundColor:"#f0f0f0",borderRadius:"8px",padding:"14px",marginTop:e.spacing(2)},countryTitle:{color:"#2d3436",marginBottom:e.spacing(1)},locationItem:{backgroundColor:"#ffffff",borderRadius:"8px",padding:"6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",boxShadow:"0 1px 2px rgba(0,0,0,0.05)"},removeButton:{padding:4,"&:hover":{backgroundColor:"rgba(0, 0, 0, 0.04)"}},removeIcon:{color:"#666"},locationInfo:{display:"flex",alignItems:"center",gap:"8px",flex:1},locationPin:{color:"#28c153",width:20,height:20},locationNameGroup:{display:"flex",alignItems:"center",justifyContent:"flex-start"},locationName:{fontSize:"13px",fontWeight:400,color:"#2d3436",width:"70px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},locationType:{color:"#95a5a6",fontSize:"13px"},rightSection:{display:"flex",alignItems:"center",gap:e.spacing(2)},radiusButton:{color:"#2d3436",fontSize:"13px",textTransform:"none",padding:"4px 8px",paddingLeft:0,minWidth:"unset",marginLeft:"8px","&:hover":{backgroundColor:"transparent"}},radiusPopover:{padding:e.spacing(2),width:280},radiusSlider:{height:4,"& .MuiSlider-rail":{height:4,backgroundColor:"#e0e0e0"},"& .MuiSlider-track":{height:4}},radiusTitle:{fontSize:"16px",fontWeight:500,marginBottom:e.spacing(3),color:"#2d3436"},radiusSliderContainer:{padding:e.spacing(0,1)},autocompleteInput:{paddingLeft:"8px !important"},searchIcon:{color:"#666",marginLeft:e.spacing(1)},targetTitleContainer:{display:"flex",alignItems:"center",justifyContent:"space-between",[e.breakpoints.down("xs")]:{flexDirection:"column",alignItems:"flex-start",gap:"4px",marginBottom:"4px"}},targetMainContainer:{borderRadius:"8px 8px 0 0",padding:"12px",marginTop:e.spacing(1),border:"1px solid #e0e0e0",display:"flex",flexWrap:"wrap",gap:"8px",width:"100%",boxSizing:"border-box",maxWidth:"100vw",overflowX:"hidden",[e.breakpoints.down("xs")]:{padding:"8px",gap:"4px"}},targetTypeTitle:{color:"#2d3436",marginBottom:e.spacing(1)},targetItem:{backgroundColor:"#ffffff",borderRadius:"8px",padding:"4px 6px 4px 12px",display:"flex",alignItems:"center",boxShadow:"0 1px 2px rgba(0,0,0,0.05)",maxWidth:"100%",boxSizing:"border-box",border:"1px solid #e0e0e0",[e.breakpoints.down("xs")]:{width:"100%",padding:"4px 4px 4px 8px"}},interests:{border:"1px solid #efa95e",color:"#efa95e"},demographics:{border:"1px solid #8859E7",color:"#8859E7"},behaviors:{border:"1px solid #28c152",color:"#28c152"},deprecated:{border:"1px dashed #ef4444",color:"#ef4444"},interestsRemoveIcon:{color:"#efa95e"},demographicsRemoveIcon:{color:"#8859e7"},behaviorsRemoveIcon:{color:"#28c152"},deprecatedRemoveIcon:{color:"#ef4444"},targetInfo:{display:"flex",alignItems:"center",gap:"8px",flex:1,paddingRight:4,minWidth:0,[e.breakpoints.down("xs")]:{maxWidth:"calc(100% - 28px)",gap:"4px"}},targetNameGroup:{display:"flex",alignItems:"center",justifyContent:"flex-start",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},targetName:{fontSize:"13px",fontWeight:400,maxWidth:"100%",whiteSpace:"nowrap",overflow:"hidden",display:"flex",alignItems:"center",textOverflow:"ellipsis",[e.breakpoints.down("xs")]:{fontSize:"12px"}},targetType:{color:"#95a5a6",fontSize:"13px"},colorDot:{width:8,height:8,borderRadius:"50%",marginRight:4},targetTypeText:{lineHeight:0,marginRight:8,color:"#808080"},noTopRadius:{borderTopLeftRadius:"0 !important",borderTopRightRadius:"0 !important","& .MuiOutlinedInput-root":{borderTopLeftRadius:0,borderTopRightRadius:0}},deprecatedChip:{height:"auto",padding:"0 4px",borderRadius:"4px",marginLeft:e.spacing(1),backgroundColor:"#ef4444",color:"#ffffff",fontSize:"10px",fontWeight:"bold",textTransform:"uppercase",letterSpacing:"0.05em","& .MuiChip-label":{paddingLeft:0,paddingRight:0}}})))(ni);var ri=a(49300),li=a(93738),di=a(44556),ci=a(22806),pi=a(32506),ui=a(31685),hi=a(91529),mi=a(10373),gi=a(12853);const{isPartner:xi,isAiSensy:vi,isTenant:yi}=(0,Y.K)(),fi={CONVERSATIONS:"Conversations",LEAD_GENERATION:"Leads",QUALITY_LEAD:"Leads",LINK_CLICKS:"Link Clicks",LANDING_PAGE_VIEWS:"Landing Page Views",OFFSITE_CONVERSIONS:"Conversions",POST_ENGAGEMENT:"Post Engagements",IMPRESSIONS:"Impressions",REACH:"Reach"};class Ai extends r.Component{constructor(e){var t;super(e),t=this,this.isDuplicateAd=window.location.pathname.includes("duplicate"),this.isEditAd=window.location.pathname.includes("edit"),this.isCreateAd=window.location.pathname.includes("create"),this.budgetOptions=[{label:"Lifetime Budget",value:"lifetime_budget"},{label:"Daily Budget",value:"daily_budget"}],this.timezoneOptions=[{label:"Use Viewer's time zone",value:"viewer"},{label:"Use this ad accnount's time zone",value:"ad_account"}],this.geoToSelectedLocations=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(await Promise.all(["cities","countries","regions","places","zips"].map((a=>t.locationOptionValue(e[a]||[]))))).flat()},this.hydrateFromAdTemplate=async e=>{var t,a;if(!e)return;const i=Xt.T$.find((t=>t.value===e.adType))||Xt.T$[0],s=(0,Xt.Ge)(i.type),n=e.budgetType||"daily_budget",o=(0,Xt.rz)(Xt.eO,e.adObjective)||s.objective,r=(0,Xt.rz)(null===o||void 0===o?void 0:o.optimizationGoals,e.optimizationGoal)||s.goal,l=(null===(t=e.advanceTargets)||void 0===t||null===(a=t.flexible_spec)||void 0===a?void 0:a[0])||e.advanceTargets||{},d={selectedAdType:i.value,adType:i,adName:e.adName||"".concat(i.label," - Template"),adHeadline:e.headline||"",adCaption:e.adDescription||"",adHeadlineDescription:e.headlineDescription||"",websiteUrl:e.websiteUrl||"",gender:e.gender||"ALL",FromAge:e.minAge?String(e.minAge):"18",ToAge:e.maxAge?String(e.maxAge):"65",selectedBudget:{label:"lifetime_budget"===n?"Lifetime Budget":"Daily Budget",value:n},advanceTargets:l,selectedAdvanceTargets:this.targetingOptionValue([l]),adPlacements:e.adPlacements||this.state.adPlacements,leadFormId:e.leadFormId||this.state.leadFormId,pixelId:e.pixelId||this.state.pixelId,customAndLookalikeAudiences:e.customAndLookalikeAudiences||this.state.customAndLookalikeAudiences,excludedCustomAndLookalikeAudiences:e.excludedCustomAndLookalikeAudiences||this.state.excludedCustomAndLookalikeAudiences,advantageAudience:!0===e.advantageAudience||1===Number(e.advantageAudience),duration:Number(e.duration)||this.state.duration,isScheduledAd:!!e.isScheduledAd};o&&(d.adObjective=o),r&&(d.optimizationGoal=r),e.pixelId&&(d.pixel=(0,Xt.rz)(this.props.pixels,e.pixelId,"pixelId")||{value:e.pixelId,label:e.pixelId}),e.conversionEvent&&(d.conversionEvent=(0,Xt.rz)(Xt.kg,e.conversionEvent)||this.state.conversionEvent),e.iceBreakers&&"boolean"===typeof e.iceBreakers.status&&(d.switchChecked=e.iceBreakers.status);const c=e.callToAction||e.ctaButton;if(c&&"WHATSAPP_MESSAGE"!==c&&(d.ctaButton=c),e.geoLocation){const t=(0,mi.gS)(e.geoLocation,e.geoLocationDisplay);d.geoLocations={...this.state.geoLocations,...t},d.selectedLocations=await this.geoToSelectedLocations(t)}if(e.excludedGeoLocation){const t=(0,mi.gS)(e.excludedGeoLocation,e.geoLocationDisplay);d.excludedGeoLocations={...this.state.excludedGeoLocations,...t},d.excludedSelectedLocations=await this.geoToSelectedLocations(t)}Array.isArray(e.platforms)&&e.platforms.length&&(d.selectedPlatforms=e.platforms),"lifetime_budget"===n?d.lifetimeBudget=Number(e.lifetimeBudget)||this.state.lifetimeBudget:d.dailyBudget=Number(e.dailyBudget)||this.state.dailyBudget,e.adStartDate&&(d.fromDate=new Date(e.adStartDate)),e.adStopDate&&(d.toDate=new Date(e.adStopDate),d.isEndDate=!0),e.imageUrl&&(d.imageFile={publicUrl:e.imageUrl}),e.videoUrl&&(d.videoFile={publicUrl:e.videoUrl},d.thumbnailUrl=e.imageUrl?{publicUrl:e.imageUrl}:null),this.setState(d,(()=>{"function"===typeof this.getEstimatedDeliveryUsers&&this.getEstimatedDeliveryUsers()})),e.audienceId&&this.fetchSavedAudiences({audienceId:e.audienceId})},this.toggleAdCreditDialog=()=>{this.setState({adDialogOpen:!this.state.adDialogOpen})},this.syncIceBreakers=()=>{const e=[...this.state.iceBreakers];for(let t of e){const e=this.props.iceBreakers.iceBreakers.find((e=>e.iceBreakerId===t.iceBreakerId));e&&(t.blockId=e.blockId||"",t.blockHandle=e.blockHandle||"")}this.setState({iceBreakers:e})},this.shouldShowBudgetNextBtn=()=>this.state.activeStep<2||this.state.switchChecked,this.exitPath=()=>{var e,t;const{projectId:a}=this.props.match.params,i=null===(e=this.props.location)||void 0===e||null===(t=e.state)||void 0===t?void 0:t.returnTo;return"string"===typeof i&&i.startsWith("/")?i:"/projects/".concat(a,"/advertisement")},this.toggleDialog=()=>{const{isLiveAD:e}=this.state;if(!this.nextBtnDisableStatus(0)&&!e||this.isDuplicateAd){const{showDialog:e}=this.state;this.setState({showDialog:!e})}else this.props.history.push(this.exitPath())},this.getEstimatedDeliveryUsers=function(){var e,a;let s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;t.setState({estimatedReachLoading:!0});const{geoLocations:n,excludedGeoLocations:o,gender:r,FromAge:l,ToAge:d,advanceTargets:c,selectedPlatforms:p,adPlacements:u,customAndLookalikeAudiences:h,excludedCustomAndLookalikeAudiences:m}=t.state,{assistantId:g}=t.props.assistantDetails,x=t.resolveAdAccountId();i.Z.post("".concat(W.URL,"/meta-ads/get-delivery-estimate-result"),{adAccountId:x,minAge:parseInt(l),maxAge:parseInt(d),gender:r,geoLocation:n,excludedGeoLocation:o,selectedPlatforms:p,advanceTargets:c,assistantId:g,adPlacements:u,advantageAudience:t.state.advantageAudience?1:0,customAudiences:(h||[]).map((e=>
2e.audienceId)).filter(Boolean),excludedCustomAudiences:(m||[]).map((e=>e.audienceId)).filter(Boolean),optimizationGoal:(null===(e=t.state.optimizationGoal)||void 0===e?void 0:e.value)||"CONVERSATIONS",dailyBudget:"daily_budget"===(null===(a=t.state.selectedBudget)||void 0===a?void 0:a.value)&&parseInt(t.state.dailyBudget)||0}).then((e=>{var a,i,n,o;0===(null===e||void 0===e||null===(a=e.data)||void 0===a||null===(i=a.data)||void 0===i?void 0:i.estimate_dau)&&0===s?t.getEstimatedDeliveryUsers(s+1):t.setState({estimatedData:(null===e||void 0===e||null===(n=e.data)||void 0===n?void 0:n.data)||{},estimatedDailyResults:(null===e||void 0===e||null===(o=e.data)||void 0===o?void 0:o.estimatedDailyResults)||null,estimatedReachLoading:!1})})).catch((e=>{console.log({error:e}),t.setState({estimatedData:null,estimatedDailyResults:null,estimatedReachLoading:!1})}))},this.locationOptionValue=async e=>{const t={};return Va.ZP.forEach((e=>{t[e.isoCode]=e.name})),e.map((e=>{if("string"===typeof e){const a=t[e];return{label:a?"".concat(a,", ").concat(a):e,value:{type:"country",key:e,name:a||e,country_name:a||e}}}const{name:a,country_name:i,region:s}=e;return{label:n().compact([a,s,i]).join(", "),value:e}})).filter((e=>!!e.label))},this.advanceTargetBucket=e=>"interests"===e?"Interests":"behaviors"===e?"Behaviors":"Demographics",this.targetingOptionValue=e=>{const t=[];return e.forEach((e=>{null!==e&&void 0!==e&&e.custom_audiences||null!==e&&void 0!==e&&e.excluded_custom_audiences||Object.keys(e).forEach((a=>{e[a]&&Array.isArray(e[a])&&e[a].forEach((e=>{e.name&&t.push({label:e.name,value:{...e,type:a,path:e.path||[this.advanceTargetBucket(a)]}})}))}))})),t},this.fetchSavedAudiences=e=>{let{audienceId:t}=e;const{projectId:a}=this.props.match.params;i.Z.get("".concat(W.ADS_REST_API_URL,"/meta/audiences/saved/by-id?audienceId=").concat(t,"&assistantId=").concat(a)).then((e=>{var t;this.setState({selectedAudience:e.data,audienceName:null===(t=e.data)||void 0===t?void 0:t.audienceName})})).catch((e=>{console.log({error:e})}))},this.getSelectedSlotsCount=e=>{let t=0;for(let a of e)"7"!==a[0]&&t++;return t},this.fetchMetaAdAccount=async e=>{e&&(await i.Z.post("".concat(W.URL,"/meta-ads/fetch-meta-ad-setup"),{assistantId:e}).then((e=>{const{isValid:t,pageId:a,adAccountId:i}=null===e||void 0===e?void 0:e.data;this.props.updateAssistantStore({fbConnected:t,selectedMetaPageId:t?a:"",selectedMetaAdAccountId:t?i:""}),this.props.updateAdSetupStore({fbConnected:t,selectedMetaPageId:t?a:"",selectedMetaAdAccountId:t?i:""})})).catch((e=>{console.log({error:e})})),this.fetchAdAccount(),this.fetchMetaPage())},this.handleToDateChange=e=>{if(!e)return void this.setState({isEndDateNull:!0});const t=new Date,a=new Date(e);a.setHours(t.getHours()),a.setMinutes(t.getMinutes()),a.setSeconds(t.getSeconds()),a.setMilliseconds(t.getMilliseconds()),this.setState({toDate:a,isEndDateNull:!1},(()=>{const{isEndDate:e,toDate:t,fromDate:a,originalEndDate:i,originalStartDate:s}=this.state;if(e&&t&&a){const e=_()().startOf("day"),n=_()(t).startOf("day"),o=_()(a).startOf("day"),r=i?_()(i).startOf("day"):null;s&&_()(s).startOf("day");r?e.isSameOrBefore(o)?this.changeState("duration",_()(n).diff(o,"days")):(e.isBefore(n)&&n.isSameOrBefore(r)||e.isSameOrBefore(r)&&n.isSameOrAfter(r)||e.isSameOrAfter(r)&&e.isBefore(n))&&this.changeState("duration",_()(n).diff(e,"days")):e.isSameOrBefore(o)?this.changeState("duration",_()(n).diff(o,"days")):this.changeState("duration",_()(n).diff(e,"days"))}}))},this.handleFromDateChange=e=>{(this.state.toDate||this.isDuplicateAd)&&this.state.fromDate&&e?this.setState({fromDate:e,minDate:new Date((new Date).setDate(e.getDate()+2)),isStartDateNull:!1},(()=>{const{toDate:t,fromDate:a}=this.state;if(t&&a){let i=_()(t).startOf("day");const s=_()(a).startOf("day");_()(i).diff(_()(s),"days")<2&&(i=_()(e).add(2,"days").toDate(),this.setState({toDate:i})),this.changeState("duration",_()(i).diff(_()(s),"days"))}})):e||this.setState({isStartDateNull:!0})},this.buildIceBreakersPayload=()=>{const e=[],t=this.state.iceBreakers.filter((e=>{let{iceBreakerText:t}=e;return!!t})).map((t=>{let{iceBreakerText:a,flowId:i,iceBreakerId:s,blockId:n,blockHandle:o}=t;return e.push({iceBreaker:a,flowId:i.toString(),iceBreakerId:s,blockId:n,blockHandle:o}),{title:a}}));return{status:!0,iceBreakerNodeId:this.state.iceBreakerNodeId,rawMetaIceBreakers:{text:this.state.greetingMessage,ice_breakers:t},iceBreakerFlowMapping:e}},this.resolveAdAccountId=()=>{const e=this.props.assistantDetails||{};return e.selectedMetaAdAccountId||(this.props.adSetupDetails||{}).selectedMetaAdAccountId||(e.adSetupDetails||{}).selectedMetaAdAccountId||""},this.resolveMetaPageId=()=>{const e=this.props.assistantDetails||{};return e.selectedMetaPageId||(this.props.adSetupDetails||{}).selectedMetaPageId||(e.adSetupDetails||{}).selectedMetaPageId||""},this.fetchMetaPage=()=>{const{fbConnected:e,selectedMetaPageId:t,assistantId:a}=this.props.assistantDetails;t&&e&&i.Z.post("".concat(W.URL,"/meta-ads/fetch-page"),{assistantId:a,pageId:t}).then((e=>{this.props.updatePageDetails(e.data)})).catch((e=>console.log("error:",e)))},this.debounce=(e,t)=>{let a;return function(){for(var i=arguments.length,s=new Array(i),n=0;n<i;n++)s[n]=arguments[n];clearTimeout(a),a=setTimeout((()=>e(...s)),t)}},this.changeState=(e,t)=>
2{if("adType"===e){var a;const e=null===(a=this.state.adType)||void 0===a?void 0:a.value,i=null===t||void 0===t?void 0:t.value;"whatsapp_status"===i&&"whatsapp_status"!==e?this.setState({preLockPlatforms:this.state.selectedPlatforms,preLockPlacements:this.state.adPlacements,selectedPlatforms:["instagram","whatsapp"],adPlacements:{instagramPositions:["story"],whatsappPositions:["status"]}}):"whatsapp_status"===e&&"whatsapp_status"!==i&&this.setState({selectedPlatforms:this.state.preLockPlatforms||["facebook","instagram"],adPlacements:this.state.preLockPlacements||{facebookPositions:[],instagramPositions:[]},preLockPlatforms:null,preLockPlacements:null}),Dt(i)||"carousel"!==this.state.adFormat||this.setState({adFormat:"single",cards:[],carouselOptions:{multiShareOptimized:!0,multiShareEndCard:!1}})}"iceBreakers"===e&&(this.debouncedUpdateIceBreakers({iceBreakerNodeId:this.state.iceBreakerNodeId,iceBreakers:t}),this.debouncedRecreateAllIceBreakers(t,this.state.iceBreakerNodeId,this.state.prevIceBreakerNodeId,this.getAdDataPayload())),"switchChecked"===e&&!0===t?this.setState({activeStep:3}):"switchChecked"===e&&!1===t&&this.setState({activeStep:-1});const{ToAge:i}=this.state;"FromAge"===e&&t>i&&this.setState({ToAge:""}),this.setState({[e]:t},(()=>{["geoLocations","excludedGeoLocations","advanceTargets","advantageAudience","customAndLookalikeAudiences","excludedCustomAndLookalikeAudiences"].includes(e)&&this.debouncedGetEstimatedDeliveryUsers()})),"selectedPlatforms"==e&&this.setState({selectedPlatforms:t}),"adPlacements"==e&&this.setState({adPlacements:t}),"customAndLookalikeAudiences"==e&&this.setState({customAndLookalikeAudiences:t}),"excludedCustomAndLookalikeAudiences"==e&&this.setState({excludedCustomAndLookalikeAudiences:t});try{this.setState({[e]:t})}catch(s){console.log({error:s})}},this.handleGenerationStateChange=e=>{this.setState({isGenerating:e.isGenerating,isImageGenerating:e.isImageGenerating,isVideoGenerating:e.isVideoGenerating})},this.changeZLink=e=>{this.setState({zLink:e})},this.changeZage=(e,t)=>{"FromAge"===e&&this.state.ToAge<t?this.setState({[e]:t,ToAge:t}):this.setState({[e]:t})},this.changeZdetails=e=>{this.setState({zdetails:e})},this.changeZname=e=>{this.setState({Name:e})},this.updateFlows=async()=>{const e=this.state.iceBreakers.filter((e=>e.flowId)).map((e=>e.flowId)),t=[...new Set(e)];for(let n of t){var a;const e=this.props.flows.find((e=>e._id===n)),t=this.state.iceBreakers.filter((e=>e.flowId===n));let s=e.flow.nodes.find((e=>e.id==="".concat(this.state.iceBreakerNodeId,"-").concat(n))),o=[...e.flow.nodes],r=[...e.flow.edges];const l="iceBreaker";s||(s={id:"".concat(this.state.iceBreakerNodeId,"-").concat(n),type:"masterComponent",data:{isDrag:!0,id:this.state.iceBreakerNodeId,content:[{id:"".concat(Date.now(),"-").concat(l),type:"".concat(l),data:{iceBreakersCount:0,iceBreakers:[]}}]},position:{x:o[0].position.x+300,y:o[0].position.y}},o.push(s)),o=o.filter(((e,t,a)=>t===a.findIndex((t=>t.id===e.id))));const d=[];for(let a of t||[]){const e=s.data.content[0].data.iceBreakers.find((e=>e.id.split("-").reverse()[0]===a.id));e?d.push({...e,iceBreakerText:a.iceBreakerText}):d.push({iceBreakerText:a.iceBreakerText,id:"icebreaker_message-right-".concat(this.state.iceBreakerNodeId,"-").concat(a.iceBreakerId)})}if(s.data.content[0].data.iceBreakers=d,s.data.content[0].data.iceBreakersCount=(null===t||void 0===t?void 0:t.length)||0,this.isDuplicateAd||this.state.prevIceBreakerNodeId&&this.state.prevIceBreakerNodeId!==this.state.iceBreakerNodeId){for(let t of e.flow.edges)if(t.source==="".concat(this.state.prevIceBreakerNodeId,"-").concat(n)){const e="".concat(this.state.iceBreakerNodeId,"-").concat(n),a=t.sourceHandle.split("-").reverse()[0],i={...t,source:e,sourceHandle:"icebreaker_message-right-".concat(this.state.iceBreakerNodeId,"-").concat(a)};r.push(i)}r=r.filter(((e,t,a)=>t===a.findIndex((t=>t.sourceHandle===e.sourceHandle))))}for(let a of o){const{highlight:e,...t}=a.data;a.data={...t}}const c=null===(a=this.props.assistantDetails)||void 0===a?void 0:a.assistantId,p=(o||[]).some((e=>{var t,a,i,s;const n=null===e||void 0===e||null===(t=e.data)||void 0===t||null===(a=t.content)||void 0===a||null===(i=a[0])||void 0===i||null===(s=i.data)||void 0===s?void 0:s.aiKeywords;return Array.isArray(n)&&n.length>0}));await i.Z.post("".concat(W.URL,"/meta-catalogue/update-flow"),{assistantId:c,flowId:n,flowObject:{...e,flow:{nodes:o,edges:r},flowMessages:this.createFlowMessages(o,r,n),hasAiKeyword:p}}).then((()=>{console.log("Success")})).catch((e=>{console.log("Error while updating flow",e)}))}for(let n of this.state.initialIceBreakerFlowIds){var s;if(t.includes(n))continue;const e=this.props.flows.find((e=>e._id===n));let a=[...e.flow.nodes],o=[...e.flow.edges];const r=null===(s=this.props.assistantDetails)||void 0===s?void 0:s.assistantId,l=(a||[]).some((e=>{var t,a,i,s;const n=null===e||void 0===e||null===(t=e.data)||void 0===t||null===(a=t.content)||void 0===a||null===(i=a[0])||void 0===i||null===(s=i.data)||void 0===s?void 0:s.aiKeywords;return Array.isArray(n)&&n.length>0}));await i.Z.post("".concat(W.URL,"/meta-catalogue/update-flow"),{assistantId:r,flowId:n,flowObject:{...e,flow:{nodes:a,edges:o},flowMessages:this.createFlowMessages(a,o,n),hasAiKeyword:l}}).then((()=>{console.log("Success")})).catch((e=>{console.log("Error while updating flow",e)}))}},this.updateFlowsNew=async e=>{const t=this.state.iceBreakers.filter((e=>e.flowId)).map((e=>e.flowId)),a=[...new Set(t)];for(let c of a){var s,n,o,r,l;const t=this.props.flows.find((e=>e._id===c)),a=this.state.iceBreakers.filter((e=>e.flowId===c)),d=null===(s=this.props.flows.find((e=>e._id===c)))||void 0===s||null===(n=s.flow)||void 0===n?void 0:n.nodes,p=null===(o=this.props.flows.find((e=>e._id===c)))||void 0===o||null===(r=o.flow)||void 0===r?void 0:r.edges,u=d.find((e=>"keyword"===e.id));u.data.ads||(u.data.ads=[]);let h=[...d],m=[...p];const g=u.data.ads.filter((e=>{var t;return!(null!==(t=e.iceBreakers)&&void 0!==t&&t.iceBreakerNodeId)})),x=u.data.ads.filter((e=>{var t;return null===(t=e.iceBreakers)||void 0===t?void 0:t.iceBreakerNodeId}));let v=x.findIndex((e=>{var t;return(null===(t=e.iceBreakers)||void 0===t?void 0:t.iceBreakerNodeId)===this.state.iceBreakerNodeId}));const y=this.getAdDataPayload();y._id=e._id,y.adId=e.adId||e._id,-1===v?x.push(y):x[v]=y;const f=[...[y,...x].filter(((e,t,a)=>t===a.findIndex((t=>t.iceBreakers.iceBreakerNodeId===e.iceBreakers.iceBreakerNodeId)))),...g];if(u.data.ads=f,h=[u,...h],h=h.filter(((e,t,a)=>t===a.findIndex((t=>t.id===e.id)))),this.isDuplicateAd||this.state.prevIceBreakerNodeId&&this.state.prevIceBreakerNodeId!==this.state.iceBreakerNodeId){for(let e of t.flow.edges)if("keyword"===e.source){const t="keyword",a=e.sourceHandle.split("-").reverse()[0],i={...e,source:t,sourceHandle:"icebreaker_message-right-".concat(this.state.iceBreakerNodeId,"-").concat(a)};m.push(i)}m=m.filter(((e,t,a)=>t===a.findIndex((t=>t.sourceHandle===e.sourceHandle))))}const A=a.map((e=>e.iceBreakerId));m=m.filter((e=>{if(e.sourceHandle.startsWith("icebreaker_message-right-".concat(this.state.iceBreakerNodeId))){const t=e.sourceHandle.split("-").reverse()[0];if(!A.includes(t))return!1}return!0}));const b=null===(l=this.props.assistantDetails)||void 0===l?void 0:l.assistantId,S=(h||[]).some((e=>{var t,a,i,s;const n=null===e||void 0===e||null===(t=e.data)||void 0===t||null===(a=t.content)||void 0===a||null===(i=a[0])||void 0===i||null===(s=i.data)||void 0===s?void 0:s.aiKeywords;return Array.isArray(n)&&n.length>0}));await i.Z.post("".concat(W.URL,"/meta-catalogue/update-flow"),{assistantId:b,flowId:c,flowObject:{...t,flow:{nodes:h,edges:m},flowMessages:this.createFlowMessages(h,m,c),hasAiKeyword:S}}).then((()=>{console.log("Success")})).catch((e=>{console.log("Error while updating flow",e)}))}for(let c of this.state.initialIceBreakerFlowIds){var d;if(a.includes(c))continue;const e=this.props.flows.find((e=>e._id===c));let t=[...e.flow.nodes],s=[...e.flow.edges];const n=null===(d=this.props.assistantDetails)||void 0===d?void 0:d.assistantId,o=(t||[]).some((e=>{var t,a,i,s;const n=null===e||void 0===e||null===(t=e.data)||void 0===t||null===(a=t.content)||void 0===a||null===(i=a[0])||void 0===i||null===(s=i.data)||void 0===s?void 0:s.aiKeywords;return Array.isArray(n)&&n.length>0}));await i.Z.post("".concat(W.URL,"/meta-catalogue/update-flow"),{assistantId:n,flowId:c,flowObject:{...e,flow:{nodes:t,edges:s},flowMessages:this.createFlowMessages(t,s,c),hasAiKeyword:o}}).then((()=>{console.log("Success")})).catch((e=>{console.log("Error while updating flow",e)}))}},this.isAnyButtonElementEmpty=e=>{if(!e.length)return!0;const t=e;for(let a=0;a<t.length;a++)if(!t[a].text)return!0;return!1},this.replaceValues=(e,t)=>{for(let a=0;a<t.length;a++)e=e.replace("{{".concat(a+1,"}}"),t[a]);return e},this.isAnyElementEmpty=e=>{if(!e.length)return!0;const t=e;for(let a=0;a<t.length;a++){if(!t[a].items.length)return!0;for(let e=0;e<t[a].items.length;e++)if(!t[a].items[e].title)return!0}return!1},this.createFlowMessages=(e,t,a)=>{let i=[],s=!1;const{Easyinsightskey:n,isOrderFlowEnabled:o,assistantId:r,flowConfiguration:l}=this.props.assistantDetails;return e.forEach((e=>{let d={messageId:e.id};var c,p,u,h,m,g,x,v,y,f,A,b;if("keywordBox"===e.type)d={...d,keywords:null===(c=e.data.keywords)||void 0===c?void 0:c.map((e=>(e||"").toUpperCase().trim())),templates:null===e||void 0===e||null===(p=e.data)||void 0===p||null===(u=p.templates)||void 0===u?void 0:u.map((e=>{var a,i,s,n,o,r,l,d;return{id:e._id,name:e.name,quickReplies:null!==e&&void 0!==e&&null!==(a=e.carouselCards)&&void 0!==a&&a.length?null===e||void 0===e||null===(i=e.carouselCards)||void 0===i||null===(s=i[0])||void 0===s||null===(n=s.components)||void 0===n?void 0:n.find((e=>"BUTTONS"===e.type)).buttons.map((a=>{var i;return{label:a.text,triggerMessageId:null===(i=t.find((t=>t.sourceHandle.includes(":--:")?t.sourceHandle===a.text.trimEnd().split(" ").join("_")+":--:".concat(e._id):t.sourceHandle===a.text.trimEnd().split(" ").join("_"))))||void 0===i?void 0:i.target}})):null!==e&&void 0!==e&&null!==(o=e.buttons)&&void 0!==o&&o.length?null===e||void 0===e||null===(r=e.buttons)||void 0===r?void 0:r.map((a=>{var i;return{label:a.text,triggerMessageId:null===(i=t.find((t=>t.sourceHandle.includes(":--:")?t.sourceHandle===a.text.trimEnd().split(" ").join("_")+":--:".concat(e._id):t.sourceHandle===a.text.trimEnd().split(" ").join("_"))))||void 0===i?void 0:i.target}})):null!==e&&void 0!==e&&null!==(l=e.quickReplies)&&void 0!==l&&l.length?null===e||void 0===e||null===(d=e.quickReplies)||void 0===d?void 0:d.map((a=>{var i;return{label:a,triggerMessageId:null===(i=t.find((t=>t.sourceHandle.includes(":--:")?t.sourceHandle===a.trimEnd().split(" ").join("_")+":--:".concat(e._id):t.sourceHandle===a.trimEnd().split(" ").join("_"))))||void 0===i?void 0:i.target}})):[]}})),qrCampaigns:null===e||void 0===e||null===(h=e.data)||void 0===h||null===(m=h.qrCampaigns)||void 0===m?void 0:m.map((e=>({id:e._id,name:e.name,payload:e.payload,activeCustomMessage:null===e||void 0===e?void 0:e.activeCustomMessage}
2))),ad:e.data.ad?{adId:e.data.ad.adId,triggerMessageId:null===(g=t.find((e=>"ad-right-0"===e.sourceHandle)))||void 0===g?void 0:g.target}:null,ads:e.data.ads?e.data.ads.map((e=>{var a,i,s;return{adId:e.adId,triggerMessageId:null===(a=t.find((t=>t.sourceHandle==="ad-right-".concat(e.adId))))||void 0===a?void 0:a.target,iceBreakers:null===(i=e.iceBreakers)||void 0===i||null===(s=i.iceBreakerFlowMapping)||void 0===s?void 0:s.map((a=>{var i;const s=null===(i=t.find((t=>{var i;const s=t.sourceHandle.split("-").reverse()[0],n=t.sourceHandle.split("-").reverse()[1]||"",o=a.iceBreakerId,r=null===(i=e.iceBreakers)||void 0===i?void 0:i.iceBreakerNodeId;return s===o&&r===n&&s&&n&&o&&r})))||void 0===i?void 0:i.target;return{...a,triggerMessageId:s}}))}})):null,iceBreakers:(null===e||void 0===e||null===(x=e.data)||void 0===x||null===(v=x.iceBreakers)||void 0===v?void 0:v.map((e=>{var a;const i=null===(a=t.find((t=>{const a=t.sourceHandle.split("-").reverse()[0],i=t.sourceHandle.split("-").reverse()[1]||"",s=e.id.split("-").reverse()[0],n=e.id.split("-").reverse()[1]||"";return a===s&&n===i&&a&&i&&s&&n})))||void 0===a?void 0:a.target;return{...e,triggerMessageId:i}})))||[],regex:e.data.regex,regexCaseSensitive:!!e.data.regexCaseSensitive,triggerMessageId:null===(y=t.find((e=>"keyword-right-keyword"===e.sourceHandle)))||void 0===y?void 0:y.target,orderTriggerMessageId:null===(f=t.find((e=>"keyword-order-right-keyword"===e.sourceHandle)))||void 0===f?void 0:f.target,isOrderEnabled:!(!o||!(null!==(A=t.find((e=>"keyword-order-right-keyword"===e.sourceHandle)))&&void 0!==A&&A.target||null!==e&&void 0!==e&&null!==(b=e.data)&&void 0!==b&&b.isOrderEnable))};else if("masterComponent"===e.type){var S;let i=[];e.data.content.forEach((o=>{var d,c,p;let u={};if("message"===o.type){if(u={type:o.data.buttons.length?"INTERACTIVE":"text"},!o.data.text)return void(s=!0);if("text"===u.type)u={...u,type:"TEXT",text:o.data.text};else{var h,m,g;if(this.isAnyButtonElementEmpty(null===o||void 0===o||null===(h=o.data)||void 0===h?void 0:h.buttons))return void(s=!0);u={...u,interactive:{type:"button",body:{text:o.data.text},action:{buttons:null===o||void 0===o||null===(m=o.data)||void 0===m||null===(g=m.buttons)||void 0===g?void 0:g.map((i=>{var s;return{type:"reply",reply:{id:"message_with_button-".concat(e.id,"-").concat(i.id,"-|").concat(a),title:i.text},triggerMessageId:null===(s=t.find((t=>t.sourceHandle==="message_with_button-right-".concat(e.id,"-").concat(i.id))))||void 0===s?void 0:s.target}}))}}}}}else if("questionMessage"===o.type){var x,v;if(u={type:"QUESTION"},!o.data.text)return void(s=!0);u={...u,skipable:o.data.skipable,text:o.data.text,attribute:o.data.attribute,triggerMessageId:null===(x=t.find((t=>t.sourceHandle==="question-right-".concat(e.id))))||void 0===x?void 0:x.target,errorTriggerMessageId:null===(v=t.find((t=>t.sourceHandle==="question-error-right-".concat(e.id))))||void 0===v?void 0:v.target,attributeNumberOfAttempt:o.data.attributeNumberOfAttempt||"1",attributeFormatValue:o.data.attributeFormatValue||{},attributeFormatValidationErrorMessage:o.data.attributeFormatValidationErrorMessage,attributeFormat:o.data.attributeFormat||"Any",mediaType:o.data.mediaType||""}}else if("questionMediaMessage"===o.type){var y,f;if(u={type:"QUESTION"},!o.data.text)return void(s=!0);u={...u,text:o.data.text,attribute:o.data.attribute,skipable:o.data.skipable,triggerMessageId:null===(y=t.find((t=>t.sourceHandle==="question-media-right-".concat(e.id))))||void 0===y?void 0:y.target,errorTriggerMessageId:null===(f=t.find((t=>t.sourceHandle==="question-error-right-".concat(e.id))))||void 0===f?void 0:f.target,attributeNumberOfAttempt:o.data.attributeNumberOfAttempt||"1",attributeFormatValidationErrorMessage:o.data.attributeFormatValidationErrorMessage,attributeFormat:"Media",mediaType:o.data.mediaType||"Any"}}else if("whatsappPay"===o.type){var A;u={type:"WHATSAPPPAY"},u={...u,amount:o.data.amount,title:o.data.title,currency:"Dollar"===o.data.currency?"USD":"INR",paymentMode:o.data.paymentMode,productName:o.data.productName,productQuantity:o.data.productQuantity,templateName:o.data.templateName,isCustomProduct:o.data.isCustomProduct,notes:o.data.notes,triggerMessageId:null===(A=t.find((t=>t.sourceHandle==="whatsapp-pay-right-".concat(e.id))))||void 0===A?void 0:A.target}}else if("ConversionApi"===o.type){var b,S,I,j,C,w;if(u={type:"ConversionApi"},"Lead"!==(null===o||void 0===o||null===(b=o.data)||void 0===b?void 0:b.conversionType)&&("Purchase"!==(null===o||void 0===o||null===(S=o.data)||void 0===S?void 0:S.conversionType)||null===o||void 0===o||null===(I=o.data)||void 0===I||!I.currencyCode||isNaN(Number(null===o||void 0===o||null===(j=o.data)||void 0===j?void 0:j.value))||0===Number(null===o||void 0===o||null===(C=o.data)||void 0===C?void 0:C.value)))return void(s=!0);u={...u,value:o.data.value,conversionType:o.data.conversionType,currencyCode:o.data.currencyCode||"INR",triggerMessageId:null===(w=t.find((t=>t.sourceHandle==="set-conversion-right-".concat(e.id))))||void 0===w?void 0:w.target}}else if("setAVariable"===o.type){var k;if(u={type:"SETAVARIABLE"},!o.data.value)return void(s=!0);u={...u,value:o.data.value,attribute:o.data.attribute,triggerMessageId:null===(k=t.find((t=>t.sourceHandle==="set-a-varibale-right-".concat(e.id))))||void 0===k?void 0:k.target}}else if("condition"===o.type){var Z,T;if(u={type:"CONDITION"},!o.data.condition&&!o.data.attributeOne)return void(s=!0);u={...u,conditionKey:o.data.conditionKey,attributeOne:"$"+o.data.attributeOne,attributeTwo:o.data.attributeTwo,rangeObject:o.data.rangeObject,trueTriggerMessageId:null===(Z=t.find((t=>t.sourceHandle==="condition-right-true-".concat(e.id))))||void 0===Z?void 0:Z.target,falseTriggerMessageId:null===(T=t.find((t=>t.sourceHandle==="condition-right-false-".concat(e.id))))||void 0===T?void 0:T.target}}else if("questionAddressMessage"===o.type){var D;if(u={type:"QUESTIONADDRESS"},!o.data.text)return void(s=!0);u={...u,text:o.data.text,attribute:o.data.attribute,formattedAttribute:o.data.formattedAttribute,triggerMessageId:null===(D=t.find((t=>t.sourceHandle==="question-address-message-right-".concat(e.id))))||void 0===D?void 0:D.target}}else if("questionLocationMessage"===o.type){var P;if(u={type:"QUESTIONLOCATION"},!o.data.text)return void(s=!0);u={...u,text:o.data.text,longitudeAttribute:o.data.longitudeAttribute,latitudeAttribute:o.data.latitudeAttribute,triggerMessageId:null===(P=t.find((t=>t.sourceHandle==="question-location-message-right-".concat(e.id))))||void 0===P?void 0:P.target}}else if("addTag"===o.type){var B,E;if(u={type:"ADDTAG"},!((null===o||void 0===o||null===(B=o.data)||void 0===B?void 0:B.tags)||[]).length)return void(s=!0);u={...u,tags:o.data.tags,triggerMessageId:null===(E=t.find((t=>t.sourceHandle==="add-tag-right-".concat(e.id))))||void 0===E?void 0:E.target}}else if("setupWebhook"===o.type){var N,L,F,M;if(u={type:"SETUPWEBHOOK"},!o.data.requestObject)return void(s=!0);u={...u,requestObject:o.data.requestObject,attribute:o.data.attribute||"",responseKey:(null===o||void 0===o||null===(N=o.data)||void 0===N?void 0:N.responseKey)||"",statusCodes:((null===o||void 0===o||null===(L=o.data)||void 0===L?void 0:L.statusCodes)||[]).map((e=>{var a;return{code:e.code,triggerMessageId:null===(a=t.find((t=>t.sourceHandle==="".concat(e.handleId))))||void 0===a?void 0:a.target}})),triggerMessageId:null===(F=t.find((t=>t.sourceHandle==="setup-webhoook-right-".concat(e.id))))||void 0===F?void 0:F.target,capturingAttributes:null===o||void 0===o||null===(M=o.data)||void 0===M?void 0:M.capturingAttributes}}else if("easyinsights"===o.type){var R;if(u={type:"EASYINSIGHTS"},!o.data.eventType)return void(s=!0);
2if("Status Change"===o.data.eventType&&!o.data.conversionName)return void(s=!0);if("Transaction"===o.data.eventType&&(!o.data.revenue||!o.data.currency||!o.data.discount||!o.data.offerCode))return void(s=!0);u={...u,key:n,eventType:o.data.eventType,conversionName:o.data.conversionName,revenue:o.data.revenue,currency:o.data.currency,discount:o.data.discount,offerCode:o.data.offerCode,triggerMessageId:null===(R=t.find((t=>t.sourceHandle==="easyinsights-right-".concat(e.id))))||void 0===R?void 0:R.target}}else if("imageWithCaption"===o.type){var O,U,z,_,H;if(!o.data.url||!o.data.fileType)return void(s=!0);if(((null===o||void 0===o||null===(O=o.data)||void 0===O?void 0:O.buttons)||[]).length>0)u={type:"INTERACTIVE",interactive:{type:"button",header:{type:"file"===o.data.fileType.toLowerCase()?"document":o.data.fileType.toLowerCase(),["file"===o.data.fileType.toLowerCase()?"document":o.data.fileType.toLowerCase()]:{link:o.data.url,..."FILE"==o.data.fileType?{filename:null===(U=o.data)||void 0===U?void 0:U.fileName}:{}}},body:{text:o.data.text||"."},action:{buttons:null===o||void 0===o||null===(z=o.data)||void 0===z||null===(_=z.buttons)||void 0===_?void 0:_.map((i=>{var s;return{type:"reply",reply:{id:"message_with_button-".concat(e.id,"-").concat(i.id,"-|").concat(a),title:i.text},triggerMessageId:null===(s=t.find((t=>t.sourceHandle==="message_with_button-right-".concat(e.id,"-").concat(i.id))))||void 0===s?void 0:s.target}}))}}};else if(u={type:o.data.fileType,url:o.data.url,caption:o.data.text,size:o.data.fileSize},"FILE"==o.data.fileType)u={...u,filename:null===(H=o.data)||void 0===H?void 0:H.fileName}}else if("templateMessage"===o.type)u={type:"TEMPLATE",template:{...o.data,templateType:o.data.type,name:o.data.name,templateLanguage:o.data.templateLanguage,namespace:o.data.namespace,parameters:o.data.parameters,format:o.data.format,templateParams:o.data.parameters?o.data.templateParams.slice(0,o.data.parameters):[],isTemplate:!0,url:o.data.url,filename:o.data.filename,..."TEXT"===o.data.type?{text:this.replaceValues(o.data.format,o.data.templateParams)}:{caption:this.replaceValues(o.data.format,o.data.templateParams)}}};else if("listMessage"===o.type){var G,V,Q,q,Y;if(!o.data.body||null===o||void 0===o||null===(G=o.data)||void 0===G||null===(V=G.sections)||void 0===V||!V.length||this.isAnyElementEmpty(null===o||void 0===o||null===(Q=o.data)||void 0===Q?void 0:Q.sections))return void(s=!0);u={type:"INTERACTIVE",interactive:{type:"list",...o.data.header?{header:{type:"text",text:o.data.header}}:{},body:{text:o.data.body},...o.data.footer?{footer:{text:o.data.footer}}:{},action:{button:o.data.buttonTitle,sections:null===o||void 0===o||null===(q=o.data)||void 0===q||null===(Y=q.sections)||void 0===Y?void 0:Y.map((e=>{var i;return{id:e.id,title:e.title,rows:null===e||void 0===e||null===(i=e.items)||void 0===i?void 0:i.map((e=>{var i;return{id:e.id+"-|".concat(a),title:e.title,description:e.description,triggerMessageId:null===(i=t.find((t=>t.sourceHandle===e.id)))||void 0===i?void 0:i.target}}))}}))}}}}else if("whatsappForms"===o.type){var K,J,X,$,ee,te;if(!o.data.body||null===o||void 0===o||null===(K=o.data)||void 0===K||!K.flowId||null===o||void 0===o||null===(J=o.data)||void 0===J||!J.flowStatus||null===o||void 0===o||null===(X=o.data)||void 0===X||!X.screenName||null===o||void 0===o||null===($=o.data)||void 0===$||!$.buttonTitle)return void(s=!0);u={triggerMessageId:null===(ee=t.find((t=>t.sourceHandle==="whatsapp-forms-".concat(e.id))))||void 0===ee?void 0:ee.target,attributeFormatValidationErrorMessage:o.data.attributeFormatValidationErrorMessage,type:"INTERACTIVE",interactive:{type:"flow",...o.data.header?{header:{type:"text",text:o.data.header}}:{},body:{text:o.data.body},...o.data.footer?{footer:{text:o.data.footer}}:{},action:{name:"flow",parameters:{flow_message_version:"3",flow_action:(null===o||void 0===o||null===(te=o.data)||void 0===te?void 0:te.flowAction)||"navigate",flow_token:o.data.flowToken||"<FLOW_TOKEN>",flow_id:o.data.flowId,flow_cta:o.data.buttonTitle,mode:o.data.flowStatus.toLowerCase(),..."data_exchange"!=o.data.flowAction?{flow_action_payload:{screen:o.data.screenName,data:o.data.attributeName||""}}:{}}}}}}else if("catalogueMessage"===o.type){var ae;if(null===o||void 0===o||null===(ae=o.data)||void 0===ae||!ae.body)return void(s=!0);u={type:"INTERACTIVE",interactive:{type:"catalog_message",body:{text:o.data.body},...o.data.footer?{footer:{text:o.data.footer}}:{},action:{name:"catalog_message"}}}}else if("singleProductMessage"===o.type){var ie,se;if(null===o||void 0===o||null===(ie=o.data)||void 0===ie||null===(se=ie.product)||void 0===se||!se.catalogueId)return void(s=!0);u={type:"INTERACTIVE",interactive:{type:"product",...o.data.body?{body:{text:o.data.body}}:{},...o.data.footer?{footer:{text:o.data.footer}}:{},action:{catalog_id:o.data.product.catalogueId,product_retailer_id:o.data.product.retailerId}}}}else if("multiProductMessage"===o.type){var ne,oe,re,le,de,ce,pe,ue,he,me,ge;if(null===o||void 0===o||null===(ne=o.data)||void 0===ne||!ne.header||null===o||void 0===o||null===(oe=o.data)||void 0===oe||!oe.body||null===o||void 0===o||null===(re=o.data)||void 0===re||null===(le=re.sections)||void 0===le||!le.length||null===o||void 0===o||null===(de=o.data)||void 0===de||null===(ce=de.sections[0])||void 0===ce||null===(pe=ce.products)||void 0===pe||!pe.length)return void(s=!0);u={type:"INTERACTIVE",interactive:{type:"product_list",...o.data.header?{header:{type:"text",text:o.data.header}}:{},body:{text:o.data.body},...o.data.footer?{footer:{text:o.data.footer}}:{},action:{catalog_id:null===o||void 0===o||null===(ue=o.data)||void 0===ue||null===(he=ue.sections[0])||void 0===he?void 0:he.products[0].catalogueId,sections:null===o||void 0===o||null===(me=o.data)||void 0===me||null===(ge=me.sections)||void 0===ge?void 0:ge.map((e=>{var t;return{id:e.id,title:e.title,product_items:null===e||void 0===e||null===(t=e.products)||void 0===t?void 0:t.map((e=>({product_retailer_id:e.retailerId})))}}))}}}}else if("humanIntervention"===o.type)u={...u,type:"HUMANINTERVENTION",isRequesting:!0};else if("connectFlows"===o.type)u={...u,flowId:o.data.flowId,flowName:o.data.flowName,type:"CONNECTFLOWS"};else if("iceBreaker"===o.type){var xe;u={type:"ICEBREAKERS",iceBreakers:null===(xe=o.data.iceBreakers)||void 0===xe?void 0:xe.map((e=>{var a;const i=null===(a=t.find((t=>{const a=t.sourceHandle.split("-").reverse()[0],i=t.sourceHandle.split("-").reverse()[1]||"",s=e.id.split("-").reverse()[0],n=e.id.split("-").reverse()[1]||"";return a===s&&n===i&&a&&i&&s&&n})))||void 0===a?void 0:a.target;return{...e,triggerMessageId:i}}))}}var ve,ye;(u={...u,delay:null===(d=o.data)||void 0===d?void 0:d.delay},null!==o&&void 0!==o&&null!==(c=o.data)&&void 0!==c&&c.timeoutToggle&&(null!==l&&void 0!==l&&l.t
2imeoutEnabled||W.TIMEOUT_FEATURED_ASSISTANTIDS.includes(r)||null!==(p=this.props.assistantDetails)&&void 0!==p&&p.flowsProFeatureEnabled))&&(u={...u,time:+(null===o||void 0===o||null===(ve=o.data)||void 0===ve?void 0:ve.time),timeoutMessageTriggerId:null===(ye=t.find((t=>t.sourceHandle==="component-right-timeout-".concat(e.id))))||void 0===ye?void 0:ye.target});i.push(u)})),d={...d,content:i,defaultTriggerMessageId:null===(S=t.find((t=>t.sourceHandle==="master-component-right-".concat(e.id))))||void 0===S?void 0:S.target}}i.push(d)})),s?(this.setState({snack:!0,snackMessage:"Please fill all required fields ",snackStatus:"error"}),[]):i},this.createAd=()=>{var e,t,a,s,n;this.setState({isLoading:!0});const{adName:o,adCaption:r,adHeadline:l,imageFile:d,thumbnailUrl:c,videoFile:p,uploadType:u,geoLocations:h,excludedGeoLocations:m,gender:g,FromAge:x,ToAge:v,advanceTargets:y,dailyBudget:f,duration:A,selectedPlatforms:b,selectedAudience:S,isEndDate:I,leadFormId:j}=this.state;let{fromDate:C,toDate:w}=this.state;const k=_()();C=_()(C).set({hour:k.hour(),minute:k.minute(),second:k.second(),millisecond:k.millisecond()}).toDate(),w=_()(w).set({hour:k.hour(),minute:k.minute(),second:k.second(),millisecond:k.millisecond()}).add(5,"seconds").toDate();let{assistantId:Z,assistantName:T,partnerId:D,currency:P}=this.props.assistantDetails;const B=this.resolveAdAccountId(),E=this.resolveMetaPageId(),{adId:N}=this.props.match.params,L=(0,gi.cc)({adId:N,assistantId:Z,assistantName:T,adAccountId:B,metaPageId:E,adDescription:r,adName:o,budgetType:this.state.selectedBudget.value,dailyBudget:f,lifetimeBudget:this.state.lifetimeBudget,..."carousel"!==this.state.adFormat?{headline:l,headlineDescription:this.state.adHeadlineDescription}:{},gender:g,minAge:x,maxAge:v,geoLocation:h,excludedGeoLocation:m,adStartDate:C,adStopDate:w,isEndDate:I,duration:A,advanceTargets:y,selectedPlatforms:b,audienceId:(null===S||void 0===S?void 0:S._id)||"",duplicateAd:this.isDuplicateAd,isScheduledAd:this.state.isScheduledAd,adType:null===(e=this.state.adType)||void 0===e?void 0:e.value,adObjective:null===(t=this.state.adObjective)||void 0===t?void 0:t.value,optimizationGoal:null===(a=this.state.optimizationGoal)||void 0===a?void 0:a.value,conversionEvent:null===(s=this.state.conversionEvent)||void 0===s?void 0:s.value,ctaButton:this.state.ctaButton,websiteUrl:this.state.websiteUrl,pixelId:null===(n=this.state.pixel)||void 0===n?void 0:n.value,adPlacements:this.state.adPlacements,customAndLookalikeAudiences:this.state.customAndLookalikeAudiences,excludedCustomAndLookalikeAudiences:this.state.excludedCustomAndLookalikeAudiences,leadFormId:j,advantageAudience:this.state.advantageAudience,adSetSchedule:this.state.isScheduledAd?this.convertScheduleStrings(this.state.selectedCells):void 0,timezoneType:"viewer"===this.state.selectedTimezone.value?"USER":"ADVERTISER",iceBreakers:this.state.switchChecked?this.buildIceBreakersPayload():{status:!1},uploadType:u,imageUrl:"VIDEO_UPLOAD"===u?"string"===typeof c?c:null===c||void 0===c?void 0:c.publicUrl:null===d||void 0===d?void 0:d.publicUrl,videoUrl:null===p||void 0===p?void 0:p.publicUrl});if("carousel"===this.state.adFormat&&(L.adFormat="carousel",L.cards=this.state.cards,L.carouselOptions=this.state.carouselOptions,delete L.imageUrl,delete L.videoUrl),u){let e="create-meta-ad";i.Z.post("".concat(W.URL,"/meta-ads/")+e,L).then((e=>{var t,a,i;const{data:s}=e||{};this.state.switchChecked&&this.updateFlowsNew(s),setTimeout((()=>{this.props.history.push("/projects/".concat(Z,"/advertisement/").concat(null===s||void 0===s?void 0:s._id,"/personal-analytics/")),this.setState({isLoading:!1,snack:!this.state.snack,snackMessage:"Ad is created successfully",snackStatus:"success"})}),200),ui.Z.trackCustomEvent("ad_campaign_created",{budget:null===s||void 0===s?void 0:s.amountSpent,ad_campaign_id:null===s||void 0===s?void 0:s._id});const n=(null===d||void 0===d||null===(t=d.fileName)||void 0===t?void 0:t.includes("Generated"))||"Generated Image"===(null===d||void 0===d?void 0:d.fileName),o=(null===p||void 0===p||null===(a=p.fileName)||void 0===a?void 0:a.includes("Generated"))||"Generated Video"===(null===p||void 0===p?void 0:p.fileName);if(!yi&&!xi&&(n||o)&&Z){const e=o?"video":"image";ri.Z.track("ad_created_with_generated_media",{type:e,source:"generation",assistantId:Z})}const r=null===(i=this.props.adAccountInsights)||void 0===i?void 0:i.lastFetchParams;this.props.fetchAdAccountInsights({assistantId:Z,adAccountId:B,page:(null===r||void 0===r?void 0:r.page)||1,limit:(null===r||void 0===r?void 0:r.limit)||fe.FY,nameQuery:(null===r||void 0===r?void 0:r.nameQuery)||"",startDate:(null===r||void 0===r?void 0:r.startDate)||null,endD
2ate:(null===r||void 0===r?void 0:r.endDate)||null,selectedOption:(null===r||void 0===r?void 0:r.selectedOption)||null})})).catch((e=>{var t,a,i,s,n,o,r,l,d;console.log("error:",e),this.setState({isLoading:!1,snack:!0,snackMessage:(null===e||void 0===e||null===(t=e.response)||void 0===t||null===(a=t.data)||void 0===a?void 0:a.message)||(null===e||void 0===e||null===(i=e.response)||void 0===i||null===(s=i.data)||void 0===s||null===(n=s.errorMessage)||void 0===n?void 0:n.error_user_msg)||(null===e||void 0===e||null===(o=e.response)||void 0===o||null===(r=o.data)||void 0===r||null===(l=r.errorMessage)||void 0===l?void 0:l.message)||"Something went wrong",snackStatus:"error"});const{action:c,assistant:p}=(null===e||void 0===e||null===(d=e.response)||void 0===d?void 0:d.data)||{};if("reconnect"===c&&p){const{fbConnected:e,fbUserId:t,fbGrantedScopes:a,selectedMetaPageId:i,selectedMetaAdAccountId:s,freezedMetaAdAccountId:n,freezedMetaPageId:o}=p||{};this.props.updateAssistantStore({fbConnected:e,fbUserId:t,fbGrantedScopes:a,selectedMetaPageId:i,selectedMetaAdAccountId:s,freezedMetaAdAccountId:n,freezedMetaPageId:o}),setTimeout((()=>{this.props.history.replace("/projects/"+Z+"/advertisement")}),2e3)}else if("accept_discrimination_policy"===c){const{link:e}=p||{};this.setState({errorAction:{link:e,name:"Follow the document to accept Facebook Non-Discrimination Policy"}})}else if("add_payment_method"===c){const{link:e}=p||{};this.setState({errorAction:{link:e,name:"Click to add Payment in your Ad Account"}})}else if("accept_lead_gen_tos"===c){const{link:e}=p||{};this.setState({errorAction:{link:e||"https://www.facebook.com/legal/leadgen/tos",name:"Accept Facebook's Lead Generation Terms of Service"}})}else if("reconnect_meta_for_lead_ads"===c){var u,h,m;this.setState({errorAction:{link:"/projects/".concat(null===(u=this.props)||void 0===u||null===(h=u.match)||void 0===h||null===(m=h.params)||void 0===m?void 0:m.assistantId,"/advertisement"),name:"Reconnect Meta Account for Lead Ads (pages_manage_ads permission required)",isInternalLink:!0}
2})}}))}},this.getAdDataPayload=()=>{const{adName:e,adCaption:t,adHeadline:a,imageFile:i,thumbnailUrl:s,videoFile:n,uploadType:o,geoLocations:r,excludedGeoLocations:l,gender:d,FromAge:c,ToAge:p,advanceTargets:u,dailyBudget:h,duration:m,selectedPlatforms:g,selectedAudience:x,isEndDate:v}=this.state;let{fromDate:y,toDate:f}=this.state;const A=_()();y=_()(y).set({hour:A.hour(),minute:A.minute(),second:A.second(),millisecond:A.millisecond()}).toDate(),f=_()(f).set({hour:A.hour(),minute:A.minute(),second:A.second(),millisecond:A.millisecond()}).add(5,"seconds").toDate();let{assistantId:b,assistantName:S,partnerId:I,currency:j}=this.props.assistantDetails;const C=this.resolveAdAccountId(),w=this.resolveMetaPageId(),{adId:k}=this.props.match.params,Z={adId:k,assistantId:b,assistantName:S,adAccountId:C,metaPageId:w,adDescription:t,adName:e,dailyBudget:"daily_budget"===this.state.selectedBudget.value?h:0,lifetimeBudget:"lifetime_budget"===this.state.selectedBudget.value?this.state.lifetimeBudget:0,..."carousel"!==this.state.adFormat?{headline:a,headlineDescription:this.state.adHeadlineDescription}:{},gender:d,minAge:parseInt(c),maxAge:parseInt(p),geoLocation:r,excludedGeoLocation:l,adStopDate:v?f:"",adStartDate:y,duration:m,advanceTargets:u,selectedPlatforms:g,audienceId:(null===x||void 0===x?void 0:x._id)||"",duplicateAd:this.isDuplicateAd,pageDetails:this.props.pageDetails,iceBreakers:{status:!1},isScheduledAd:this.state.isScheduledAd,leadFormId:this.state.leadFormId||"",advantageAudience:this.state.advantageAudience?1:0};if(this.state.isScheduledAd){const e=this.convertScheduleStrings(this.state.selectedCells);Z.adSetSchedule=e,Z.timezoneType="viewer"===this.state.selectedTimezone.value?"USER":"ADVERTISER"}if(this.state.switchChecked){Z.iceBreakers.status=!0,Z.iceBreakers.iceBreakerNodeId=this.state.iceBreakerNodeId;const e=[],t=this.state.iceBreakers.filter((e=>{let{iceBreakerText:t}=e;return!!t})).map((t=>{let{iceBreakerText:a,flowId:i,iceBreakerId:s,blockId:n,blockHandle:o}=t;return e.push({iceBreaker:a,flowId:i.toString(),iceBreakerId:s,blockId:n,blockHandle:o}),{title:a}})),a={text:this.state.greetingMessage,ice_breakers:t};Z.iceBreakers.rawMetaIceBreakers=a,Z.iceBreakers.iceBreakerFlowMapping=e}return"carousel"===this.state.adFormat?(Z.adFormat="carousel",Z.cards=this.state.cards,Z.carouselOptions=this.state.carouselOptions):"VIDEO_UPLOAD"===o?(Z.videoUrl=null===n||void 0===n?void 0:n.publicUrl,Z.imageUrl="string"===typeof s?s:null===s||void 0===s?void 0:s.publicUrl):"IMAGE_UPLOAD"===o&&(Z.imageUrl=null===i||void 0===i?void 0:i.publicUrl),Z},this.handleSaveIceBreaker=async()=>{const e={iceBreakers:{status:!0,iceBreakerNodeId:this.state.iceBreakerNodeId}},t=[],a=this.state.iceBreakers.filter((e=>{let{iceBreakerText:t}=e;return!!t})).map((e=>{let{iceBreakerText:a,flowId:i,iceBreakerId:s,blockId:n,blockHandle:o}=e;return t.push({iceBreaker:a,flowId:i.toString(),iceBreakerId:s,blockId:n,blockHandle:o}),{title:a}})),s={text:this.state.greetingMessage,ice_breakers:a};e.iceBreakers.rawMetaIceBreakers=s,e.iceBreakers.iceBreakerFlowMapping=t;const{assistantId:n}=this.props.assistantDetails;try{this.setState({isIceBreakerSaving:!0});const{data:t}=await i.Z.post("".concat(W.URL,"/meta-ads/save-icebreakers"),{assistantId:n,name:this.state.iceBreakerName,iceBreakers:e.iceBreakers});this.setState((e=>({snack:!0,snackMessage:"Ice Breakers Saved Successfully",snackStatus:"success",showSaveIceBreakerModal:!1,isIceBreakerSaving:!1,currSelectedSavedIceBreaker:t,savedIceBreakers:[t,...e.savedIceBreakers]})))}catch(p){var o,r,l,d,c;console.log({error:p}),this.setState({snack:!0,snackMessage:(null===p||void 0===p||null===(o=p.response)||void 0===o||null===(r=o.data)||void 0===r?void 0:r.message)||(null===p||void 0===p||null===(l=p.response)||void 0===l||null===(d=l.data)||void 0===d||null===(c=d.errorMessage)||void 0===c?void 0:c.error_user_msg)||"Something went wrong",snackStatus:"error",isIceBreakerSaving:!1})}},this.handleUpdateIceBreaker=async e=>{const t={iceBreakers:{status:!0,iceBreakerNodeId:this.state.iceBreakerNodeId}},a=[],s=this.state.iceBreakers.filter((e=>{let{iceBreakerText:t}=e;return!!t})).map((e=>{let{iceBreakerText:t,flowId:i,iceBreakerId:s,blockId:n,blockHandle:o}=e;return a.push({iceBreaker:t,flowId:i.toString(),iceBreakerId:s,blockId:n,blockHandle:o}),{title:t}})),n={text:this.state.greetingMessage,ice_breakers:s};t.iceBreakers.rawMetaIceBreakers=n,t.iceBreakers.iceBreakerFlowMapping=a;const{assistantId:o}=this.props.assistantDetails;try{this.setState({isIceBreakerSaving:!0});const{data:a}=await i.Z.post("".concat(W.URL,"/meta-ads/update-icebreakers"),{_id:e,assistantId:o,name:this.state.iceBreakerName,iceBreakers:t.iceBreakers});this.setState({snack:!0,snackMessage:"Ice Breakers Updated Successfully",snackStatus:"success",showSaveIceBreakerModal:!1,isIceBreakerSaving:!1,currSelectedSavedIceBreaker:a})}catch(u){var r,l,d,c,p;console.log({error:u}),this.setState({snack:!0,snackMessage:(null===u||void 0===u||null===(r=u.response)||void 0===r||null===(l=r.data)||void 0===l?void 0:l.message)||(null===u||void 0===u||null===(d=u.response)||void 0===d||null===(c=d.data)||void 0===c||null===(p=c.errorMessage)||void 0===p?void 0:p.error_user_msg)||"Something went wrong",snackStatus:"error",isIceBreakerSaving:!1})}},this.hasCreativeChanges=()=>{var e,t,a;const{originalCreativeData:i}=this.state;if(!i)return!1;const s={adName:this.state.adName,adCaption:this.state.adCaption,adHeadline:this.state.adHeadline,adHeadlineDescription:this.state.adHeadlineDescription,uploadType:this.state.uploadType,videoUrl:null===(e=this.state.videoFile)||void 0===e?void 0:e.publicUrl,imageUrl:(null===(t=this.state.imageFile)||void 0===t?void 0:t.publicUrl)||(null===(a=this.state.thumbnailUrl)||void 0===a?void 0:a.publicUrl),greetingMessage:this.state.greetingMessage,iceBreakers:this.state.iceBreakers,switchChecked:this.state.switchChecked,adFormat:this.state.adFormat,cards:this.state.cards,carouselOptions:this.state.carouselOptions},n=e=>null==e||""===e?null:e,o=(e,t)=>n(e)!==n(t),r=o(i.imageUrl,s.imageUrl),l=o(i.videoUrl,s.videoUrl);return i.adName!==s.adName||i.adCaption!==s.adCaption||i.adHeadline!==s.adHeadline||i.adHeadlineDescription!==s.adHeadlineDescription||i.uploadType!==s.uploadType||l||r||i.greetingMessage!==s.greetingMessage||i.switchChecked!==s.switchChecked||JSON.stringify(i.iceBreakers)!==JSON.stringify(s.iceBreakers)||(i.adFormat||"single")!==(s.adFormat||"single")||JSON.stringify(i.cards||[])!==JSON.stringify(s.cards||[])||JSON.stringify(i.carouselOptions||{})!==JSON.stringify(s.carouselOptions||{})},this.createDraftAd=()=>{var e,t,a,s,n;this.setState({isLoading:!0});const{adName:o,adCaption:r,adHeadline:l,imageFile:d,thumbnailUrl:c,videoFile:p,uploadType:u,geoLocations:h,excludedGeoLocations:m,gender:g,FromAge:x,ToAge:v,advanceTargets:y,dailyBudget:f,duration:A,fromDate:b,toDate:S,selectedPlatforms:I,selectedAudience:j,isEndDate:C}=this.state;let{assistantId:w,assistantName:k,partnerId:Z,currency:T}=this.props.assistantDetails;const D=this.resolveAdAccountId(),P=this.resolveMetaPageId(),{adId:B}=this.props.match.params,E={adId:B,assistantId:w,assistantName:k,adAccountId:D,metaPageId:P,adDescription:r,adName:o,dailyBudget:"daily_budget"===this.state.selectedBudget.value?f:0,..."carousel"!==this.state.adFormat?{headline:l,headlineDescription:this.state.adHeadlineDescription}:{},gender:g,minAge:parseInt(x),maxAge:parseInt(v),geoLocation:h,excludedGeoLocation:m,adStopDate:C?S:"",adStartDate:b,duration:A,advanceTargets:y,selectedPlatforms:I,audienceId:(null===j||void 0===j?void 0:j._id)||"",duplicateAd:this.isDuplicateAd,iceBreakers:{status:!1},isScheduledAd:this.state.isScheduledAd,lifetimeBudget:"lifetime_budget"===this.state.selectedBudget.value?this.state.lifetimeBudget:0,ctaButton:this.state.ctaButton||"APPLY_NOW",websiteUrl:this.state.websiteUrl||"",adType:(null===(e=this.state.adType)||void 0===e?void 0:e.value)||"",adObjective:(null===(t=this.state.adObjective)||void 0===t?void 0:t.value)||"",optimizationGoal:(null===(a=this.state.optimizationGoal)||void 0===a?void 0:a.value)||"",pixelId:(null===(s=this.state.pixel)||void 0===s?void 0:s.value)||"",conversionEvent:(null===(n=this.state.conversionEvent)||void 0===n?void 0:n.value)||"",adPlacements:this.state.adPlacements||{},customAndLookalikeAudiences:this.state.customAndLookalikeAudiences||[],excludedCustomAndLookalikeAudiences:this.state.excludedCustomAndLookalikeAudiences||[],leadFormId:this.state.leadFormId||"",leadFormAutomation:this.state.leadFormAutomation||null,advantageAudience:this.state.advantageAudience?1:0};if(this.state.isScheduledAd){const e=this.convertScheduleStrings(this.state.selectedCells);E.adSetSchedule=e,E.timezoneType="viewer"===this.state.selectedTimezone.value?"USER":"ADVERTISER"}if(this.state.switchChecked){E.iceBreakers.status=!0,E.iceBreakers.iceBreakerNodeId=this.state.iceBreakerNodeId;const e=[],t=this.state.iceBreakers.filter((e=>{let{iceBreakerText:t}=e;return!!t})).map((t=>{let{iceBreakerText:a,flowId:i,iceBreakerId:s,blockId:n,blockHandle:o}=t;return e.push({iceBreaker:a,flowId:i.toString(),iceBreakerId:s,blockId:n,blockHandle:o}),{title:a}})),a={text:this.state.greetingMessage,ice_breakers:t};E.iceBreakers.rawMetaIceBreakers=a,E.iceBreakers.iceBreakerFlowMapping=e}"carousel"===this.state.adFormat?(E.adFormat="carousel",E.cards=this.state.cards,E.carouselOptions=this.state.carouselOptions):"VIDEO_UPLOAD"===u?(E.videoUrl=null===p||void 0===p?void 0:p.publicUrl,E.imageUrl="string"===typeof c?c:null===c||void 0===c?void 0:c.publicUrl):"IMAGE_UPLOAD"===u&&(E.imageUrl=null===d||void 0===d?void 0:d.publicUrl),u&&i.Z.post("".concat(W.URL,"/meta-ads/create-draft-meta-ad"),E).then((e=>{this.state.switchChecked&&this.updateFlowsNew(e.data),this.props.history.push("/projects/".concat(w,"/advertisement")),this.setState({isLoading:!1,snack:!this.state.snack,snackMessage:"Ad saved successfully",snackStatus:"success"})})).catch((e=>{var t,a,i,s,n;console.log("error:",e),this.setState({isLoading:!1,snack:!0,snackMessage:(null===e||void 0===e||null===(t=e.response)||void 0===t||null===(a=t.data)||void 0===a?void 0:a.message)||(null===e||void 0===e||null===(i=e.response)||void 0===i||null===(s=i.data)||void 0===s||null===(n=s.errorMessage)||void 0===n?void 0:n.error_user_msg)||"Something went wrong",snackStatus:"error"})}))},this.editAd=()=>{var e,t,a,s,n;this.setState({isLoading:!0});const{adName:o,adCaption:r,adHeadline:l,imageFile:d,thumbnailUrl:c,videoFile:p,uploadType:u,geoLocations:h,excludedGeoLocations:m,gender:g,FromAge:x,ToAge:v,advanceTargets:y,dailyBudget:f,duration:A,fromDate:b,selectedPlatforms:S,selectedAudience:I,isEndDate:j}=this.state;let{toDate:C}=this.state,{assistantId:w,assistantName:k}=this.props.assistantDetails;const Z=this.resolveAdAccountId(),T=this.resolveMetaPageId(),D=_()();C=_()(C).set({hour:D.hour(),minute:D.minute(),second:D.second(),millisecond:D.millisecond()}).add(5,"seconds").toDate();const{adId:P}=this.props.match.params,B={adId:P,assistantId:w,assistantName:k,adAccountId:Z,metaPageId:T,adDescription:r,adName:o,dailyBudget:"daily_budget"===this.state.selectedBudget.value?f:0,..."carousel"!==this.state.adFormat?{headline:l,headlineDescription:this.state.adHeadlineDescription}:{},gender:g,minAge:parseInt(x),maxAge:parseInt(v),geoLocation:h,excludedGeoLocation:m,adStopDate:j?C:"",adStartDate:b,duration:A,advanceTargets:y,selectedPlatforms:S,audienceId:(null===I||void 0===I?void 0:I._id)||"",isScheduledAd:this.state.isScheduledAd,lifetimeBudget:this.state.lifetimeBudget,hasCreativeChanges:this.hasCreativeChanges(),websiteUrl:this.state.websiteUrl||"",ctaButton:this.state.ctaButton||"APPLY_NOW",adPlacements:this.state.adPlacements||{},customAndLookalikeAudiences:this.state.customAndLookalikeAudiences||[],excludedCustomAndLookalikeAudiences:this.state.excludedCustomAndLookalikeAudiences||[],adType:(null===(e=this.state.adType)||void 0===e?void 0:e.value)||"",adObjective:(null===(t=this.state.adObjective)||void 0===t?void 0:t.value)||"",optimizationGoal:(null===(a=this.state.optimizationGoal)||void 0===a?void 0:a.value)||"",pixelId:(null===(s=this.state.pixel)||void 0===s?void 0:s.value)||"",conversionEvent:(null===(n=this.state.conversionEvent)||void 0===n?void 0:n.value)||"",leadFormId:this.state.leadFormId||"",leadFormAutomation:this.state.leadFormAutomation||null,advantageAudience:this.state.advantageAudience?1:0};if(this.state.isScheduledAd){const e=this.convertScheduleStrings(this.state.selectedCells);B.adSetSchedule=e,B.timezoneType="viewer"===this.state.selectedTimezone.value?"USER":"ADVERTISER"}if(this.state.switchChecked){B.iceBreakers={},B.iceBreakers.status=!0,B.iceBreakers.iceBreakerNodeId=this.state.iceBreakerNodeId;const e=[],t=this.state.iceBreakers.filter((e=>{let{iceBreakerText:t}=e;return!!t})).map((t=>{let{iceBreakerText:a,flowId:i,iceBreakerId:s,blockId:n,blockHandle:o}=t;return e.push({iceBreaker:a,flowId:i.toString(),iceBreakerId:s,blockId:n,blockHandle:o}),{title:a}})),a={text:this.state.greetingMessage,ice_breakers:t};B.iceBreakers.rawMetaIceBreakers=a,B.iceBreakers.iceBreakerFlowMapping=e}"carousel"===this.state.adFormat?(B.adFormat="carousel",B.cards=this.state.cards,B.carouselOptions=this.state.carouselOptions):"VIDEO_UPLOAD"===u?(B.videoUrl=null===p||void 0===p?void 0:p.publicUrl,B.imageUrl="string"===typeof c?c:null===c||void 0===c?void 0:c.publicUrl):"IMAGE_UPLOAD"===u&&(B.imageUrl=null===d||void 0===d?void 0:d.publicUrl),u&&i.Z.post("".concat(W.URL,"/meta-ads/edit-meta-ad"),B).then((e=>{this.state.switchChecked&&this.updateFlowsNew(e.data.newAdData),setTimeout((()=>{this.props.history.push("/projects/".concat(w,"/advertisement/").concat(P,"/personal-analytics/")),this.setState({isLoading:!1,snack:!this.state.snack,snackMessage:"Ad saved successfully",snackStatus:"success"})}),200)})).catch((e=>{var t,a,i,s,n;console.log("error:",e),this.setState({isLoading:!1,snack:!0,snackMessage:(null===e||void 0===e||null===(t=e.response)||void 0===t||null===(a=t.data)||void 0===a?void 0:a.message)||(null===e||void 0===e||null===(i=e.response)||void 0===i||null===(s=i.data)||void 0===s||null===(n=s.errorMessage)||void 0===n?void 0:n.error_user_msg)||"Something went wrong",snackStatus:"error"})}))},this.validateLinkChange=async e=>{const t=/^(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,10}\b([-a-zA-Z0-9()@:%_+.~#?&\/=]*)$/g,{value:a}=e.target;if(a){this.setState({validatingLink:!0});if(t.test(a))try{var s,n,o;const{assistantId:e}=this.props.assistantDetails,t=await i.Z.post("".concat(W.URL,"/meta-ads/fetch-web-meta-data"),{link:"https://".concat(a),assistantId:e}),r=null===t||void 0===t||null===(s=t.data)||void 0===s?void 0:s.documentDOC,l=(new DOMParser).parseFromString(r,"text/html"),d=null===(n=l.querySelector("meta[property='og:description']"))||void 0===n?void 0:n.getAttribute("content"),c=null===(o=l.querySelector("meta[property='og:image']"))||void 0===o?void 0:o.getAttribute("content");this.setState({errorLink:"",validatingLink:!1,linkMetaData:{linkTitle:l.title,linkDescription:d,linkImage:c}})}catch(r){console.log(r),this.setState({errorLink:"Invalid Website Link",validatingLink:!1,linkMetaData:{linkTitle:"",linkDescription:"",linkImage:""}}
2)}else this.setState({errorLink:"Invalid Website Link",validatingLink:!1,linkMetaData:{linkTitle:"",linkDescription:"",linkImage:""}})}},this.carouselRequiresPerCardUrl=()=>{var e;return["website_traffic","website_to_whatsapp"].includes(null===(e=this.state.adType)||void 0===e?void 0:e.value)},this.getCarouselFormatError=()=>{var e,t;return"whatsapp_status"===(null===(e=this.state.adType)||void 0===e?void 0:e.value)?"Carousel format is not supported for WhatsApp Status ads":((null===(t=this.state.adPlacements)||void 0===t?void 0:t.facebookPositions)||[]).includes("story")?"Carousel format cannot be combined with the Story placement":""},this.isValidCarouselUrl=e=>{try{return new window.URL(e),!0}catch(t){return!1}},this.getCardValidationError=(e,t,a)=>("video"===e.mediaType?e.videoUrl:e.imageUrl)?e.imageUrl&&!this.isValidCarouselUrl(e.imageUrl)?"Card #".concat(t+1,": image URL is invalid"):e.videoUrl&&!this.isValidCarouselUrl(e.videoUrl)?"Card #".concat(t+1,": video URL is invalid"):e.headline?e.headline.length>40?"Card #".concat(t+1,": headline must be ").concat(40," characters or fewer"):e.description&&e.description.length>30?"Card #".concat(t+1,": description must be ").concat(30," characters or fewer"):a&&!e.websiteUrl?"Card #".concat(t+1,": website URL is required"):e.websiteUrl&&!this.isValidCarouselUrl(e.websiteUrl)?"Card #".concat(t+1,": website URL is invalid"):"":"Card #".concat(t+1,": headline is required"):"Card #".concat(t+1,": image or video is required"),this.isCarouselCreativeInvalid=()=>{const{cards:e}=this.state;if(!Array.isArray(e)||e.length<2||e.length>Tt)return!0;if(this.getCarouselFormatError())return!0;const t=this.carouselRequiresPerCardUrl();return e.some(((e,a)=>!!this.getCardValidationError(e,a,t)))},this.getCarouselValidationError=()=>{const{cards:e}=this.state;if(!Array.isArray(e)||e.length<2)return"A carousel needs at least ".concat(2," cards");if(e.length>Tt)return"A carousel can have at most ".concat(Tt," cards");const t=this.getCarouselFormatError();if(t)return t;const a=this.carouselRequiresPerCardUrl();for(let i=0;i<e.length;i++){const t=this.getCardValidationError(e[i],i,a);if(t)return t}return""},this.nextBtnDisableStatus=e=>{var t,a,i;const{assistantDetails:n}=this.props,{metaAdsCredit:o,currency:r}=n,{adCaption:l,adName:d,imageFile:c,videoFile:p,thumbnailUrl:u,uploadType:h,adHeadline:m,gender:g,selectedLocations:x,FromAge:v,ToAge:y,dailyBudget:f,duration:A,selectedPlatforms:b=[],iceBreakers:S,greetingMessage:I,switchChecked:j,adAccountData:C,lifetimeBudget:w,customAndLookalikeAudiences:k,adFormat:Z,cards:T}=this.state,{accountId:D}=C||{},P="INR"===((null===n||void 0===n||null===(t=n.adSetupDetails)||void 0===t?void 0:t.selectedMetaAdAccountId)==D?r:null===C||void 0===C?void 0:C.currency)?"INR":"USD",B=Xt.cU[P],E=Xt.uy[P];switch(e){case 0:return!this.state.selectedAdType;case 1:return"carousel"===Z?!l||!d||this.state.isGenerating||this.isCarouselCreativeInvalid():!l||!d||!(c||p)||"VIDEO_UPLOAD"===h&&!this.isValidHttpUrl(null===p||void 0===p?void 0:p.publicUrl)||"VIDEO_UPLOAD"===h&&u&&!this.isValidHttpUrl(null===u||void 0===u?void 0:u.publicUrl)&&!this.isValidHttpUrl(u)||"IMAGE_UPLOAD"===h&&!this.isValidHttpUrl(null===c||void 0===c?void 0:c.publicUrl)||"whatsapp_status"!==(null===(a=this.state.adType)||void 0===a?void 0:a.value)&&!m||this.state.isGenerating;case 2:return!g||(0,s.isEmpty)(x)&&(0,s.isEmpty)(k)||!v||!y||!Array.isArray(b)||0===(null===b||void 0===b?void 0:b.length);case 3:{let e="";if("lifetime_budget"===this.state.selectedBudget.value&&this.state.isScheduledAd)if(0===this.state.selectedCells.size)e="Please select a valid schedule";else{const{invalidSlots:t,message:a}=this.validateTimeSlotsAgainstDateRange();t.length>0&&(e=a)}const t=this.state.startDateError||this.state.isStartDateNull||this.state.endDateError||this.state.isEndDateNull;return"daily_budget"===this.state.selectedBudget.value?!f||f<B||!A||"USD"!==r&&f&&+o-2*f<0||e||t:!w||w<E||!A||"USD"!==r&&w&&+o-w<0||e||t}case 4:return["website_traffic","website_to_whatsapp"].includes(null===(i=this.state.adType)||void 0===i?void 0:i.value)?"carousel"!==Z&&(!this.state.websiteUrl||""===this.state.websiteUrl.trim()):!f||f<B||"USD"!==r&&f&&+o-2*f<0||!(()=>
2{if(!j)return!0;if(!I||!S||0===S.length)return!1;if(S.some((e=>!(null!==e&&void 0!==e&&e.iceBreakerText))))return!1;if(S.some((e=>{let{flowId:t,blockId:a}=e;return t&&!a})))return!1;for(let e=0;e<S.length-1;e++){const{iceBreakerText:t}=S[e];for(let a=e+1;a<S.length;a++){const{iceBreakerText:e}=S[a];if(t===e)return!1}}return!0})();default:return!0}},this.nextSection=e=>{switch(e){case 0:return this.nextBtnDisableStatus(0);case 1:return this.nextBtnDisableStatus(1);case 2:return this.nextBtnDisableStatus(2);default:return!1}},this.formatCompactCount=e=>{var t,a;const i=null===(t=this.props)||void 0===t||null===(a=t.assistantDetails)||void 0===a?void 0:a.currency;return null===e||void 0===e||isNaN(e)?"\u2014":"INR"===i?e>=1e7?(e/1e7).toFixed(1).replace(/\.0$/,"")+" Cr":e>=1e5?(e/1e5).toFixed(1).replace(/\.0$/,"")+" Lakh":e>=1e3?(e/1e3).toFixed(1).replace(/\.0$/,"")+" K":String(e):e>=1e6?(e/1e6).toFixed(1).replace(/\.0$/,"")+" Mn":e>=1e3?(e/1e3).toFixed(1).replace(/\.0$/,"")+" K":String(e)},this.formatNumber=(e,t)=>{const a="Monthly Active Users";return"INR"===t?e>=1e7?(e/1e7).toFixed(1).replace(/\.0$/,"")+" Cr "+a:e>=1e5?(e/1e5).toFixed(1).replace(/\.0$/,"")+" Lakh "+a:e>=1e3?(e/1e3).toFixed(1).replace(/\.0$/,"")+" K "+a:e+" "+a:"USD"===t?e>=1e6?(e/1e6).toFixed(1).replace(/\.0$/,"")+" Mn "+a:e>=1e3?(e/1e3).toFixed(1).replace(/\.0$/,"")+" K "+a:e+" "+a:e+" "+a},this.formatGeoLocationsSummary=e=>Object.entries(Object.entries(e||{}).reduce(((e,t)=>{let[a,i]=t;return"location_types"===a||(i||[]).forEach((t=>{const i={};Va.ZP.forEach((e=>{i[e.isoCode]=e.name}));const s="string"===typeof t?i[t]||t:t.country_name;e[s]||(e[s]=[]),"countries"===a||e[s].push("".concat(t.name).concat(t.radius?" (".concat(t.radius,"km)"):"").concat("zip"===(null===t||void 0===t?void 0:t.type)?", ".concat(null===t||void 0===t?void 0:t.region):""))})),e}),{})).map((e=>{let[t,a]=e;return a.length?"".concat(t).concat(a.length?"".concat(t?": ":""," ").concat(a.join("; ")):""):t})).filter(Boolean).join(", "),this.handleSaveAudience=async()=>{const{audienceName:e,selectedAudience:t,isUpdateMode:a}=this.state,{gender:s,FromAge:n,ToAge:o,geoLocations:r,advanceTargets:l,selectedPlatforms:d,selectedLocations:c,excludedSelectedLocations:p}=this.state,{assistantId:u}=this.props.assistantDetails;if(e.trim())if(/[a-zA-Z]/.test(e)){this.setState({savingAudience:!0});try{const r={assistantId:u,audienceName:e.trim(),gender:s,minAge:parseInt(n),maxAge:parseInt(o),geoLocation:c,excludedGeoLocation:p,advanceTargets:l,selectedPlatforms:d};let h;h=a&&t._id?await i.Z.post("".concat(W.ADS_REST_API_URL,"/meta/audiences/saved/update"),{audienceId:t._id,...r,assistantId:u}):await i.Z.post("".concat(W.ADS_REST_API_URL,"/meta/audiences/saved/create"),r);const m=h.data;this.setState({showSaveAudienceModal:!1,saveAudienceError:"",snack:!0,snackMessage:"Audience ".concat(a?"updated":"saved"," successfully"),snackStatus:"success",savingAudience:!1,isUpdateMode:!1,keyThird:new Date,selectedAudience:m,audienceName:m.audienceName}),this.audienceFormRef.current&&this.audienceFormRef.current.loadLatestAudiences()}catch(x){var h,m,g;this.setState({saveAudienceError:(null===x||void 0===x||null===(h=x.response)||void 0===h||null===(m=h.data)||void 0===m||null===(g=m.errorMessage)||void 0===g?void 0:g.message)||"Failed to ".concat(a?"update":"save"," audience"),savingAudience:!1})}}else this.setState({saveAudienceError:"Audience name should contain at least one alphabet"});else this.setState({saveAudienceError:"Audience name is required"})},this.checkAudienceChanged=()=>{const{selectedAudience:e}=this.state,{gender:t,FromAge:a,ToAge:i,selectedLocations:s,excludedSelectedLocations:o,advanceTargets:r,selectedPlatforms:l}=this.state;if(!e)return!1;const d=(e,t)=>{const a=e||[],i=t||[];if(a.length!==i.length)return!0;for(let s=0;s<i.length;s++)if(!a.some((e=>e.label===i[s].label&&e.value.radius===i[s].value.radius)))return!0;return!1},c=d(e.geoLocation,s)||d(e.excludedGeoLocation,o);let p=!n().isEqual((e.selectedPlatforms||[]).sort(),(l||[]).sort()),u=!1;const h=e.advanceTargets||{},m=r||{};for(const g of Object.keys(h)){const e=h[g]||[],t=m[g]||[],a=n().sortBy(e,"id"),i=n().sortBy(t,"id");if(!n().isEqual(a,i)){u=!0;break}}return e.gender!==t||e.minAge!==a||e.maxAge!==i||c||p||u},this.isValidAd=()=>{var e;const t=this.getPublishTooltipMessage();return t?(this.setState({snackStatus:"warning",snackMessage:t,snack:!0}),!1):this.state.isLiveAD&&!this.isDuplicateAd||!_()(this.state.fromDate).startOf("day").isBefore(_()().startOf("day"))?null===(e=this.state.deprecatedAdvanceTargets)||void 0===e||!e.length||!this.state.deprecatedAdvanceTargets.some((e=>!n().isEmpty(this.state.selectedAdvanceTargets)&&this.state.selectedAdvanceTargets.some((t=>t.value.id===e.id))))||(this.setState({snackStatus:"warning",snackMessage:"Some of your selected advanced targets are no longer supported by the platform. Please remove or replace them to ensure your Ad can be published.",snack:!0}),!1):(this.setState({snackStatus:"warning",snackMessage:"Invalid End Date",snack:!0}),!1)},this.getPublishTooltipMessage=()=>{var e,t,a,i;const{imageFile:s,videoFile:n,thumbnailUrl:o,uploadType:r,switchChecked:l,iceBreakers:d,greetingMessage:c,adAccountData:p,duration:u}=this.state,{accountId:h}=p||{},{assistantDetails:m}=this.props,{currency:g,metaAdsCredit:x}=m,v="INR"===((null===m||void 0===m||null===(e=m.adSetupDetails)||void 0===e?void 0:e.selectedMetaAdAccountId)==h?g:null===p||void 0===p?void 0:p.currency)?"INR":"USD",y=Xt.cU[v],f=Xt.uy[v];if(""===this.state.adName)return"Ad Name is required";if(""===this.state.adCaption)return"Ad Caption is required";if("carousel"===this.state.adFormat){const e=this.getCarouselValidationError();if(e)return e}else{var A;if("whatsapp_status"!==(null===(A=this.state.adType)||void 0===A?void 0:A.value)&&""===this.state.adHeadline)return"Ad Headline is required";if("IMAGE_UPLOAD"===r&&!this.isValidHttpUrl(null===s||void 0===s?void 0:s.publicUrl))return"Please enter a valid image url";if("VIDEO_UPLOAD"===r&&!this.isValidHttpUrl(null===n||void 0===n?void 0:n.publicUrl))return"Please enter a valid video url";if("VIDEO_UPLOAD"===r&&o&&!this.isValidHttpUrl(null===o||void 0===o?void 0:o.publicUrl)&&!this.isValidHttpUrl(o))return"Please enter a valid thumbnail url"}if((!this.state.selectedLocations||0===(null===(t=this.state.selectedLocations)||void 0===t?void 0:t.length))&&0===this.state.customAndLookalikeAudiences.length)return"Select at least one location";if(!this.state.selectedPlatforms||0===(null===(a=this.state.selectedPlatforms)||void 0===a?void 0:a.length))return"Select at least one Ad platform";var b,S,I,j;if("daily_budget"===this.state.selectedBudget.value){if(this.state.dailyBudget<y)return"Daily Budget should be at least ".concat(y," ").concat(null===(b=this.props)||void 0===b||null===(S=b.assistantDetails)||void 0===S?void 0:S.currency)}else if(this.state.lifetimeBudget<f)return"Lifetime Budget should be at least ".concat(f," ").concat(null===(I=this.props)||void 0===I||null===(j=I.assistantDetails)||void 0===j?void 0:j.currency);if("daily_budget"===this.state.selectedBudget.value){if(parseInt(x)-2*this.state.dailyBudget<0)return"Insufficient Balance"}else if(parseInt(x)-this.state.lifetimeBudget<0)return"Insufficient Balance";if(this.state.startDateError||this.state.isStartDateNull)return"Invalid Ad Start Date";if(this.state.endDateError||this.state.isEndDateNull)return"Invalid Ad End Date";if("lifetime_budget"===this.state.selectedBudget.value&&this.state.isScheduledAd&&0===this.state.selectedCells.size)return"Please select a valid schedule";if("lifetime_budget"===this.state.selectedBudget.value&&this.state.isScheduledAd){const{invalidSlots:e,message:t}=this.validateTimeSlotsAgainstDateRange();if(e.length>0)return t}if(l){if(!c)return"Greeting Message is required";if(0===d.length)return"At least One Ice Breaker is required";if(d.some((e=>{let{iceBreakerText:t}=e;return!t})))return"Ice Breaker Text Cannot be Empty";if(d.some((e=>{let{flowId:t,blockId:a}=e;return t&&!a})))return"Please select blocks for all flows";for(let e=0;e<d.length-1;e++){const{iceBreakerText:t}=d[e];for(let a=e+1;a<d.length;a++){const{iceBreakerText:e}=d[a];if(t===e)return"Duplicate Icebreaker Texts are not allowed"}}}return"carousel"!==this.state.adFormat&&["website_traffic","website_to_whatsapp"].includes(null===(i=this.state.adType)||void 0===i?void 0:i.value)&&!this.state.websiteUrl?"Website URL is required":""},this.validateAdvancedTargets=async(e,t)=>{try{if(!e||0===Object.keys(e).length)return;const{data:a}=await i.Z.post("".concat(W.URL,"/meta-ads/validate-advanced-targeting"),{assistantId:t,advanceTargets:e});this.setState({deprecatedAdvanceTargets:a}),a&&Array.isArray(a)&&a.length>0&&this.setState({snackStatus:"warning",snackMessage:"Some of your selected advanced targets are no longer supported by the platform. Please remove or replace them to ensure your Ad can be published.",snack:!0})}catch(a){console.log("Error validating targets",a)}},this.applyDefaultBudgets=(e,t)=>{const a={};this.state.dailyBudget||(a.dailyBudget=e),this.state.lifetimeBudget||(a.lifetimeBudget=t),Object.keys(a).length>0&&this.setState(a)},this.audienceFormRef=r.createRef(),this.debouncedGetEstimatedDeliveryUsers=n().debounce((()=>{this.getEstimatedDeliveryUsers()}),500),this.debouncedUpdateIceBreakers=n().debounce(this.props.updateIceBreakers,300),this.debouncedRecreateAllIceBreakers=n().debounce(this.props.recreateAllIceBreakerNodes,300),this.state={leadFormId:"",leadForm:null,adAccountData:{},lable:"Advertisement details",activeStep:0,expandedSections:new Set([0]),selectedAdType:"ctwa",websiteUrl:"",pixelId:"",error:null,status:null,snack:!1,snackMessage:"",snackStatus:"",isLoading:!1,hash:null,validatingLink:!1,errorAction:{},showDialog:!1,adName:"",adCaption:"",adHeadline:"",adHeadlineDescription:"",imageFile:null,thumbnailUrl:null,videoFile:null,uploadType:"IMAGE_UPLOAD",adFormat:"single",cards:[],carouselOptions:{multiShareOptimized:!0,multiShareEndCard:!1},selectedLocations:[],excludedSelectedLocations:[],customAndLookalikeAudiences:[],excludedCustomAndLookalikeAudiences:[],geoLocations:{countries:[],cities:[],regions:[],places:[],zips:[]},excludedGeoLocations:{countries:[],cities:[],regions:[],places:[],zips:[]},gender:"ALL",FromAge:"18",ToAge:"65",advanceTargets:{},selectedAdvanceTargets:[],advantageAudience:!1,advantageAudienceLocked:!1,dailyBudget:0,lifetimeBudget:0,duration:2,isEndDate:!1,fromDate:new Date,toDate:new Date((new Date).setDate((new Date).getDate()+2)),minDate:new Date((new Date).setDate((new Date).getDate()+2)),estimatedData:{},isLiveAD:!1,keyThird:new Date,selectedPlatforms:["facebook","instagram"],adPlacements:{facebookPositions:[],instagramPositions:[]},adEffectiveStatus:null,originalDuration:null,showSaveAudienceModal:!1,audienceName:"",saveAudienceError:"",savingAudience:!1,selectedAudience:null,isUpdateMode:!1,originalEndDate:null,originalStartDate:null,adStatus:null,isAdFetched:!1,greetingMessage:"",switchChecked:!1,iceBreakers:[{iceBreakerText:"",flowId:"",iceBreakerId:"".concat(Date.now()),blockId:"",blockHandle:""}],iceBreakerNodeId:"".concat(Date.now()),prevIceBreakerNodeId:"",defaultIceBreakers:[{iceBreakerText:"",flowId:""}],defaultGreetingMsg:"",isDefaultIceBreakerOn:!1,isIceBreakerStepOn:!1,currSelectedFlowId:"",estimatedReachLoading:!1,iceBreakerName:"",isIceBreakerSaving:!1,showSaveIceBreakerModal:!1,initialIceBreakerFlowIds:[],currSelectedSavedIceBreaker:null,totalAdsCount:20,savedIceBreakers:[],showPreview:!1,isScheduledAd:!1,selectedTimezone:{label:"Use Viewer's time zone",value:"viewer"},selectedBudget:{label:"Daily Budget",value:"daily_budget"},selectedCells:new Set,selectedSlotsCount:0,startDateError:"",endDateError:"",isStartDateNull:!1,isEndDateNull:!1,originalCreativeData:null,adType:Xt.T$[0],adObjective:Xt.eO[0],optimizationGoal:"",conversionEvent:null,ctaButton:"APPLY_NOW",isGenerating:!1,isImageGenerating:!1,isVideoGenerating:!1,adDialogOpen:!1,deprecatedAdvanceTargets:[]}}componentDidMount(){var e,t;this.fetchAdAccount(),this.fetchMetaPage(),this.isCreateAd&&this.getEstimatedDeliveryUsers(),this.debouncedUpdateIceBreakers({iceBreakerNodeId:this.state.iceBreakerNodeId,iceBreakers:this.state.iceBreakers});const{currency:a,iceBreakers:i}=this.props.assistantDetails,{projectId:s}=this.props.match.params;var n,o;(this.props.getFlows(s),null!==(e=this.props.assistantDetails)&&void 0!==e&&null!==(t=e.flowConfiguration)&&void 0!==t&&t.totalAdsCount)&&this.setState({totalAdsCount:20+(null===(n=this.props.assistantDetails)||void 0===n||null===(o=n.flowConfiguration)||void 0===o?void 0:o.totalAdsCount)});const{rawMetaIceBreakers:r,isDefaultIceBreakerOn:l,iceBreakerFlowMapping:d}=i||{},c=(null===r||void 0===r?void 0:r.text)||"",p=((null===r||void 0===r?void 0:r.ice_breakers)||[]).map((e=>{var t;let{title:a}=e;return{iceBreakerText:a,flowId:(null===(t=(d||[]).find((e=>e.iceBreaker===a)))||void 0===t?void 0:t.flowId)||""}}));this.setState({defaultIceBreakers:p,defaultGreetingMsg:c,isDefaultIceBreakerOn:l});const{projectId:u,adId:h}=this.props.match.params,{state:m}=this.props.location;if(u&&this.props.fetchPixels({assistantId:u,limit:100}),null!==m&&void 0!==m&&m.selectedAudience){const{name:e,audienceId:t,accountId:a,type:i}=m.selectedAudience;this.setState({customAndLookalikeAudiences:[{name:e,audienceId:t,accountId:a,type:i}]})}try{var g;const e=(null===(g=this.props.location)||void 0===g?void 0:g.search)||"",t=new
2URLSearchParams(e),a=t.get("selectedAdType"),i=t.get("pixelId");if(this.isCreateAd&&(a||i)){if(a){this.changeState("selectedAdType",a);const e=Xt.T$.find((e=>e.value===a));if(e){this.changeState("adType",e);const{objective:t,goal:a}=(0,Xt.Ge)(e.type);t&&this.changeState("adObjective",t),a&&this.changeState("optimizationGoal",a)}}i&&this.changeState("pixelId",i)}}catch(x){}this.fetchAd({adId:h,projectId:u}),"USD"!==a&&this.fetchMetaAdAccount(u),this.isCreateAd&&null!==m&&void 0!==m&&m.adTemplateVariant&&this.hydrateFromAdTemplate(m.adTemplateVariant)}validateTimeSlotsAgainstDateRange(){var e;const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=null===(e=this.state.adAccountData)||void 0===e?void 0:e.timezone,{fromDate:i,toDate:s,selectedCells:n}=this.state;if(!s)return{invalidSlots:[]};const o=new Set;let r=_().tz(i,a).startOf("day");const l=_().tz(s,a).endOf("day");if(l.diff(r,"days")>=6)return{invalidSlots:[]};for(;r.isSameOrBefore(l);)o.add(r.day()),r.add(1,"day");const d=[],c=new Set;for(const p of n){const[e]=p.split("-");if("7"===e)continue;const t=parseInt(e,10);o.has(t)||(d.push(p),c.add(t))}if(d.length>0){const e=[...c].map((e=>t[e])).join(", "),s=[];for(r=_().tz(i,a);r.isSameOrBefore(l);)s.push(t[r.day()]),r.add(1,"day");const n=[...new Set(s)],o=1===n.length?n[0]:"".concat(n[0]," to ").concat(n[n.length-1]);return{invalidSlots:d,message:"You have scheduled this ad set to run on ".concat(e,". But the selected date range only includes ").concat(o,". Please change your date range or schedule.")}}return{invalidSlots:[]}}componentDidUpdate(e,t){var a,i,s,n,o,r,l,d,c,p,u,h;(e.isFlowPopupOpen!==this.props.isFlowPopupOpen&&this.syncIceBreakers(),(null===(a=this.props.assistantDetails)||void 0===a||null===(i=a.flowConfiguration)||void 0===i?void 0:i.totalAdsCount)!==(null===(s=e.assistantDetails)||void 0===s||null===(n=s.flowConfiguration)||void 0===n?void 0:n.totalAdsCount))&&(null!==(c=this.props.assistantDetails)&&void 0!==c&&null!==(p=c.flowConfiguration)&&void 0!==p&&p.totalAdsCount&&this.setState({totalAdsCount:20+(null===(u=this.props.assistantDetails)||void 0===u||null===(h=u.flowConfiguration)||void 0===h?void 0:h.totalAdsCount)}));t.gender!==this.state.gender&&this.getEstimatedDeliveryUsers(),t.FromAge!==this.state.FromAge&&this.getEstimatedDeliveryUsers(),t.ToAge!==this.state.ToAge&&this.getEstimatedDeliveryUsers(),t.selectedPlatforms.length!==this.state.selectedPlatforms.length&&this.getEstimatedDeliveryUsers(),t.adPlacements!==this.state.adPlacements&&this.getEstimatedDeliveryUsers(),t.dailyBudget===this.state.dailyBudget&&t.selectedBudget===this.state.selectedBudget&&t.optimizationGoal===this.state.optimizationGoal||this.debouncedGetEstimatedDeliveryUsers(),(null===(o=e.assistantDetails)||void 0===o?void 0:o.selectedMetaPageId)===(null===(r=this.props.assistantDetails)||void 0===r?void 0:r.selectedMetaPageId)&&(null===(l=e.assistantDetails)||void 0===l?void 0:l.fbConnected)===(null===(d=this.props.assistantDetails)||void 0===d?void 0:d.fbConnected)||this.fetchMetaPage()}isValidHttpUrl(e){let t;try{t=new window.URL(e)}catch(a){return!1}return"http:"===t.protocol&&(null===e||void 0===e?void 0:e.startsWith("http://"))||"https:"===t.protocol&&(null===e||void 0===e?void 0:e.startsWith("https://"))}fetchAd(e){let{adId:t,projectId:a}=e;t&&a&&i.Z.post("".concat(W.URL,"/meta-ads/sync-ad"),{assistantId:a,_id:t,isFromEdit:!0}).then((async e=>{var t,i,s,n,o,r,l,d,c,p,u,h,m,g,x,v,y,f,A,b;const S=e.data.adData;this.validateAdvancedTargets((null===S||void 0===S||null===(t=S.advanceTargets)||void 0===t||null===(i=t.flexible_spec)||void 0===i?void 0:i[0])||(null===S||void 0===S?void 0:S.advanceTargets)||{},a);let I=this.state.iceBreakers;const{iceBreakers:j}=e.data.adData,C=null===j||void 0===j||null===(s=j.iceBreakerFlowMapping)||void 0===s?void 0:s.map((e=>e.flowId)).filter((e=>!!e)).filter(((e,t,a)=>t===a.findIndex((t=>t===e)))),{status:w,rawMetaIceBreakers:k}=j||{};let{iceBreakerNodeId:Z}=j||{};const T=Z;if(this.isDuplicateAd&&(Z="".concat(Date.now())),k&&w&&k.ice_breakers&&S.iceBreakers&&S.iceBreakers.iceBreakerFlowMapping){const e=S.iceBreakers.iceBreakerFlowMapping;I=k.ice_breakers.map((t=>{var a,i,s,n,o,r,l,d,c,p,u,h,m,g;let{title:x}=t;const v=e.find((e=>e.iceBreaker===x))||{},y=null===v||void 0===v?void 0:v.flowId,f=null===v||void 0===v?void 0:v.iceBreakerId,A=!(null===v||void 0===v||!v.blockId)&&(null===(a=this.props.flows)||void 0===a||null===(i=a.find((e=>e._id===y)))||void 0===i||null===(s=i.flow)||void 0===s||null===(n=s.nodes)||void 0===n?void 0:n.some((e=>e.id===(null===v||void 0===v?void 0:v.blockId)))),b=!(null===v||void 0===v||!v.blockId)&&(null===(o=this.props.flows)||void 0===o||null===(r=o.find((e=>e._id===y)))||void 0===r||null===(l=r.flow)||void 0===l||null===(d=l.edges)||void 0===d?void 0:d.some((e=>!(!e.sourceHandle.includes("icebreaker_message-right")||e.sourceHandle.split("-").reverse()[0]!==f||e.target!==(null===v||void 0===v?void 0:v.blockId))))),S=A&&b&&(null===v||void 0===v?void 0:v.blockId)||"",I=A&&b&&(null===v||void 0===v?void 0:v.blockHandle)||"",j=(null===(c=this.props.flows)||void 0===c||null===(p=c.find((e=>e._id===y)))||void 0===p||null===(u=p.flow)||void 0===u||null===(h=u.nodes[0])||void 0===h||null===(m=h.data)||void 0===m||null===(g=m.ads)||void 0===g?void 0:g.length)||0;return{flowId:this.isEditAd||j<this.state.totalAdsCount?y:"",iceBreakerText:x,iceBreakerId:f,blockId:this.isEditAd||j<this.state.totalAdsCount?S:"",blockHandle:this.isEditAd||j<this.state.totalAdsCount?I:""}}))}this.debouncedUpdateIceBreakers({iceBreakerNodeId:Z,iceBreakers:I}),this.setState({adName:null===S||void 0===S?void 0:S.adName,adCaption:null===S||void 0===S?void 0:S.adDescription,adHeadline:(null===S||void 0===S?void 0:S.headline)||(null===S||void 0===S?void 0:S.headlineDescription),adHeadlineDescription:(null===S||void 0===S?void 0:S.headlineDescription)||"",uploadType:S.videoUrl?"VIDEO_UPLOAD":"IMAGE_UPLOAD",selectedLocations:[...await this.locationOptionValue((null===S||void 0===S||null===(n=S.geoLocation)||void 0===n?void 0:n.cities)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(o=S.geoLocation)||void 0===o?void 0:o.countries)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(r=S.geoLocation)||void 0===r?void 0:r.regions)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(l=S.geoLocation)||void 0===l?void 0:l.places)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(d=S.geoLocation)||void 0===d?void 0:d.zips)||[])],...(null===S||void 0===S?void 0:S.geoLocation)&&{geoLocations:null===S||void 0===S?void 0:S.geoLocation},excludedSelectedLocations:[...await this.locationOptionValue((null===S||void 0===S||null===(c=S.excludedGeoLocation)||void 0===c?void 0:c.cities)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(p=S.excludedGeoLocation)||void 0===p?void 0:p.countries)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(u=S.excludedGeoLocation)||void 0===u?void 0:u.regions)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(h=S.excludedGeoLocation)||void 0===h?void 0:h.places)||[]),...await this.locationOptionValue((null===S||void 0===S||null===(m=S.excludedGeoLocation)||void 0===m?void 0:m.zips)||[])],...(null===S||void 0===S?void 0:S.excludedGeoLocation)&&{excludedGeoLocations:null===S||void 0===S?void 0:S.excludedGeoLocation},gender:null===S||void 0===S?void 0:S.gender,FromAge:null===S||void 0===S?void 0:S.minAge,ToAge:null===S||void 0===S?void 0:S.maxAge,selectedPlatforms:(null===S||void 0===S?void 0:S.platforms)||[],websiteUrl:(null===S||void 0===S?void 0:S.websiteUrl)||"",pixelId:(null===S||void 0===S?void 0:S.pixelId)||this.state.pixelId||"",ctaButton:(null===S||void 0===S?void 0:S.ctaButton)||this.state.ctaButton,advanceTargets:(null===S||void 0===S||null===(g=S.advanceTargets)||void 0===g||null===(x=g.flexible_spec)||void 0===x?void 0:x[0])||
2(null===S||void 0===S?void 0:S.advanceTargets)||{},selectedAdvanceTargets:this.targetingOptionValue([(null===S||void 0===S||null===(v=S.advanceTargets)||void 0===v||null===(y=v.flexible_spec)||void 0===y?void 0:y[0])||(null===S||void 0===S?void 0:S.advanceTargets)||{}]),dailyBudget:(null===S||void 0===S?void 0:S.dailyBudget)/100,originalDuration:null===S||void 0===S?void 0:S.duration,duration:this.getInitialDuration(null===S||void 0===S?void 0:S.adStopDate,null===S||void 0===S?void 0:S.adStatus,null===S||void 0===S?void 0:S.adStartDate),isEndDate:!(null===S||void 0===S||!S.adStopDate),fromDate:null===S||void 0===S?void 0:S.adStartDate,toDate:this.getValidAdStopDate(null===S||void 0===S?void 0:S.adStopDate,null===S||void 0===S?void 0:S.adStatus,null===S||void 0===S?void 0:S.adStartDate),minDate:null===S||void 0===S?void 0:S.adStopDate,isLiveAD:"DRAFT"!==(null===S||void 0===S?void 0:S.adStatus)&&!this.isDuplicateAd,activeStep:0,expandedSections:new Set([0]),keyThird:new Date,originalEndDate:null===S||void 0===S?void 0:S.adStopDate,originalStartDate:null===S||void 0===S?void 0:S.adStartDate,adStatus:null===S||void 0===S?void 0:S.adStatus,adEffectiveStatus:null===S||void 0===S?void 0:S.adEffectiveStatus,originalDuration:null===S||void 0===S?void 0:S.duration,isAdFetched:!0,switchChecked:w,greetingMessage:null===k||void 0===k?void 0:k.text,iceBreakers:I,iceBreakerNodeId:Z,prevIceBreakerNodeId:T,initialIceBreakerFlowIds:C,selectedCells:this.extractScheduledString(null===S||void 0===S?void 0:S.adSetSchedule),selectedSlotsCount:this.getSelectedSlotsCount(this.extractScheduledString(null===S||void 0===S?void 0:S.adSetSchedule)),isScheduledAd:null===S||void 0===S?void 0:S.isScheduledAd,selectedBudget:!isNaN(parseInt(S.dailyBudget))&&parseInt(S.dailyBudget)?this.budgetOptions[1]:this.budgetOptions[0],lifetimeBudget:isNaN(parseInt(null===S||void 0===S?void 0:S.lifetimeBudget))?0:parseInt(null===S||void 0===S?void 0:S.lifetimeBudget)/100,selectedTimezone:"ADVERTISER"===(null===S||void 0===S?void 0:S.timezoneType)?this.timezoneOptions[1]:this.timezoneOptions[0],adType:(0,Xt.rz)(Xt.T$,null===S||void 0===S?void 0:S.adType)||"",adObjective:(0,Xt.rz)(Xt.eO,null===S||void 0===S?void 0:S.adCampaignObjective)||"",optimizationGoal:(0,Xt.rz)(null===(f=Xt.eO.find((e=>(null===e||void 0===e?void 0:e.value)===(null===S||void 0===S?void 0:S.adCampaignObjective))))||void 0===f?void 0:f.optimizationGoals,null===S||void 0===S?void 0:S.optimizationGoal)||"",pixel:(0,Xt.rz)(this.props.pixels,null===S||void 0===S?void 0:S.pixelId,"pixelId")||(null!==S&&void 0!==S&&S.pixelId?{value:null===S||void 0===S?void 0:S.pixelId,label:null===S||void 0===S?void 0:S.pixelId}:""),conversionEvent:(0,Xt.rz)(Xt.kg,null===S||void 0===S?void 0:S.conversionEvent)||"",adPlacements:(null===S||void 0===S?void 0:S.adPlacements)||{},customAndLookalikeAudiences:(null===S||void 0===S?void 0:S.customAndLookalikeAudiences)||[],excludedCustomAndLookalikeAudiences:(null===S||void 0===S?void 0:S.excludedCustomAndLookalikeAudiences)||[],leadFormId:(null===S||void 0===S?void 0:S.leadFormId)||"",adFormat:(null===S||void 0===S?void 0:S.adFormat)||"single",cards:(null===S||void 0===S?void 0:S.cards)||[],carouselOptions:(null===S||void 0===S?void 0:S.carouselOptions)||{multiShareOptimized:!0,multiShareEndCard:!1},advantageAudience:1===Number(null!==(A=null===S||void 0===S?void 0:S.advantageAudience)&&void 0!==A?A:0),advantageAudienceLocked:1===Number(null!==(b=null===S||void 0===S?void 0:S.advantageAudience)&&void 0!==b?b:0)},(()=>{this.getEstimatedDeliveryUsers()})),"carousel"!==(null===S||void 0===S?void 0:S.adFormat)&&(S.videoUrl?this.setState({videoFile:{publicUrl:null===S||void 0===S?void 0:S.videoUrl},thumbnailUrl:null!==S&&void 0!==S&&S.imageUrl?{publicUrl:null===S||void 0===S?void 0:S.imageUrl}:null}):this.setState({imageFile:{publicUrl:null===S||void 0===S?void 0:S.imageUrl}})),this.setState({originalCreativeData:{adName:null===S||void 0===S?void 0:S.adName,adCaption:null===S||void 0===S?void 0:S.adDescription,adHeadline:(null===S||void 0===S?void 0:S.headline)||(null===S||void 0===S?void 0:S.headlineDescription),adHeadlineDescription:(null===S||void 0===S?void 0:S.headlineDescription)||"",uploadType:S.videoUrl?"VIDEO_UPLOAD":"IMAGE_UPLOAD",videoUrl:null===S||void 0===S?void 0:S.videoUrl,imageUrl:null===S||void 0===S?void 0:S.imageUrl,adFormat:(null===S||void 0===S?void 0:S.adFormat)||"single",cards:(null===S||void 0===S?void 0:S.cards)||[],carouselOptions:(null===S||void 0===S?void 0:S.carouselOptions)||{multiShareOptimized:!0,multiShareEndCard:!1},greetingMessage:null===k||void 0===k?void 0:k.text,iceBreakers:I,switchChecked:w}}),""!==(null===S||void 0===S?void 0:S.audienceId)&&this.fetchSavedAudiences({audienceId:null===S||void 0===S?void 0:S.audienceId})})).catch((e=>{this.setState({isAdFetched:!0}),console.log(e)}))}getValidAdStopDate(e,t,a){const i=_()().startOf("day");e=e?_()(e).startOf("day"):e,a=a?_()(a).startOf("day"):a;const s=_()().startOf("day").add(1,"days"),n=_()().startOf("day").add(2,"days");if("DRAFT"===t){const t=_()().startOf("day").add(2,"days");if(!a)return a;
2if(e)return i.isSameOrBefore(a)||i.isBefore(e)&&e.diff(i)>2?e.toISOString():(i.isBefore(e)&&e.diff(i),t.toISOString());if(a.isSameOrBefore(i))return t.toISOString();if(a.isAfter(i))return a.add(2,"days").toISOString()}return e?e.isBefore(i)?s.toISOString():e.toISOString():i.isSame(a)?n.toISOString():s.toISOString()}getInitialDuration(e,t,a){e=e?_()(e).startOf("day"):e;const i=_()().startOf("day");if(a=a?_()(a).startOf("day"):a,"DRAFT"===t){if(!a)return a;if(e)return i.isSameOrBefore(a)?e.diff(a,"days"):i.isBefore(e)&&e.diff(i)>2?e.diff(i,"days"):(i.isBefore(e)&&e.diff(i),2);if(a.isSameOrBefore(i))return 2;if(a.isAfter(i))return 2}return e?e.isBefore(i)?1:a.isAfter(i)?a.diff(i,"days"):e.diff(i,"days"):i.isSame(a)?2:1}fetchAdAccount(){let{fbConnected:e,assistantId:t}=this.props.assistantDetails;const a=this.resolveAdAccountId();a&&t&&e&&(i.Z.post("".concat(W.URL,"/meta-ads/fetch-ad-account"),{assistantId:t,adAccountId:a}).then((e=>{this.setState({adAccountData:e.data})})).catch((e=>{console.log(e)})),this.getEstimatedDeliveryUsers())}convertScheduleStrings(e){const t=new Map;for(const s of e){const e=s.split("-"),a=parseInt(e[0],10),i=parseInt(e[1],10);a>=0&&a<=6&&i>=0&&i<=23&&(t.has(i)||t.set(i,[]),t.get(i).push(a))}const a=[],i=Array.from(t.keys()).sort(((e,t)=>e-t));for(const s of i){const e=60*s,i=60*(s+1),n=Array.from(new Set(t.get(s))).sort(((e,t)=>e-t));a.push({start_minute:e,end_minute:i,days:n,timezone_type:"viewer"===this.state.selectedTimezone.value?"USER":"ADVERTISER"})}return a}extractScheduledString(e){if(!e||!Array.isArray(e))return new Set;const t=new Set;for(let a of e){const e=a.start_minute/60,i=a.end_minute/60;for(let s=e;s<i;s++)for(let e of a.days)t.add("".concat(e,"-").concat(s))}for(let a=0;a<23;a++)for(let e=0;e<=7&&(7===e&&t.add("".concat(e,"-").concat(a)),t.has("".concat(e,"-").concat(a,"}")));e++);return t}isValidUrl(e){let t;try{t=new window.URL(e)}catch(a){return!1}return"http:"===t.protocol||"https:"===t.protocol}componentWillUnmount(){this.debouncedGetEstimatedDeliveryUsers&&this.debouncedGetEstimatedDeliveryUsers.cancel()}validateTimeSlotsAgainstDateRange(){var e;const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=null===(e=this.state.adAccountData)||void 0===e?void 0:e.timezone,{fromDate:i,toDate:s,selectedCells:n}=this.state;if(!s)return{invalidSlots:[]};const o=new Set;let r=_().tz(i,a).startOf("day");const l=_().tz(s,a).endOf("day");if(l.diff(r,"days")>=6)return{invalidSlots:[]};for(;r.isSameOrBefore(l);)o.add(r.day()),r.add(1,"day");const d=[],c=new Set;for(const p of n){const[e]=p.split("-");if("7"===e)continue;const t=parseInt(e,10);o.has(t)||(d.push(p),c.add(t))}if(d.length>0){const e=[...c].map((e=>t[e])).join(", "),s=[];for(r=_().tz(i,a);r.isSameOrBefore(l);)s.push(t[r.day()]),r.add(1,"day");const n=[...new Set(s)],o=1===n.length?n[0]:"".concat(n[0]," to ").concat(n[n.length-1]);return{invalidSlots:d,message:"You have scheduled this ad set to run on ".concat(e,". But the selected date range only includes ").concat(o,". Please change your date range or schedule.")}}return{invalidSlots:[]}}render(){var e,t,a,i,o,r,l,N,L,F,M,R,O,U,z,_;const{classes:W,history:G,assistantDetails:V}=this.props,{FromAge:Q,ToAge:q,adAccountData:Y,selectedPlatforms:J}=this.state,{accountId:X,accountName:$,currency:ee}=Y||{},te=window.innerWidth<532,ae="INR"===((null===V||void 0===V||null===(e=V.adSetupDetails)||void 0===e?void 0:e.selectedMetaAdAccountId)==X?V.currency:ee),ie=Xt.cU[ae?"INR":"USD"],se=ae?500:ie,oe=Xt.uy[ae?"INR":"USD"],re=[{title:"Where should people go after clicking your ad?",description:"This choice determines the campaign setup and the results you can optimise for.",component:(0,K.jsx)(Ha,{parentState:this.state,changeState:this.changeState,isLiveAD:this.state.isLiveAD,isDuplicateAd:this.isDuplicateAd,isAdFetched:this.state.isAdFetched,isCreateAd:this.isCreateAd,isEditPage:this.isEditAd,assistantId:null===(t=this.props)||void 0===t||null===(a=t.assistantDetails)||void 0===a?void 0:a.assistantId}),isCompleted:this.nextBtnDisableStatus(0)},{title:"Ad Targeting & Audience",description:"Select geo location in which you would like to ad. Select gender and age group of your audience",component:(0,K.jsx)(oi,{parentState:this.state,changeAge:this.changeZage,changeState:this.changeState,FromAge:Q,ToAge:q,heading:this.state.heading,geoLocations:this.state.geoLocations,excludedGeoLocations:this.state.excludedGeoLocations,selectedLocations:this.state.selectedLocations,excludedSelectedLocations:this.state.excludedSelectedLocations,linkMetaData:this.state.linkMetaData,selectedAdvanceTargets:this.state.selectedAdvanceTargets,getEstimatedDeliveryUsers:this.getEstimatedDeliveryUsers,selectedPlatforms:this.state.selectedPlatforms,isEditPage:this.isEditAd,deprecatedAdvanceTargets:this.state.deprecatedAdvanceTargets},this.state.keyThird),isCompleted:this.nextBtnDisableStatus(2)},{title:"Ad Budget",description:"Select daily budget you would like to spend on an ad. Select the time period for which an ad will run",component:(0,K.jsx)(ne,{parentState:this.state,adAccountData:this.state.adAccountData,handleToDateChange:this.handleToDateChange,handleFromDateChange:this.handleFromDateChange,changeState:this.changeState,isLiveAD:this.state.isLiveAD},this.state.keyThird),isCompleted:this.nextBtnDisableStatus(3)},{title:"Ad Creative",description:"Provide details to create ad creative and preview. Ad will have similar as shown in preview",component:(0,K.jsx)(Ba,{parentState:this.state,changeState:this.changeState,isLiveAD:null===(i=this.state)||void 0===i?void 0:i.isLiveAD,onGenerationStateChange:this.handleGenerationStateChange}),isCompleted:this.nextBtnDisableStatus(1)}];"ctwa"!==(null===(o=this.state.adType)||void 0===o?void 0:o.value)&&"whatsapp_status"!==(null===(r=this.state.adType)||void 0===r?void 0:r.value)||re.push({title:"Icebreakers (Optional)",description:"Set actions like ad level icebreakers for your ads and connect flows with your icebreaker messages",component:(0,K.jsx)(di.Z,{totalAdsCount:this.state.totalAdsCount,flows:this.props.flows,changeState:this.changeState,greetingMessage:this.state.greetingMessage,iceBreakers:this.state.iceBreakers,switchChecked:this.state.switchChecked,isDefaultIceBreakerOn:this.state.isDefaultIceBreakerOn,defaultGreetingMsg:this.state.defaultGreetingMsg,defaultIceBreakers:this.state.defaultIceBreakers,isLiveAD:this.state.isLiveAD,isAdFetched:this.state.isAdFetched,pageDetails:this.props.pageDetails,debouncedUpdateIceBreakers:this.debouncedUpdateIceBreakers,iceBreakerName:this.state.iceBreakerName,isIceBreakerSaving:this.state.isIceBreakerSaving,showSaveIceBreakerModal:this.state.showSaveIceBreakerModal,handleSaveIceBreaker:this.handleSaveIceBreaker,iceBreakerNodeId:this.state.iceBreakerNodeId,areIceBreakersModified:this.areIceBreakersModified,handleUpdateIceBreaker:this.handleUpdateIceBreaker,currSelectedSavedIceBreaker:this.state.currSelectedSavedIceBreaker,savedIceBreakers:this.state.savedIceBreakers}),isCompleted:this.nextBtnDisableStatus(4)});
2const{adCaption:le,adHeadline:de,imageFile:ce,videoFile:pe,thumbnailUrl:ue,uploadType:he}=this.state,{isLiveAD:me,isAdFetched:ge}=this.state,xe=!ge&&this.isEditAd||this.isEditAd&&ge&&me;return(0,K.jsxs)("div",{className:"".concat(W.root," ginger-page-root"),children:[(0,K.jsxs)(f.Z,{container:!0,justify:"center",alignItems:"center",className:"".concat(W.pageTitleContainer," ").concat(W.fullWidth," ginger-page-header"),children:[(0,K.jsx)(f.Z,{item:!0,children:(0,K.jsx)(A.Z,{children:(0,K.jsx)(b.Z,{style:{padding:0,marginRight:"0.5em",paddingBottom:te?"10px":"0"},component:S.Z,onClick:()=>{this.toggleDialog()},children:(0,K.jsx)(d.Z,{})})})}),(0,K.jsx)(f.Z,{item:!0,xs:!0,children:(0,K.jsxs)(I.Z,{variant:"h3",style:{whiteSpace:"nowrap",marginRight:"0.5em",paddingBottom:te?"10px":"0"},children:[this.props.match.params.adId?this.isDuplicateAd?"Duplicate ":"Edit ":"Create New "," ","Ad"]})}),(0,K.jsx)(A.Z,{style:{display:"flex",width:te?"100%":"auto"},children:(0,K.jsxs)(I.Z,{onClick:this.toggleAdCreditDialog,variant:"h4",style:{marginRight:"1em",cursor:"pointer"},children:["Remaining Ad Credit:"," ","USD"===this.props.assistantDetails.currency?"$":"\u20b9"," ",(this.props.assistantDetails.metaAdsCredit||0).toFixed(2)]})}),(0,K.jsx)(A.Z,{display:"flex",alignItems:"center",children:(0,K.jsx)(hi.default,{})})]}),(0,K.jsxs)(f.Z,{container:!0,justify:"center",children:[(0,K.jsxs)(f.Z,{item:!0,className:W.formContainer,children:[(0,K.jsxs)(f.Z,{container:!0,className:W.stepContainer,children:[!this.state.showPreview&&re.map(((e,t)=>{var a,i;return(0,K.jsxs)(f.Z,{className:"".concat(W.stepsContentBlock," ").concat(this.state.expandedSections.has(t)?"":W.stepsContentBlockPaddingRemove),style:e.isCompleted?{}:{borderColor:"#28c153"},onClick:e=>{var a,i;if(e.target.closest("button")||e.target.closest("input")||e.target.closest("textarea")||e.target.closest('[role="button"]')||e.target.closest('[role="combobox"]')||e.target.closest(".MuiAutocomplete-root")||e.target.closest(".MuiAutocomplete-inputRoot")||e.target.closest(".MuiAutocomplete-input")||e.target.closest(".MuiPopover-root")||e.target.closest(".MuiPaper-root")||e.target.closest('[role="listbox"]')||e.target.closest('[role="option"]')||e.target.closest(".MuiTextField-root")||e.target.closest(".MuiFormControl-root")||e.target.closest(".MuiSelect-root")||e.target.closest(".MuiCheckbox-root")||e.target.closest(".MuiRadio-root")||e.target.closest(".MuiSwitch-root")||e.target.closest("a")||e.target.closest("label")||e.target.closest("[data-content-area]"))return;if(4===t&&("ctwa"===(null===(a=this.state.adType)||void 0===a?void 0:a.value)||"whatsapp_status"===(null===(i=this.state.adType)||void 0===i?void 0:i.value))&&!this.state.switchChecked)return void(this.state.isLiveAD&&!this.isDuplicateAd&&this.setState({snackStatus:"warning",snackMessage:"You can't edit icebreakers once the ad is live",snack:!0}));if(!this.state.isAdFetched&&!this.isCreateAd&&0!==t)return;let s=new Set;this.state.expandedSections.has(t)?s=new Set:s.add(t),this.nextSection(t)?this.setState({expandedSections:s}):(2!==t&&2===t&&this.checkAudienceChanged()?this.setState({selectedAudience:null,audienceName:"",activeStep:t,expandedSections:s}):this.setState({activeStep:t,expandedSections:s}),3===t&&this.applyDefaultBudgets(se,oe)),2===t&&this.applyDefaultBudgets(se,oe)},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between"},children:[(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"top",gap:"20px"},children:[(0,K.jsxs)(A.Z,{style:{width:"26px",height:"26px",borderRadius:"8px",border:"1px solid #0a474c",color:"#0a474c",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",position:"relative"},children:[t+1,!e.isCompleted&&(0,K.jsx)(c.Z,{className:W.checked})]}),(0,K.jsxs)(A.Z,{children:[(0,K.jsx)(I.Z,{children:e.title}),(0,K.jsx)(I.Z,{variant:"h6",color:"textSecondary",style:{marginBottom:"24px"},children:e.description})]})]}),4===t&&("ctwa"===(null===(a=this.state.adType)||void 0===a?void 0:a.value)||"whatsapp_status"===(null===(i=this.state.adType)||void 0===i?void 0:i.value))&&(0,K.jsx)(j.ZP,{title:me&&!this.isDuplicateAd?"You can't change icebreaker status once the ad is live":"",children:(0,K.jsx)("span",{style:{display:"inline-block"},children:(0,K.jsx)(C.Z,{color:"primary",checked:this.state.switchChecked,disabled:xe,onCh
2ange:()=>{this.changeState("switchChecked",!this.state.switchChecked)}})})})]}),(0,K.jsx)("div",{"data-content-area":"true",onClick:e=>e.stopPropagation(),style:{transition:"all 0.2s",display:this.state.expandedSections.has(t)?"block":"none"},children:this.state.expandedSections.has(t)&&e.component}),this.state.expandedSections.has(t)&&(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"flex-end",gap:"16px"},children:["Ad Targeting & Audience"===e.title&&(0,K.jsx)(w.Z,{className:e.isCompleted||this.state.isLoading?"".concat(W.saveAudienceBtn," ").concat(W.disabledBtn):W.saveAudienceBtn,variant:"outlined",color:"primary",onClick:()=>this.setState({showSaveAudienceModal:!0}),disabled:e.isCompleted||this.state.isLoading,children:"Save Audience"}),t!==re.length-1&&(0,K.jsx)(A.Z,{children:(0,K.jsxs)(w.Z,{className:W.actionBtn2,onClick:e=>{e.stopPropagation(),1!==t&&2!==t||this.applyDefaultBudgets(se,oe);const a=new Set([t+1]);2==this.state.activeStep&&this.checkAudienceChanged()?this.setState({selectedAudience:null,audienceName:"",activeStep:t+1,expandedSections:a}):this.setState({activeStep:t+1,expandedSections:a})},startIcon:this.state.isLoading&&(0,K.jsx)(p.Z,{className:this.state.isLoading?W.rotationIcon:""}),children:["Next",this.state.isLoading?"":(0,K.jsx)(u.Z,{style:{fontSize:"16px"}})]})})]})]})})),(0,K.jsxs)(A.Z,{className:W.publishBtnContainer,children:[(0,K.jsx)(w.Z,{variant:"outlined",color:"primary",className:W.previewBtn,onClick:()=>this.changeState("showPreview",!this.state.showPreview),children:(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"3px"},children:[(0,K.jsx)("span",{children:this.state.showPreview?"Hide":"Preview"}),this.state.showPreview?(0,K.jsx)(h.Z,{style:{fontSize:"16px"}}):(0,K.jsx)(m.Z,{style:{fontSize:"16px",marginTop:"2px"}})]})}),(0,K.jsxs)(w.Z,{variant:"contained",color:"primary",className:W.publishBtn,startIcon:this.state.isLoading&&(0,K.jsx)(p.Z,{className:this.state.isLoading?W.rotationIcon:""}),onClick:()=>{this.state.isLiveAD&&!this.isDuplicateAd?this.isValidAd()&&this.editAd():this.isValidAd()&&this.createAd()},disabled:this.state.isLoading,children:[(0,K.jsx)("span",{children:me&&!this.isDuplicateAd?"Publish Changes":"Publish"}),!this.state.isLoading&&(0,K.jsx)(g.Z,{style:{fontSize:"16px",marginBottom:"2px"}})]})]})]}),(0,K.jsx)(f.Z,{style:{position:"sticky",top:"100px",alignSelf:"flex-start"},children:(0,K.jsxs)(f.Z,{item:!0,xs:!0,style:{marginBottom:"160px",justifyContent:"center",width:"100%",display:"grid"},children:[(window.innerWidth>700||window.innerWidth<=700&&this.state.showPreview)&&(0,K.jsx)(li.Z,{ctaButton:this.state.ctaButton,websiteUrl:this.state.websiteUrl,activeCardIndex:null!==(l=this.state.previewCardIndex)&&void 0!==l?l:0,onActiveCardChange:e=>this.changeState("previewCardIndex",e),payload:{adCaption:le,adHeadline:de,adHeadlineDescription:this.state.adHeadlineDescription,imageFile:ce,videoFile:pe,mediaType:"IMAGE_UPLOAD"===he?"IMAGE":"VIDEO",pageDetails:this.props.pageDetails,thumbnailUrl:(null===(N=this.state.thumbnailUrl)||void 0===N?void 0:N.publicUrl)||("string"===typeof this.state.thumbnailUrl?this.state.thumbnailUrl:""),adType:this.state.adType,ctaButton:this.state.ctaButton,adFormat:this.state.adFormat,cards:this.state.cards},maxHeight:"800px"}),(0,K.jsx)(K.Fragment,{children:window.innerWidth>700||window.innerWidth<=700&&this.state.showPreview?(0,K.jsx)(f.Z,{style:{width:"310px",marginTop:"24px",background:"white",boxShadow:"0 0 11px rgb(230,230,230)",borderRadius:"8px"},children:(0,K.jsxs)(A.Z,{style:{padding:"8px 16px"},children:[(0,K.jsx)(I.Z,{children:"Estimated reach"}),(0,K.jsx)(A.Z,{style:{display:"flex",justifyContent:"center",padding:"16px 0px"},children:this.state.estimatedReachLoading?(0,K.jsx)(k.Z,{size:28}):null!==(L=this.state.estimatedData)&&void 0!==L&&L.estimate_mau_lower_bound||null!==(F=this.state.estimatedData)&&void 0!==F&&F.estimate_mau_upper_bound?(0,K.jsx)(I.Z,{variant:"h3",component:"div",children:this.formatNumber((((null===(M=this.state.estimatedData)||void 0===M?void 0:M.estimate_mau_lower_bound)||0)+((null===(R=this.state.estimatedData)||void 0===R?void 0:R.estimate_mau_upper_bound)||0))/2,null===(O=this.props)||void 0===O||null===(U=O.assistantDetails)||void 0===U?void 0:U.currency)}):(0,K.jsxs)(A.Z,{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"10px",width:"100%"},children:[(0,K.jsx)(I.Z,{variant:"h4",children:"Unable To Fetch"}),(0,K.jsx)(x.Z,{onClick:()=>this.getEstimatedDeliveryUsers(),style:{cursor:"pointer"}})]})}),!this.state.estimatedReachLoading&&this.state.estimatedDailyResults&&(0,K.jsxs)(A.Z,{style:{borderTop:"1px solid #eeeeee",padding:"8px 0px",marginBottom:"8px"},children:[(0,K.jsx)(I.Z,{variant:"body2",color:"textSecondary",style:{marginBottom:"6px"},children:"Estimated daily results"}),[{label:"Reach",value:this.state.estimatedDailyResults.reach},{label:"Impressions",value:this.state.estimatedDailyResults.impressions},{label:fi[this.state.estimatedDailyResults.optimizationGoal]||"Results",value:this.state.estimatedDailyResults.actions}].map((e=>(0,K.jsxs)(A.Z,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"2px 0px"},children:[(0,K.jsx)(I.Z,{variant:"body2",children:e.label}),(0,K.jsx)(I.Z,{variant:"body2",style:{fontWeight:600},children:this.formatCompactCount(e.value)})]},e.label)))]}),(0,K.jsx)(I.Z,{variant:"h6",color:"textSecondary",style:{fontSize:"11px"},children:"The accuracy of these estimates relies on factors like past campaign data, budget, market data, targeting, and ad placements. They provide an idea of potential performance but do not guarantee results."})]})}):(0,K.jsx)(K.Fragment,{})})]})})]}),this.state.currSelectedFlowId&&this.props.isFlowPopupOpen&&(0,K.jsx)("div",{style:{position:"absolute",width:"100%",height:"100%",display:"flex",justifyContent:"center",alignItems:"center",bottom:0,left:0,zIndex:1e3,backgroundColor:"rgba(0, 0, 0, 0.5)"},children:(0,K.jsx)("div",{style:{zIndex:100,border:"none",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)",overflow:"hidden"},className:W.flowPageContainer,children:(0,K.jsx)(pi.default,{flowId:this.state.currSelectedFlowId,projectId:null===(z=this.props.assistantDetails)||void 0===z?void 0:z.assistantId,iceBreakerNodeId:this.state.iceBreakerNodeId,prevIceBreakerNodeId:this.state.prevIceBreakerNodeId,localIceBreakers:this.state.iceBreakers,currSelectedFlowId:this.state.currSelectedFlowId,adData:this.getAdDataPayload()})})})]}),(0,K.jsxs)(Z.Z,{open:this.state.showDialog,onClose:this.toggleDialog,maxWidth:"xs",children:[(0,K.jsxs)(A.Z,{className:W.dialogWrapper,children:[(0,K.jsx)(T.Z,{className:W.dialogTitle,children:(0,K.jsx)(I.Z,{variant:"h3",children:"Discard Ad"})}),(0,K.jsx)(v.Z,{className:W.icon,onClick:this.toggleDialog})]}),(0,K.jsx)(D.Z,{children:(0,K.jsx)(P.Z,{style:{color:"rgb(0,0,0,0.67)",fontSize:"16px",fontWeight:"500"},children:"If you discard this ad then all changes made by you will be lost. You can also save this ad as a draft and modify it at a later point."})}
2),(0,K.jsxs)(B.Z,{style:{paddingBottom:"16px",paddingRight:"24px"},children:[(0,K.jsx)(w.Z,{variant:"outlined",onClick:()=>{this.toggleDialog(),G.push(this.exitPath())},children:"Discard ad"}),(0,K.jsx)(w.Z,{color:"primary",variant:"contained",onClick:()=>{this.createDraftAd()},disabled:this.state.isLoading,autoFocus:!0,children:"Save to Draft"})]})]}),(0,K.jsxs)(Z.Z,{open:this.state.showSaveAudienceModal,onClose:()=>{var e;return this.setState({showSaveAudienceModal:!1,isUpdateMode:!1,audienceName:(null===(e=this.state.selectedAudience)||void 0===e?void 0:e.audienceName)||"",saveAudienceError:""})},children:[(0,K.jsxs)(A.Z,{className:W.saveAudienceDialogWrapper,style:{color:"#000000"},children:[(0,K.jsxs)(T.Z,{className:W.saveAudienceDialogTitle,children:[(0,K.jsx)(I.Z,{variant:"h3",children:"Save Audience Changes"}),(0,K.jsx)(I.Z,{variant:"h5",color:"textSecondary",style:{marginTop:"4px",wordBreak:"break-word"},children:"Update or rename your audience by entering a unique name below."})]}),(0,K.jsx)(v.Z,{className:W.saveAudienceCloseIcon,onClick:()=>{var e;return this.setState({showSaveAudienceModal:!1,isUpdateMode:!1,audienceName:(null===(e=this.state.selectedAudience)||void 0===e?void 0:e.audienceName)||"",saveAudienceError:""})}})]}),(0,K.jsx)(E.Z,{}),(0,K.jsx)(D.Z,{children:(0,K.jsxs)(f.Z,{container:!0,spacing:1,py:1,style:{color:"#000000",marginTop:"0px"},children:[(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,children:(0,K.jsx)("label",{style:{fontWeight:"400"},htmlFor:"audienceName",children:"Audience Name:"})}),(0,K.jsxs)(f.Z,{item:!0,xs:12,sm:9,children:[(0,K.jsx)("input",{id:"audienceName",type:"text",autoFocus:!0,value:this.state.audienceName,onChange:e=>this.setState({audienceName:e.target.value}),style:{width:"70%",border:this.state.saveAudienceError?"1px solid red":"none",padding:"8px",borderRadius:"4px",background:"#f0f0f0",outline:"none"}}),this.state.saveAudienceError&&(0,K.jsx)("div",{style:{color:"red",fontSize:"12px",marginTop:"4px"},children:this.state.saveAudienceError})]})]})}),(0,K.jsx)(E.Z,{style:{marginBottom:"4px"}}),(0,K.jsx)(D.Z,{style:{paddingTop:"0px",marginTop:"0px",color:"#000000"},children:(0,K.jsxs)(A.Z,{mt:3,children:[(0,K.jsx)(I.Z,{variant:"h4",fontWeight:"500",gutterBottom:!0,children:"Details"}),(0,K.jsx)(A.Z,{className:W.audienceDetails,children:(0,K.jsxs)(f.Z,{container:!0,spacing:1,children:[(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Locations:"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsx)(I.Z,{children:this.formatGeoLocationsSummary(this.state.geoLocations)})}),Object.entries(this.state.excludedGeoLocations||{}).some((e=>{let[t,a]=e;return"location_types"!==t&&(a||[]).length>0}))&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Excluded Locations:"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsx)(I.Z,{children:this.formatGeoLocationsSummary(this.state.excludedGeoLocations)})})]}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Gender:"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsx)(I.Z,{children:this.state.gender})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Age Range:"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsxs)(I.Z,{children:[this.state.FromAge," - ",this.state.ToAge]})}),!n().isEmpty(this.state.selectedAdvanceTargets)&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Advanced Targeting:"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsx)(I.Z,{children:this.state.selectedAdvanceTargets.map((e=>e.label)).join(", ")})})]}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Audience expansion:"})}
2),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsx)(I.Z,{children:this.state.advantageAudience?"Allow Meta to expand audience":"Use only my selected targeting"})}),!n().isEmpty(this.state.selectedPlatforms)&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(f.Z,{item:!0,xs:12,sm:3,style:{color:"#808080"},children:(0,K.jsx)(I.Z,{children:"Platforms:"})}),(0,K.jsx)(f.Z,{item:!0,xs:12,sm:9,className:W.audienceDetailValues,children:(0,K.jsx)(I.Z,{children:this.state.selectedPlatforms.map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(", ")})})]})]})})]})}),(0,K.jsx)(E.Z,{style:{marginTop:"4px"}}),(0,K.jsx)(B.Z,{children:null!==(_=this.state.selectedAudience)&&void 0!==_&&_._id?(0,K.jsxs)("div",{className:W.saveAudienceBtnContainer,children:[(0,K.jsx)(w.Z,{onClick:()=>{this.setState({isUpdateMode:!1},(()=>{this.handleSaveAudience()}))},className:W.dialogSaveBtn,color:"primary",variant:"outlined",disabled:this.state.savingAudience,children:"Save New Audience"}),this.checkAudienceChanged()&&(0,K.jsx)(w.Z,{onClick:()=>{this.setState({isUpdateMode:!0},(()=>{this.handleSaveAudience()}))},className:W.dialogSaveBtn,color:"primary",variant:"contained",disabled:this.state.savingAudience,children:"Update Audience"})]}):(0,K.jsx)(w.Z,{onClick:this.handleSaveAudience,color:"primary",variant:"contained",disabled:this.state.savingAudience,className:W.dialogSaveBtn,children:this.state.savingAudience?"Saving...":"Save Audience"})})]}),(0,K.jsx)(ht.A9,{open:this.state.snack,onClose:()=>{this.setState({snack:!1})},anchorOrigin:{vertical:"top",horizontal:"center"},severity:this.state.snackStatus,message:this.state.snackMessage}),!(0,s.isEmpty)(this.state.errorAction)&&(0,K.jsxs)(Z.Z,{open:!(0,s.isEmpty)(this.state.errorAction),onClose:()=>this.setState({errorAction:{}}),maxWidth:"sm",children:[(0,K.jsx)(T.Z,{children:(0,K.jsx)(I.Z,{variant:"h3",children:"Action Required"})}),(0,K.jsx)(D.Z,{children:(0,K.jsx)(P.Z,{style:{color:"rgb(0,0,0,0.87)"},children:this.state.errorAction.name})}),(0,K.jsxs)(B.Z,{style:{padding:"16px 24px"},children:[(0,K.jsx)(w.Z,{variant:"outlined",onClick:()=>this.setState({errorAction:{}}),children:"Close"}),this.state.errorAction.isInternalLink?(0,K.jsx)(w.Z,{color:"primary",variant:"contained",onClick:()=>{this.setState({errorAction:{}}),this.props.history.push(this.state.errorAction.link)},children:"Reconnect Meta"}):(0,K.jsx)(w.Z,{color:"primary",variant:"contained",href:this.state.errorAction.link,target:"_blank",rel:"noopener noreferrer",endIcon:(0,K.jsx)(y.Z,{}),children:"Open Link"})]})]}),(0,K.jsx)(H.default,{dialogOpen:this.state.adDialogOpen,toggleTemplateCreditDialog:this.toggleAdCreditDialog,assistantDetails:this.props.assistantDetails})]})}}const bi=(0,o.connect)((e=>({pageDetails:e.ads.pageDetails,assistantDetails:e.assistantDetails.data,iceBreakers:e.assistantDetails.iceBreakers,adSetupDetails:e.assistantDetails.adSetupDetails,flows:[...e.flow.flows],isFlowPopupOpen:e.assistantDetails.isFlowPopupOpen,pixels:e.audience.pixels,adAccountInsights:e.ads.adAccountInsights})),{updatePageDetails:fe.x5,updateAssistantStore:be.sJ,updateAdSetupStore:be.IR,createnewAds:fe.iA,FetchBudget:fe.FO,FetchDetails:fe.$4,FetchNames:fe.PE,getFlows:ci.Wf,createNode:ci.dS,createIceBreakerNode:ci.RQ,updateIceBreakers:be.wk,recreateAllIceBreakerNodes:ci.vZ,fetchPixels:za.tb,fetchAdAccountInsights:fe.Eq})(Ai),Si=(0,N.Z)((e=>({root:{height:"100%",overflowY:"scroll",background:"#f9f9f9"},formContainer:{width:"85%",minWidth:0,background:"transparent",display:"flex",padding:"20px 0px",justifyContent:"space-between",boxSizing:"border-box",gap:"20px",[e.breakpoints.down("sm")]:{flexDirection:"column",width:"100%",padding:"10px"}},stepContainer:{display:"flex",flexDirection:"column",gap:"16px",transition:"0.2s all",flex:1,minWidth:0},buttonContainer:{width:"100%"},pageTitleContainer:{position:"sticky",zIndex:101,top:0,boxSizing:"border-box",boxShadow:"0 0 11px rgb(230 230 230)",[e.breakpoints.down("md")]:{},[e.breakpoints.down("sm")]:{},background:"white",padding:"16px 24px"},pageTitleContainer2:{position:"sticky",zIndex:100,top:60,boxSizing:"border-box",paddingBottom:"1.2em",background:"rgb(251, 251, 251)"},stepLabel:{"& .MuiStepLabel-label":{marginTop:"4px"}},accordianCompeted:{borderBottom:"4px solid #27c152"},accordian:{borderRadius:8,transition:"0.3s",boxShadow:"0 0 11px rgb(230,230,230)"}
2,accordianSummary:{paddingLeft:"0px","&.Mui-expanded":{minHeight:"48px"},"& .MuiAccordionSummary-content.Mui-expanded":{margin:"0px"},"& .MuiAccordionSummary-content":{margin:"0px"}},accordianDetail:{padding:"20px 8px 8px 8px",display:"block"},stepIcon:{"& .MuiSvgIcon-root":{fontSize:"25px"}},stepTitle:{color:"darkslategrey",fontWeight:"bolder"},checked:{position:"absolute",bottom:-6,left:16,color:"#27c152",background:"white",borderRadius:20,fontSize:"20px"},watsappCheck:{color:"#27c152",marginRight:8},templates:{border:"1px solid lightgrey",borderRadius:8,overflowX:"auto",[e.breakpoints.up("sm")]:{padding:20},[e.breakpoints.down("sm")]:{padding:12}},addTemplate:{float:"right"},dialogTitle:{padding:"24px 0 8px 32px"},dialogContent:{paddingTop:0},razorpayConnect:{backgroundColor:"#3295fe",color:"white",padding:"6px 25px","&:hover":{backgroundColor:"#3295fe"}},stepsContentBlock:{background:"white",borderBottom:"4px solid transparent",padding:"20px 20px 20px 20px",borderRadius:"8px",minWidth:0,"&:hover":{boxShadow:"0 0 11px rgb(230,230,230)"},[e.breakpoints.down("sm")]:{padding:"10px"}},stepsContentBlockPaddingRemove:{padding:"20px 20px 0px 20px",[e.breakpoints.down("sm")]:{padding:"10px 10px 0px 10px"}},actionBtn2:{fontSize:"14px",fontWeight:"500",borderRadius:"5px",border:"1px solid ".concat(e.palette.primary.main),padding:"2px 12px",background:e.palette.primary.main,color:"white",height:"40px","&:hover":{cursor:"pointer",background:"#073135"}},disabledBtn:{background:"rgba(0, 0, 0, 0.12)",color:"rgba(0, 0, 0, 0.26)",border:"none"},dialogWrapper:{display:"flex",justifyContent:"space-between",alignItems:"center"},saveAudienceDialogWrapper:{display:"flex",justifyContent:"space-between",alignItems:"center",[e.breakpoints.down("xs")]:{alignItems:"flex-start",paddingRight:"24px",width:"100%",boxSizing:"border-box"}},icon:{marginRight:24,"&:hover":{cursor:"pointer"}},saveAudienceCloseIcon:{marginRight:24,"&:hover":{cursor:"pointer"},[e.breakpoints.down("xs")]:{display:"none"}},dialogTitle:{"& .MuiTypography-h6":{fontSize:20,fontWeight:600,color:"rgb(0,0,0,0.87)"}},rotationIcon:{animation:"$rotation 2s infinite linear"},"@keyframes rotation":{from:{transform:"rotate(0deg)"},to:{transform:"rotate(359deg)"}},snackbar:{zIndex:3e3,top:70},saveAudienceBtnContainer:{display:"flex",gap:"8px",[e.breakpoints.down("xs")]:{flexDirection:"column",width:"100%"}},dialogSaveBtn:{[e.breakpoints.down("xs")]:{width:"100%"}},saveAudienceBtn:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500"},audienceDetailValues:{[e.breakpoints.down("xs")]:{marginTop:"-8px"}},saveAudienceDialogTitle:{[e.breakpoints.down("xs")]:{maxWidth:"100%"}},flowPageContainer:{width:"calc(85% - 10px)",marginRight:"10px",height:"80%",borderRadius:"8px",[e.breakpoints.down("800")]:{width:"100vw",height:"100vh",marginRight:0,borderRadius:0}},rotationIcon:{animation:"$rotation 2s infinite linear"},publishBtnContainer:{display:"flex",justifyContent:"flex-end",[e.breakpoints.down(700)]:{justifyContent:"space-between",alignItems:"stretch",position:"absolute",bottom:"50px",width:"100%",right:0,gap:"10px",paddingTop:"10px",boxShadow:"0 -4px 6px -2px rgba(0, 0, 0, 0.05)",paddingBottom:"10px",background:"white",borderTop:"1px solid #e8e8e8",zIndex:99}},publishBtn:{display:"flex",maxWidth:"300px",paddingTop:"10px",paddingBottom:"10px",zIndex:100,alignItems:"center",[e.breakpoints.down(700)]:{width:"100%",maxWidth:"100%",marginRight:"10px"}},previewBtn:{display:"none",[e.breakpoints.down(700)]:{display:"flex",width:"100%",paddingTop:"10px",paddingBottom:"10px",zIndex:99,backgroundColor:"white",marginLeft:"10px",background:"white",gap:"5px",alignItems:"center"}}})))((0,l.withRouter)(bi))},36526:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"}),"Business")},43593:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"}),"Email")},1776:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"}),"Home")},38394:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.
216-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z"}),"Language")},48152:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"}),"Person")},28348:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c0-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"}),"PhoneInTalk")},26670:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M5 4v2h14V4H5zm0 10h4v6h6v-6h4l-7-7-7 7z"}),"Publish")},65963:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"}),"SearchOutlined")},87210:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"}),"Videocam")},32724:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M12 6c3.79 0 7.17 2.13 8.82 5.5-.59 1.22-1.42 2.27-2.41 3.12l1.41 1.41c1.39-1.23 2.49-2.77 3.18-4.53C21.27 7.11 17 4 12 4c-1.27 0-2.49.2-3.64.57l1.65 1.65C10.66 6.09 11.32 6 12 6zm-1.07 1.14L13 9.21c.57.25 1.03.71 1.28 1.28l2.07 2.07c.08-.34.14-.7.14-1.07C16.5 9.01 14.48 7 12 7c-.37 0-.72.05-1.07.14zM2.01 3.87l2.68 2.68C3.06 7.83 1.77 9.53 1 11.5 2.73 15.89 7 19 12 19c1.52 0 2.98-.29 4.32-.82l3.42 3.42 1.41-1.41L3.42 2.45 2.01 3.87zm7.5 7.5l2.61 2.61c-.04.01-.08.02-.12.02-1.38 0-2.5-1.12-2.5-2.5 0-.05.01-.08.01-.13zm-3.4-3.4l1.75 1.75c-.23.55-.36 1.15-.36 1.78 0 2.48 2.02 4.5 4.5 4.5.63 0 1.23-.13 1.77-.36l.98.98c-.88.24-1.8.38-2.75.38-3.79 0-7.17-2.13-8.82-5.5.7-1.43 1.72-2.61 2.93-3.53z"}),"VisibilityOffOutlined")},95470:(e,t,a)=>{a.d(t,{Z:()=>s});var i=a(47313);const s=(0,a(14214).Z)(i.createElement("path",{d:"M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z"}),"Work")},85497:(e,t)=>{var a=function(){if("undefined"!==typeof self)return self;if("undefined"!==typeof window)return window;if("undefined"!==typeof a)return a;throw new Error("unable to locate global object")}();e.exports=t=a.fetch,a.fetch&&(t.default=a.fetch.bind(a)),t.Headers=a.Headers,t.Request=a.Request,t.Response=a.Response}}]);
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.