useblocks 1.1.85-dev.3 → 1.1.85-dev.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -854,4 +854,4 @@ ${o}}`,n.appendChild(document.createTextNode(o));const i=t.querySelector('[data-
854
854
  </amp-accordion>
855
855
  </td></tr></table>`,Pc={image:"element_image","ai-image":"element_ai_image",text:"element_text",header:"element_heading",button:"element_button",spacer:"element_spacer","list-ul":"element_lists","list-ol":"element_lists",divider:"element_divider",social:"element_social",table:"element_table",countdown:"element_timer",video:"element_video","amp-carousel":"element_amp_carousel","amp-accordion":"element_amp_accordion","amp-form":"element_amp_form"};function yi(e){return Pc[e]??null}var vi=e=>Number(e)||void 0,Rc={colors:[],fonts:[],socials:[]},Kr=(e="entity")=>{const t=typeof globalThis<"u"?globalThis.crypto:void 0;if(t?.randomUUID)return t.randomUUID();const n=typeof performance<"u"?performance.now().toString(36).replace(".",""):String(Date.now());return`${e}-${Date.now().toString(36)}-${n}`},jc=()=>Kr("soc"),Oc=/^[a-z][a-z0-9+.-]*:/i,bi=e=>{const t=String(e??"").trim();return t?Oc.test(t)?t:`https://${t}`:""},Lc=e=>{const t=bi(e);if(!t)return!1;try{const n=new URL(t);return n.protocol==="https:"&&!!n.hostname}catch{return!1}},Mc=e=>[...e].filter(t=>t.url.trim()!=="").sort((t,n)=>t.order-n.order),Nc=e=>Mc(e).map(t=>({platform:t.icon_key,href:t.url,label:t.name,...t.icon_url?{iconSrc:t.icon_url}:{}})),Dc=/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i,Fc=/^#?([0-9a-f]{6})$/i,Yr=e=>{if(!e)return null;const t=String(e).trim().toLowerCase(),n=Fc.exec(t);if(n)return`#${n[1]}`;const o=Dc.exec(t);if(o){const[,i,s,c]=o;return`#${i}${i}${s}${s}${c}${c}`}return null},Ei=()=>Kr("bc"),Bc=/\.(woff2|woff|ttf|otf)$/i,$c=e=>{const t=Bc.exec(e.trim().toLowerCase());return t?`.${t[1]}`:null},Uc={".woff":"application/x-font-woff",".woff2":"application/font-woff2",".ttf":"font/sfnt",".otf":"font/sfnt"},zc={".woff":["application/x-font-woff","font/woff","application/font-woff"],".woff2":["application/font-woff2","font/woff2"],".ttf":["font/sfnt","application/font-sfnt","application/x-font-ttf","font/ttf","application/x-font-truetype"],".otf":["font/sfnt","application/font-sfnt","application/vnd.ms-opentype","application/x-font-opentype","font/otf","font/opentype"]},Gc=new Set(["","application/octet-stream","binary/octet-stream"]),Wc=e=>{const t=$c(e.name);if(!t)return e;const n=e.type.trim().toLowerCase();return zc[t].includes(n)||!Gc.has(n)?e:new File([e],e.name,{type:Uc[t],lastModified:e.lastModified})},Hc=()=>Kr("fnt"),qc=e=>e.family?.trim()||e.name.trim(),Vc=e=>e.filter(t=>t.source_url?.trim()).map(t=>({family:t.family?.trim()||t.name.trim(),source_url:t.source_url?.trim()??"",weight:t.weight?.trim()||"400",style:t.style??"normal"})),Kc=(e,t={})=>{const n=t.srcOverride?.trim()||e.source_url?.trim();if(!n||!t.srcOverride&&Si(e)||t.srcOverride&&r.isGoogleFontsCssUrl(n))return null;const o=t.familyOverride?.trim()||qc(e),i=e.weight?.trim()||"400",s=e.style??"normal";return`@font-face{font-family:${JSON.stringify(o)};src:url(${JSON.stringify(n)});font-weight:${i};font-style:${s};font-display:swap;}`},Yc=e=>e.source_kind?e.source_kind:r.isGoogleFontsCssUrl(e.source_url)?"google_stylesheet":e.file_name?.trim()?"uploaded":"remote_file",Si=e=>e.source_kind?e.source_kind==="google_stylesheet"||e.source_kind==="remote_stylesheet":r.isGoogleFontsCssUrl(e.source_url),wi="data-em-project-fonts-face",ki="data-em-project-font-link",Qc=e=>{const t=e.filter(n=>Si(n)).map(n=>n.source_url?.trim()??"").filter(Boolean);return[...new Set(t)]},Xc=e=>e.map(t=>Kc(t)).filter(t=>!!t).join(""),Jc=(e,t=document)=>{const n=Xc(e),{head:o}=t;let i=o.querySelector(`style[${wi}]`);if(!n){i?.remove();return}i||(i=t.createElement("style"),i.setAttribute(wi,""),o.appendChild(i)),i.textContent=n},Zc=(e,t=document)=>{const n=new Set(Qc(e)),{head:o}=t;o.querySelectorAll(`link[${ki}]`).forEach(i=>{const s=i.getAttribute("href")??"";n.has(s)?n.delete(s):i.remove()}),n.forEach(i=>{const s=t.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute("href",i),s.setAttribute(ki,""),o.appendChild(s)})},ed=(e,t=document)=>{Jc(e,t),Zc(e,t)},td=new Set(["normal","italic","oblique"]),Bv="[emailmaker] projectStyles:",Wt=e=>{},vt=e=>typeof e=="string"?e.trim():"",Ci=e=>!e||e.startsWith("//")?!1:e.startsWith("/")||e.startsWith("./")||e.startsWith("../")?!0:e.toLowerCase().startsWith("https://"),nd=e=>r.isGoogleFontsCssUrl(e)?"google_stylesheet":(e.split(/[?#]/)[0]??"").toLowerCase().endsWith(".css")?"remote_stylesheet":"remote_file",Qr=(e,t,n)=>e.length<=t?e:(Wt(`${n} list is capped at ${t} entries, ${e.length-t} dropped`),e.slice(0,t)),rd=(e,t)=>{const n=Yr(e?.hex);if(!n){Wt(`colors[${t}] skipped: "${String(e?.hex)}" is not a hex color`);return}return{id:vt(e.id)||Ei(),name:vt(e.name),hex:n,order:0}},od=(e,t)=>{const n=vt(e?.family),o=vt(e?.source_url);if(!n){Wt(`fonts[${t}] skipped: family is required`);return}if(!o){Wt(`fonts[${t}] skipped: source_url is required`);return}if(!Ci(o)){Wt(`fonts[${t}] skipped: source_url must be https or relative, got "${o}"`);return}const i=vt(e.style);return{id:vt(e.id)||Hc(),name:vt(e.name)||n,family:n,source_url:o,source_kind:nd(o),weight:vt(e.weight)||"400",style:td.has(i)?i:"normal",order:0}},id=(e,t)=>{const n=bi(e?.url);if(!n||!Lc(n)){Wt(`socials[${t}] skipped: url must be https, got "${String(e?.url)}"`);return}const o=vt(e.icon_key),i=vt(e.icon_url);let s;if(i&&Ci(i)?s=i:i&&Wt(`socials[${t}]: icon_url must be https or relative, got "${i}" — icon dropped`),!o&&!s){Wt(`socials[${t}] skipped: icon_key or icon_url is required`);return}return{id:vt(e.id)||jc(),name:vt(e.name),url:n,icon_key:o,...s?{icon_url:s}:{},enabled:!0,order:0}},Xr=e=>e.map((t,n)=>({...t,order:n})),sd=e=>({colors:Xr(Qr(e?.colors??[],32,"colors").map(rd).filter(t=>t!==void 0)),fonts:Xr(Qr(e?.fonts??[],20,"fonts").map(od).filter(t=>t!==void 0)),socials:Xr(Qr(e?.socials??[],20,"socials").map(id).filter(t=>t!==void 0))}),ad={tg:"telegram",yt:"youtube",yd:"yandex_zen",tt:"tiktok",pi:"pinterest",ig:"instagram",fb:"facebook",xa:"x",tw:"twitter"},Ti="vk",ld=new Set(r.EM_SOCIAL_SELECT_ORDER),cd=e=>ld.has(e),Ii=e=>{const t=String(e??"").trim().toLowerCase();return t?cd(t)?t:ad[t]??Ti:Ti},dd=e=>Ii(e),ud=new Set(["normal","italic","oblique"]),pd=new Set(["uploaded","remote_file","google_stylesheet"]),Pt=e=>(e??"").trim(),wn=e=>Pt(e)||void 0,Ai=e=>typeof e=="number"&&e>0?e:void 0,md=e=>ud.has(e)?e:void 0,fd=e=>pd.has(e)?e:void 0,gd=(e,t)=>{const n=Yr(Pt(e.hex));return n?{id:Pt(e.id)||Ei(),name:Pt(e.name),hex:n,order:e.order??t}:null},xi=(e,t=0)=>({id:Pt(e.id),name:Pt(e.name),source_url:wn(e.source_url),source_kind:fd(e.source_kind),file_name:wn(e.file_name),family:wn(e.family),weight:wn(e.weight),style:md(e.style),preview_url:wn(e.preview_url),storage_fallback:e.storage_fallback||void 0,font_size_px:Ai(e.font_size_px),line_height_px:Ai(e.line_height_px),order:e.order??t}),hd=(e,t)=>{const n=Pt(e.url);return n?{id:Pt(e.id),name:Pt(e.name),url:n,icon_key:Ii(Pt(e.icon_key)),enabled:e.enabled??!0,order:e.order??t}:null},rn=e=>[...e].sort((t,n)=>t.order-n.order),Pi=e=>e?{colors:rn((e.colors??[]).map(gd).filter(t=>t!==null)),fonts:rn((e.fonts??[]).map(xi)),socials:rn((e.socials??[]).map(hd).filter(t=>t!==null))}:Rc,_d=e=>e==="remote_stylesheet"?"remote_file":e,yd=e=>{const t={};return e.colors&&(t.colors=rn(e.colors).map(n=>({id:n.id,name:n.name.trim(),hex:Yr(n.hex)||n.hex}))),e.fonts&&(t.fonts=rn(e.fonts).map(n=>({id:n.id,name:n.name.trim(),source_url:n.source_url??"",source_kind:_d(Yc(n)),file_name:n.file_name??"",family:n.family??"",weight:n.weight??"",style:n.style??"",preview_url:n.preview_url??"",storage_fallback:n.storage_fallback??!1,font_size_px:n.font_size_px??0,line_height_px:n.line_height_px??0}))),e.socials&&(t.socials=rn(e.socials).map(n=>({id:n.id,name:n.name.trim(),url:n.url,icon_key:dd(n.icon_key),enabled:n.enabled}))),t},Ri="ProjectBrandStyles",Qt=r.createApi({reducerPath:"projectSettingsStylesApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),tagTypes:[Ri],endpoints:e=>({getProjectStyles:e.query({async queryFn({projectId:t},n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.stylesList({id:String(t)}));return"error"in o?{error:o.error}:{data:Pi(o.data)}},providesTags:(t,n,{projectId:o})=>[{type:Ri,id:String(o)}]}),updateProjectStyles:e.mutation({async queryFn({projectId:t,patch:n},o){const i=r.v2ResultOf(await r.getClientV2(h.getContainer(o)).projects.stylesPartialUpdate({id:String(t)},yd(n)));return"error"in i?{error:i.error}:{data:Pi(i.data)}},async onQueryStarted({projectId:t,patch:n},{dispatch:o,queryFulfilled:i}){const s=o(Qt.util.updateQueryData("getProjectStyles",{projectId:t},c=>Object.assign(c,n)));try{const{data:c}=await i;o(Qt.util.upsertQueryData("getProjectStyles",{projectId:t},c))}catch{s.undo()}}}),uploadProjectFont:e.mutation({async queryFn({projectId:t,file:n},o){const i=new FormData;i.append("file",Wc(n));const s=r.v2ResultOf(await r.getClientV2(h.getContainer(o)).request({path:`/projects/${String(t)}/styles/fonts`,method:"POST",body:i,secure:!0,type:r.ContentType.FormData,format:"json"}));return"error"in s?{error:s.error}:{data:xi(s.data)}},async onQueryStarted({projectId:t},{dispatch:n,queryFulfilled:o}){try{const{data:i}=await o;n(Qt.util.updateQueryData("getProjectStyles",{projectId:t},s=>{s.fonts=s.fonts.some(c=>c.id===i.id)?s.fonts.map(c=>c.id===i.id?i:c):[...s.fonts,i],s.fonts.sort((c,d)=>c.order-d.order)}))}catch{}}})})}),{useGetProjectStylesQuery:vd,useUpdateProjectStylesMutation:$v,useUploadProjectFontMutation:Uv}=Qt,ji=e=>{const t=r.useIntegratorConfigValue("projectStyles"),{data:n}=vd({projectId:e},{skip:!0});return(0,l.useMemo)(()=>sd(t),[t])},bd=2.5,Ed=({atom:e,onSelect:t,onDragStart:n,isDroppedAtom:o})=>{const i=(0,l.useCallback)(d=>t(d,e),[t,e]),s=(0,l.useCallback)(d=>n(d,e,o),[n,e,o]),c=(0,l.useCallback)(d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),t(d,e))},[t,e]);return(0,a.jsxs)("button",{type:"button",className:"ant-card-hoverable atoms__item "+e.className+(e.isLockedByPlan?" atoms__item_locked":""),draggable:!0,onClick:i,onKeyDown:c,onDragStart:s,"data-test-name":e.name,children:[(0,a.jsxs)("span",{className:"atom-image",children:[e.icon,e.isLockedByPlan&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:12,strokeWidth:bd,className:"atom-image__lock"})]}),(0,a.jsx)("span",{className:"atom-title",children:e.title})]})},Oi=()=>{const e=r.useI18n(),{__:t}=e,n=r.useAppConfig(),o=r.useProjectData(),i=r.useCurrentUserLocale()||"en_US",s=xt.useSetHtmlAtomInIframeHandler(),c=xt.useDragStartAtomToIframeHandler(),[d,u]=(0,l.useState)(!1),[p,f]=(0,l.useState)(0),g=r.useMessageService(),y=r.useServices(h.ATOMS_HANDLERS_ID),m=r.useEventEmitter(h.HANDLE_ATOM_INSERT_ID),E=r.usePlanFeatureLocks(),k=vi(o?.id),w=ji(k),v=w?Nc(w.socials):[],x=v.length>0?gi(v):Sc;let P=[];if(n.elementImageEnabled&&P.push({title:t("Image"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementImage",component:_.icons$ElementImage,size:24,strokeWidth:n.iconStrokeWidth}),html:dc,className:"",name:"image"}),n.elementAIimageEnabled&&P.push({title:t("AI image"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementImageAI",component:_.icons$ElementImageAI,size:24,strokeWidth:n.iconStrokeWidth}),html:uc,className:"ai",name:"ai-image"}),n.elementTextEnabled&&P.push({title:t("Text"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementText",component:_.icons$ElementText,size:24,strokeWidth:n.iconStrokeWidth}),html:pc(e),className:"",name:"text"}),n.elementHeaderEnabled&&P.push({title:t("Header"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementTitle",component:_.icons$ElementTitle,size:24,strokeWidth:n.iconStrokeWidth}),html:mc(e),className:"",name:"header"}),n.elementButtonEnabled&&P.push({title:t("Button"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementButton",component:_.icons$ElementButton,size:24,strokeWidth:n.iconStrokeWidth}),html:fc(e),className:"",name:"button"}),n.elementSpacerEnabled&&P.push({title:t("Spacer"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementSpacer",component:_.icons$ElementSpacer,size:24,strokeWidth:n.iconStrokeWidth}),html:yc,className:"",name:"spacer"}),n.elementListULEnabled&&P.push({title:t("List UL"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementListUL",component:_.icons$ElementListUL,size:24,strokeWidth:n.iconStrokeWidth}),html:gc(e),className:"",name:"list-ul"}),n.elementListOLEnabled&&P.push({title:t("List OL"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementListOL",component:_.icons$ElementListOL,size:24,strokeWidth:n.iconStrokeWidth}),html:hc(e),className:"",name:"list-ol"}),n.elementDividerEnabled&&P.push({title:t("Divider"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementDivider",component:_.icons$ElementDivider,size:24,strokeWidth:n.iconStrokeWidth}),html:_c,className:"",name:"divider"}),n.elementSocialEnabled&&P.push({title:t("Social media"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementSocial",component:_.icons$ElementSocial,size:24,strokeWidth:n.iconStrokeWidth}),html:x,className:"",name:"social"}),n.elementTableEnabled&&P.push({title:t("Table"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementTable",component:_.icons$ElementTable,size:24,strokeWidth:n.iconStrokeWidth}),html:wc(e),className:"",name:"table"}),n.elementCountdownEnabled&&P.push({title:t("Countdown"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementCountdown",component:_.icons$ElementCountdown,size:24,strokeWidth:n.iconStrokeWidth}),html:Tc(i),className:"",name:"countdown"}),n.elementVideoEnabled&&P.push({title:t("Video"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementVideo",component:_.icons$ElementVideo,size:24,strokeWidth:n.iconStrokeWidth}),html:Ic,className:"",name:"video"}),n.elementCarouselEnabled&&P.push({title:t("Carousel"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementCarousel",component:_.icons$ElementCarousel,size:24,strokeWidth:n.iconStrokeWidth}),html:Ac(e),className:"amp",name:"amp-carousel"}),n.elementAccordionEnabled&&P.push({title:t("Accordion"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementAccordion",component:_.icons$ElementAccordion,size:24,strokeWidth:n.iconStrokeWidth}),html:xc(e),className:"amp",name:"amp-accordion"}),n.elementFormEnabled&&P.push({title:t("Form"),icon:(0,a.jsx)(r.EmIcons,{icon:"ElementForm",component:_.icons$ElementForm,size:24,strokeWidth:n.iconStrokeWidth}),html:null,className:"amp",name:"amp-form"}),P=P.map(A=>({...A,fallbackTooltip:t("Coming soon"),planFeature:yi(A.name),isLockedByPlan:E(yi(A.name))})),y){const A={value:P};for(const O of y)O.execute(A);P=A.value}(0,l.useEffect)(()=>{const{dispose:A}=g.addListener(r.EVENT_TYPES.APPLICATION_ATOM_INSERTED,O=>{const z=P.find(B=>B.name===O);z&&m.fire(z)});return()=>A()},[g,P,m]);const K=(0,l.useCallback)(A=>{u(!0),f(A.planFeature?r.FEATURE_UPSELL_SLIDE[A.planFeature]:1)},[]),J=(0,l.useCallback)(A=>A.isLockedByPlan?(setTimeout(()=>K(A),1e3),!1):!0,[K]),N=(0,l.useCallback)((A,O)=>{if(O.isLockedByPlan){K(O);return}s(A,O)},[K,s]),L=(0,l.useCallback)((A,O,z)=>{c(A,O,z)},[c]);return(0,a.jsxs)("div",{className:"atoms",children:[(0,a.jsx)("div",{className:"atoms__list",children:(0,a.jsx)(_.ui_kit$Space,{wrap:!0,style:{justifyContent:"space-between",rowGap:10},children:P&&P.map((A,O)=>A.html?(0,a.jsx)(Ed,{atom:A,onSelect:N,onDragStart:L,isDroppedAtom:J},A.title+O.toString()):(0,a.jsx)(_.ui_kit$Tooltip,{title:A.fallbackTooltip||t("Coming soon"),placement:"top",children:(0,a.jsxs)("div",{className:"atoms__item atoms__item_inactive "+A.className,"data-test-name":A.name,children:[(0,a.jsx)("span",{className:"atom-image",children:A.icon}),(0,a.jsx)("span",{className:"atom-title",children:A.title})]},A.title+O.toString())},A.title+O.toString()))})}),(0,a.jsx)(r.PlanUpgradePrompt,{open:d,onCancel:()=>u(!1),initialSlide:p})]})};Oi.propTypes={};var Sd={full:{flexGrow:1},768:{width:171},425:{width:25},375:{width:28},320:{width:320}},Li={right:-12,top:4,zIndex:999,padding:0,position:"absolute"},wd=[{kind:"full",width:1200},{kind:"768",width:768},{kind:"425",width:425},{kind:"375",width:375},{kind:"320",width:320,showLabel:!0},{kind:"375",width:375},{kind:"425",width:425,control:"mobile"},{kind:"768",width:768,control:"desktop"},{kind:"full",width:1200}];function kd({kind:e,width:t,label:n,onSelect:o,onHover:i,children:s}){const c=(0,l.useCallback)(()=>i(e,n),[i,e,n]),d=(0,l.useCallback)(()=>i(null,""),[i]),u=(0,l.useCallback)(()=>o(t),[o,t]),p=(0,l.useCallback)(f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),o(t))},[o,t]);return(0,a.jsx)("div",{className:`device-width__${e}`,style:Sd[e],role:"button",tabIndex:0,"aria-label":n,onMouseEnter:c,onMouseLeave:d,onClick:u,onKeyDown:p,children:s})}function Cd({onSelectWidth:e,themeToggle:t}){const{__:n}=r.useI18n(),[o,i]=(0,l.useState)(""),[s,c]=(0,l.useState)(""),d={full:n("Desktop"),768:n("Small desktop – 768px"),425:n("Mobile L – 425px"),375:n("Mobile M – 375px"),320:n("Mobile S – 320px")},u=(0,l.useCallback)((p,f)=>{i(p?`device-width__${p}-hovered`:""),c(f)},[]);return(0,a.jsx)("div",{className:`email-pane__sizes ${o}`,children:(0,a.jsxs)("div",{className:"email-pane__width-selectors-wrapper",children:[(0,a.jsx)("div",{className:"device-width__theme",children:t}),wd.map((p,f)=>(0,a.jsxs)(kd,{kind:p.kind,width:p.width,label:d[p.kind],onSelect:e,onHover:u,children:[p.showLabel?s:null,p.control==="mobile"&&(0,a.jsx)(_.ui_kit$Tooltip,{title:n("Mobile view"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:"default",icon:(0,a.jsx)(r.EmIcons,{icon:"MobileOutlined",component:_.icons$MobileOutlined,size:16,strokeWidth:2}),size:"small",shape:"circle",style:Li})}),p.control==="desktop"&&(0,a.jsx)(_.ui_kit$Tooltip,{title:n("Desktop view"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:"default",icon:(0,a.jsx)(r.EmIcons,{icon:"DesktopOutlined",component:_.icons$DesktopOutlined,size:16,strokeWidth:2}),size:"small",shape:"circle",style:Li})})]},`${p.kind}-${f}`)),(0,a.jsx)("div",{className:"device-width__theme-placeholder"})]})})}var $e=zt.__toESM(r.require_prop_types()),Mi=h.createIdentifier$1("canvas.resizerBinder"),Td=h.createIdentifier$1("canvas.service"),zv={created:r.PHASES.canvasCreated,loaded:r.PHASES.canvasLoaded};function Id(e){return e.getInstance(Td)}function Ni(e){return{undo:()=>e.undo(),redo:()=>e.redo(),clear:()=>e.clear(),canUndo:()=>e.canUndo(),canRedo:()=>e.canRedo(),createSnapshot:()=>e.createSnapshot(),restoreSnapshot:t=>{e.restoreSnapshot(t)},getPast:t=>e.getPast(t).map(n=>({changes:n})),getFuture:t=>e.getFuture(t).map(n=>({changes:n}))}}var Ad={canUndo:!1,canRedo:!1},xd={undo:()=>{},redo:()=>{},clear:()=>{},canUndo:()=>!1,canRedo:()=>!1,createSnapshot:()=>{},restoreSnapshot:()=>{},getPast:()=>[],getFuture:()=>[]};function Jr(e){const t=r.useDocumentSessionContext(),{history:n}=e??t;return(0,l.useMemo)(()=>n?Ni(n):xd,[n])}function Pd(){const{history:e}=r.useDocumentSessionContext(),t=(0,l.useCallback)(i=>e?e.subscribe(i):()=>{},[e]),n=(0,l.useRef)(null),o=(0,l.useCallback)(()=>{if(!e)return Ad;const i={canUndo:e.canUndo(),canRedo:e.canRedo()},s=n.current;return s&&s.canUndo===i.canUndo&&s.canRedo===i.canRedo?s:(n.current=i,i)},[e]);return(0,l.useSyncExternalStore)(t,o)}var Di=2e3,Rd=10,jd="iframe_errors",Od=5;function Ld(e){const{__:t}=r.useI18n(),n=r.useMessageService(),o=Jr(),{error:i}=r.useNotification(),{document:s}=r.useDocumentSessionContext(),c=(0,l.useCallback)(()=>s?.getContent()??"",[s]),d=(0,l.useRef)(0),u=(0,l.useRef)(void 0),p=(0,l.useRef)(!1),f=r.useCurrentUser(),g=(0,l.useCallback)(m=>new Promise((E,k)=>{const w=n.addListener(r.EVENT_TYPES.SANDBOX_READY,()=>{w.dispose(),E()});m&&setTimeout(()=>{w.dispose(),k("timeout")})}),[n]),y=(0,l.useCallback)(m=>{g(Di).catch(E=>{}).finally(()=>{Promise.resolve().then(()=>{if(!p.current){if(++d.current){if(u.current){if(d.current<Od){o.restoreSnapshot(u.current);for(let E=0;E<d.current;E++)o.undo()}}else u.current=o.createSnapshot();n.send(r.EVENT_TYPES.RELOAD)}setTimeout(()=>{if(--d.current===0){u.current=null;const E=new Error(m.message);m.stack&&(E.stack=m.stack);const k=r.reportError(E,{origin:"iframe"}),w={past:o.getPast(Rd),future:o.getFuture(),errorResolved:!p.current,text:c(),message:m.message,stack:m.stack,userId:f?.id,entityId:e?.id,entityType:document.location.pathname.indexOf("emails")>0?"email":"block",sentryEventId:k};i({id:"IFRAME_ERROR",data:w,title:t("Something went wrong")}),h.RACS.post(jd,w).catch(v=>{}),p.current=!1}},Di)}})})},[o,c,i,f?.id,e?.id,t,g,n]);r.useListenPostMessage(r.EVENT_TYPES.APPLICATION_DOMPARSER_ERROR,y)}function Md(e,t){const n=JSON.stringify(t??{});Nd(e?.get().attributes.common_styles,n)||r.writeEmailAttributes(e,{common_styles:n})}function Nd(e,t){if(e===t)return!0;try{return h.deepEqual(JSON.parse(e||"{}"),JSON.parse(t||"{}"))}catch{return!1}}var Wn=Symbol("isIframeEvent");function Dd({children:e}){const[t,n]=(0,l.useState)(),[o,i]=(0,l.useState)(),[s,c]=(0,l.useState)(!1),d=r.useMessageService();return(0,l.useEffect)(()=>{if(t){const u=d.addListener(r.EVENT_TYPES.APPLICATION_IFRAME_DRAG_EVENT,p=>{if(p.type!=="drageleave"&&p.type!=="dragenter"){const f=t.getBoundingClientRect(),g=p.clientX+f.x+window.scrollX,y=p.clientY+f.y+window.scrollY,m=document.elementFromPoint(g,y);if(m){const E=new DataTransfer,k=new DragEvent(p.type,{clientX:g,clientY:y,cancelable:!0,bubbles:!0,dataTransfer:E});k[Wn]=!0,m.dispatchEvent(k)}}});return()=>u.dispose()}},[d,t]),(0,l.useEffect)(()=>{const u=f=>{f[Wn]||c(!0)},p=f=>{f[Wn]||c(!1)};return window.addEventListener("dragstart",u),window.addEventListener("dragend",p),()=>{window.removeEventListener("dragstart",u),window.removeEventListener("dragend",p)}},[o]),(0,l.useEffect)(()=>{const u=p=>{if(!p[Wn]){const f=o.getBoundingClientRect();d.send(r.EVENT_TYPES.SANDBOX_DRAG_EVENT,{value:p.dataTransfer?.getData("Text")||"",type:p.type,clientX:p.pageX-f.x-window.scrollX,clientY:p.pageY-f.y-window.scrollY})}};if(o)return o.addEventListener("dragenter",u),o.addEventListener("dragover",u),o.addEventListener("dragleave",u),o.addEventListener("drop",u),o.addEventListener("dragend",u),()=>{o.removeEventListener("dragenter",u),o.removeEventListener("dragover",u),o.removeEventListener("dragleave",u),o.removeEventListener("drop",u),o.removeEventListener("dragend",u)}},[o,d]),(0,a.jsxs)("div",{ref:n,children:[s&&(0,a.jsx)("div",{ref:i,className:"iframe-provider"}),e]})}var Fd=["colorBgBase","colorBgElevated","colorError","colorInfo","colorInfoBg","colorInfoBgHover","colorInfoBorder","colorInfoBorderHover","colorLink","colorPrimary","colorPrimaryBg","colorPrimaryBgHover","colorPrimaryBorder","colorPrimaryBorderHover"];function Bd(e){const t={};for(const n of Fd){const o=e[n];typeof o=="string"&&(t[n]=o)}return t}function Zr(e,t){const n=r.useMessageService(),o=t?.async??!1;(0,l.useEffect)(()=>{const i=o?n.addListenerAsync(r.EVENT_TYPES.RELOAD,e):n.addListener(r.EVENT_TYPES.RELOAD,e);return()=>i.dispose()},[n,e,o]),(0,l.useEffect)(()=>{},[e])}function $d(){const e=r.useMessageService(),{token:t}=(0,_.ui_kit$useToken)(),[n,o]=(0,l.useState)();(0,l.useEffect)(()=>{if(!h.deepEqual(n,t)){const s=e.onInit(()=>{e.send(r.EVENT_TYPES.SANDBOX_SET_THEME_VARIABLES,Bd(t)),o(t)});return()=>s.dispose()}},[t,n,o,e]);const i=(0,l.useCallback)(()=>{o(void 0)},[]);Zr(i)}var Ud={minHeight:600},zd="#pane-content-wrapper, .email-pane__col_preview, .preview-mode__pane-content";function Fi(e){e?.current?.resize?.()}var Bi=(0,l.forwardRef)(({className:e=null,email:t=null,handlerSendPosition:n=()=>{},surface:o,clip:i=null},s)=>{const c=r.useAppConfig(),d=r.useContainer(),u=o??(t?.hasOwnProperty("type")?"block":"email"),p=(0,l.useMemo)(()=>Id(d),[d]),f=(0,l.useMemo)(()=>p?.current(u),[p,u]),g=(0,l.useRef)(null),y=(0,l.useCallback)(()=>{r.mark(r.PHASES.canvasLoaded),Fi(s),n()},[n,s]);(0,l.useImperativeHandle)(s,()=>({getIframeElement:()=>p?.current(u)?.element,resize:()=>p?.current(u)?.resize()}),[p,u]),(0,l.useEffect)(()=>{if(!p)return;const w=g.current,v=i??w?.closest(zd)??null;return p.alignSurface(u,w,v),()=>p.alignSurface(u,null)},[p,u,i,c.sidePanelFloating]);const m=(0,l.useRef)(y);m.current=y,(0,l.useEffect)(()=>{if(!f)return;let w=!1;const v=()=>{w||m.current({target:f.element})};return f.ready().then(v).catch(()=>{window.requestAnimationFrame(()=>{w||f.ready().then(v).catch(()=>{})})}),()=>{w=!0}},[f]),$d(),Ld(t);const{document:E}=r.useDocumentSessionContext();(0,l.useEffect)(()=>{const w=r.subscribeToContent(E,()=>{Fi(s)});return()=>w.dispose()},[E,s]);const k=(0,l.useCallback)(w=>{const{operation:v,settings:x}=w.data;v===r.EVENT_TYPES.APPLICATION_COMMON_STYLES_UPDATE&&Md(E,x?.commonStyles)},[E]);return r.useListenPostMessage(k),(0,a.jsx)(Dd,{children:(0,a.jsx)("div",{ref:g,className:(0,rt.default)("email-preview",e),id:"email_iframe_slot",style:Ud})})});Bi.propTypes={className:$e.default.string,surface:$e.default.oneOf(["email","block","preview"]),email:$e.default.shape({html:$e.default.string}),handlerSendPosition:$e.default.func,clip:$e.default.object};var eo=new Map,Gd=new Map;function Wd(e,t){e.set(t,(e.get(t)??0)+1)}function Hd(e,t){const n=e.get(t)??0;n<=1?e.delete(t):e.set(t,n-1)}function $i(e,t){return(e.get(t)??0)>0}function qd(e){return $i(eo,e)||$i(Gd,e)}function Vd(e){Wd(eo,e);let t=!1;return{dispose(){t||(t=!0,Kd(e))}}}function Kd(e){Hd(eo,e)}function Yd(e,t){return Xd([...e.changes].sort((n,o)=>n.rangeOffset-o.rangeOffset).map(n=>({start:n.rangeOffset,end:n.rangeOffset+n.rangeLength,text:n.text})),t)}function Qd(e,t){return e.map(n=>{const o=t.getPositionAt(n.oldPosition),i=t.getPositionAt(n.oldEnd);return{text:n.newText,range:{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:i.lineNumber,endColumn:i.column}}})}function Xd(e,t){let n=0;return e.map(({start:o,end:i,text:s})=>{const c=new r.TextChange(o,t.slice(o,i),o+n,s);return n+=s.length-(i-o),c})}var Ui=new WeakMap;function Jd(e){const t=Ui.get(e);if(t)return t;const n=Ml(e);return Ui.set(e,n),n}var zi="monaco";function Zd(e,t){(0,l.useEffect)(()=>{if(!e||!t)return;const n=Jd(e);let o=!1;const i=d=>{o=!0;const u=Vd(t);try{d()}finally{u.dispose(),o=!1}},s=n.attach({id:zi,apply(d){return t.getValue()!==d&&i(()=>t.setValue(d)),Promise.resolve()},applyChanges(d){return i(()=>t.applyEdits(Qd(d,t))),Promise.resolve()}}),c=t.onDidChangeContent(d=>{if(o)return;const u=qd(t)?"remote":"user";n.mutateFrom(zi,{changes:Yd(d,e.getContent())},{source:u})});return()=>{s.detach(),c.dispose()}},[e,t])}function eu(e,t){const[n,o]=(0,l.useState)(void 0),i=(0,l.useRef)(!1),{error:s}=r.useNotification(),{__:c}=r.useI18n(),d=(0,l.useRef)(t);d.current=t;const u=(0,l.useRef)({error:s,__:c});u.current={error:s,__:c},(0,l.useEffect)(()=>{if(!e||n||i.current)return;i.current=!0;let f=!1;return d.current().then(g=>{if(f){g.dispose();return}o(g)}).catch(()=>{const{error:g,__:y}=u.current;g({id:"CODE_EDITOR_LOAD_FAILED",title:y("Failed to load the code editor")})}).finally(()=>{i.current=!1}),()=>{f=!0}},[e,n]);const p=(0,l.useRef)(void 0);return p.current=n,(0,l.useEffect)(()=>()=>{p.current?.dispose()},[]),n}var Hn;function to(){return Hn===void 0&&(Hn=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/ddb5a35d.js")),void 0,{}.url).catch(e=>{throw Hn=void 0,e})),Hn}function tu(){return to().then(e=>e.ensureMonaco())}var nu=r.lazyRoute(()=>to().then(e=>({default:e.MonacoEditor}))),ru=()=>to().then(e=>e.loadEditorModel()),ou={height:"100%"};function iu(e){const t=eu(!0,ru),{document:n}=r.useDocumentSessionContext();return(0,l.useEffect)(()=>{},[]),(0,l.useEffect)(()=>{},[t]),Zd(n,t),(0,a.jsx)(r.EditorModelContext.Provider,{value:t,children:(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$Flex,{justify:"center",align:"center",style:ou,children:(0,a.jsx)(_.ui_kit$Spin,{size:"large"})}),children:(0,a.jsx)(nu,{...e})})})}var su=({elementPath:e})=>{const{_x:t}=r.useI18n(),n=r.useDispatch(),o=r.useMessageService(),i=r.useAppConfig(),{blockId:s}=r.useRouteParams(),c=r.useEditorProjectId(),d=r.useRouteEmailId(),u=r.useProjectData(),p=r.usePushToDataLayer(),f=(0,l.useCallback)(x=>{o.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_ACTIVE_SET,index:x})},[o]),g=(0,l.useCallback)(x=>{let P="element";x?.target?.closest("svg")||x?.target?.closest(".anticon")||x?.target?.closest('[class*="icon"]')?P="icon":x?.target?.textContent&&!x?.target?.closest("svg")&&!x?.target?.closest(".anticon")&&(P="text"),n(r.setActiveSettingsTab(r.STYLES)),o.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:!1}),o.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_ACTIVE_RESET}),p({event:"click",action:"click_breadcrumb_email",email_id:d||s,project_id:u?.id||c,click_target:P})},[o,n,p,d,s,c,u]),y={title:(0,a.jsxs)("span",{onClick:g,children:[(0,a.jsx)(r.EmIcons,{icon:"Email",component:_.icons$Email,size:16,strokeWidth:i.iconStrokeWidth})," ",t("Email","letter")]})},[m,E]=(0,l.useState)([y]),k=(0,l.useCallback)(x=>{o.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_HOVER_SET,index:x})},[o]),w=x=>{if(x.includes("em-element-path-item-text"))return(0,a.jsx)(r.EmIcons,{icon:"ElementText",component:_.icons$ElementText,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-image"))return(0,a.jsx)(r.EmIcons,{icon:"ElementImage",component:_.icons$ElementImage,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-link"))return(0,a.jsx)(r.EmIcons,{icon:"LinkOutlined",component:_.icons$LinkOutlined,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-atom"))return(0,a.jsx)(r.EmIcons,{icon:"Atom",component:_.icons$Atom,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-column"))return(0,a.jsx)(r.EmIcons,{icon:"Column",component:_.icons$Column,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-block"))return(0,a.jsx)(r.EmIcons,{icon:"Block",component:_.icons$Block,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-group"))return(0,a.jsx)(r.EmIcons,{icon:"Group",component:_.icons$Group,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-button"))return(0,a.jsx)(r.EmIcons,{icon:"ElementButton",component:_.icons$ElementButton,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-table"))return(0,a.jsx)(r.EmIcons,{icon:"ElementTable",component:_.icons$ElementTable,size:16,strokeWidth:i.iconStrokeWidth});if(x.includes("em-element-path-item-amp"))return(0,a.jsx)(r.EmIcons,{icon:"AMP",component:_.icons$AMP,size:16,strokeWidth:i.iconStrokeWidth})},v=(0,l.useCallback)((x,P)=>{const K=J=>{let N="element";J.target.closest("svg")||J.target.closest(".anticon")||J.target.closest('[class*="icon"]')?N="icon":J.target.textContent&&!J.target.closest("svg")&&!J.target.closest(".anticon")&&(N="text");const L=e?.[P],A=L?.className?.replace("em-element-path-item-","")||"unknown";p({event:"click",action:"click_breadcrumb_element",email_id:d||s,project_id:u?.id||c,element_type:A,element_index:P,element_title:L?.title||"",click_target:N}),f(P)};return(0,a.jsxs)("span",{className:x.className,onClick:K,onMouseOver:()=>{k(P)},children:[w(x.className)," ",x.title]})},[f,k,e,p,d,s,c,u]);return(0,l.useEffect)(()=>{if(e){const x=e.map((P,K)=>({title:v(P,K)}));E([{title:(0,a.jsxs)("span",{onClick:g,children:[(0,a.jsx)(r.EmIcons,{icon:"Email",component:_.icons$Email,size:16,strokeWidth:i.iconStrokeWidth})," ",t("Email","letter")]})},...x])}},[e,v,g,t]),(0,a.jsx)(a.Fragment,{children:(0,a.jsx)(_.ui_kit$Breadcrumb,{items:m,type:"separator",separator:""})})};function au(){const{document:e}=r.useDocumentSessionContext(),t=(0,l.useCallback)(o=>e?e.subscribe(o):()=>{},[e]),n=(0,l.useCallback)(()=>e?.getContent()??"",[e]);return(0,l.useSyncExternalStore)(t,n)}var lu=({fallbackHtml:e})=>{const{__:t}=r.useI18n(),n=au(),o=(0,l.useMemo)(()=>r.getCodeSize(n||e||""),[e,n]),i=r.formatCodeSize(o),s=r.isCodeSizeExceeded(o);return(0,a.jsx)(_.ui_kit$Tooltip,{placement:"left",title:t(s?"The code size exceeds the recommended value 90kB":"Code size"),children:(0,a.jsx)("span",{className:(0,rt.default)("email-pane__code-size",{"email-pane__code-size_exceeded":s}),children:i})})};function Gi(e){const{limits:t,isLoaded:n}=r.useProjectPlanLimits();return r.useProjectData(),(0,l.useMemo)(()=>({isLocked:!1,state:{state:"allowed"},isPlanDataReady:n,exceeded:null}),[!1,e,t,n])}var cu=({open:e,onClose:t})=>{const{__:n}=r.useI18n();return(0,a.jsxs)(_.ui_kit$Modal,{open:e,centered:!0,closable:!1,mask:{closable:!1},footer:null,width:520,className:"browser-extension-warning-modal",title:n("Browser extension detected"),onCancel:t,children:[(0,a.jsx)("p",{children:n("A browser extension (for example, Urban VPN Proxy or similar ad blockers/VPN tools) is injecting code into the email preview. This can corrupt your template when saving.")}),(0,a.jsx)("p",{children:n("We removed the injected code automatically. To avoid this issue, disable the extension for this site or use the editor in an incognito window without extensions.")}),(0,a.jsx)("div",{className:"browser-extension-warning-modal__footer",children:(0,a.jsxs)(_.ui_kit$Button,{type:"primary",onClick:t,children:[n("Got it")," "]})})]})},du={closable:!1},uu=({open:e,onClose:t})=>{const{__:n}=r.useI18n();return(0,a.jsxs)(_.ui_kit$Modal,{open:e,centered:!0,closable:!1,mask:du,footer:null,width:520,className:"browser-translate-warning-modal",title:n("Browser translation detected"),children:[(0,a.jsx)("p",{children:n("Browser page translation (for example, Google Translate) is active. It can break the editor and cause errors when saving.")}),(0,a.jsx)("p",{children:n("To avoid this issue, disable translation for this site in your browser settings or turn off auto-translate.")}),(0,a.jsx)("div",{className:"browser-translate-warning-modal__footer",children:(0,a.jsx)(_.ui_kit$Button,{type:"primary",onClick:t,children:n("Got it")})})]})},pu=h.createIdentifier$1("prewarm.editorVisible");function mu(e){if(typeof requestAnimationFrame!="function"){setTimeout(e,0);return}requestAnimationFrame(()=>requestAnimationFrame(e))}function fu(e={}){const t=e.paint??mu;let n=!1,o=!1,i=!1,s=!1,c=!1;const d=[],u=()=>{c||s||!n||!o||!i||(s=!0,t(()=>{c=!0,r.mark(r.PHASES.editorVisible);for(const p of d.splice(0))p()}))};return{noteShellVisible(){n=!0,u()},notePagePainted(){o=!0,u()},noteContentShown(){i=!0,u()},whenVisible(p){if(c){p();return}d.push(p)},contentShown:()=>i}}function Ht(e){return e.getOrCreateInstance(pu,()=>fu())}function kn(e){const t=(0,l.useRef)(!1);return e&&(t.current=!0),t.current}var Wi=4e3;function Xt(e){const t=window.requestIdleCallback;if(typeof t=="function"){t(e,{timeout:Wi});return}window.setTimeout(e,Wi)}var qn,no;function ro(){return qn===void 0&&(qn=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/b97bd382.js")).then(e=>e.panels_exports).then(e=>(no=e,e),e=>{throw qn=void 0,e}),void 0,{}.url)),qn}function gu(e){(0,l.useEffect)(()=>{Ht(e).whenVisible(()=>{Xt(()=>{ro().catch(()=>{})})})},[e])}function ut(e){const t=r.lazyRoute(()=>ro().then(o=>({default:o[e]})),"panels");function n(o){const[i]=(0,l.useState)(()=>no?no[e]:t);return(0,l.createElement)(i,o)}return n.displayName=`PanelDoor(${String(e)})`,n}var Hi=ut("EmailProperties"),hu=ut("SelectedElementPanel"),_u=ut("EmailSettings"),yu=ut("EmailStyles"),vu=ut("DiscussAi"),bu=ut("Optimise"),Eu=ut("FileManagerDataLayer"),Su=ut("BlocksSearch"),wu=ut("Discuss"),ku=ut("HistoryPanel"),Cu=ut("AddNewBlockModal"),Tu=ut("AddAllBlocksModal"),Iu=ut("SendTestEmailModal"),Au=ut("SaveBlockBtn"),oo=ut("LimitUpgradeModal"),xu={height:"100%"},Pu=()=>{const e=r.useContainer(),t=r.isImageCenterModal(r.useSelector(r.selectActiveModal$1)),[n,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{e&&Ht(e).whenVisible(()=>o(!0))},[e]),kn(n||t)?(0,a.jsx)(l.Suspense,{fallback:t?(0,a.jsx)(_.ui_kit$PageLoader,{style:xu}):null,children:(0,a.jsx)(Eu,{})}):null},Vn;function Ru(){return Vn===void 0&&(Vn=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/3bd1b21b.js")),void 0,{}.url).catch(e=>{throw Vn=void 0,e})),Vn}function Cn(e){return r.lazyRoute(()=>Ru().then(t=>({default:t[e]})),"form-panels")}var Gv=Cn("FormEditorCalendarPanel"),Wv=Cn("FormEditorCheckboxPanel"),Hv=Cn("FormEditorDropdownListPanel"),qv=Cn("FormEditorInputPanel"),Vv=Cn("FormEditorRadioPanel");function ju(){try{const e=new URLSearchParams(window.location.search).get("deferChrome");return e===null?void 0:e!=="0"&&e!=="false"}catch{return}}function Ou(e,t){const n=ju()??r.readLocalToggle(r.LOCAL_STORAGE_ITEMS.em_defer_chrome);if(n!==void 0)return n;const o=t?.deferEditorChrome;return typeof o=="boolean"?o:o&&typeof o=="object"?o[e]??!0:{}.REACT_APP_DEFER_EDITOR_CHROME_DEFAULT!=="false"}function qi(e){const t=r.useAppConfig(),[n,o]=(0,l.useState)(()=>!Ou(e,t));return(0,l.useEffect)(()=>{if(n)return;let i=0;const s=window.requestAnimationFrame(()=>{i=window.requestAnimationFrame(()=>(0,l.startTransition)(()=>o(!0)))});return()=>{window.cancelAnimationFrame(s),window.cancelAnimationFrame(i)}},[n]),n}var Vi=r.createState({blocksTotal:null,blocksTotalPages:null,parentEmailBlocksTotal:null,parentEmailBlocksTotalPages:null,templateBlocks:[],templateBlocksTotal:null,templateBlocksTotalPages:null,elementsView:r.CARDS,elementsList:[],customFolders:{},blocksTrashTotal:0,elementsTrashList:[]}),Kn="blocksPageSlice",io=r.createSlice({name:Kn,initialState:Vi,reducers:{resetPagesAndTotal:()=>Vi,resetElementsList:e=>{e.elementsList=[]},toggleElementsView:(e,t)=>{e.elementsView=t.payload},removeBlockFromList:(e,{payload:t})=>{const n=e.customFolders;t.folder!=="all"&&n[t.folder]?.list&&(n[t.folder]={...n[t.folder],list:n[t.folder].list.filter(o=>o.id!==t.emailId),total:n[t.folder].total-1},e.customFolders=n)}},extraReducers:e=>{e.addMatcher(r.blocksApi.endpoints.getBlocks.matchFulfilled,(t,{meta:n,payload:o})=>{const i=n.baseQueryMeta?.response.headers.get("X-WP-Total")||o?.length,s=n.arg.originalArgs?.status==="trash",c=!!n.arg.originalArgs?.name?.length,d=n.arg.originalArgs?.page,u=n.arg.originalArgs?.folderTag||n.arg.originalArgs?.tags?.[0];s?(c||(t.blocksTrashTotal=i),t.elementsTrashList=o):u?t.customFolders={...t.customFolders,[u]:{list:o,page:d,total:i}}:(t.blocksTotal=i,t.elementsList=o)}),e.addMatcher(r.blocksApi.endpoints.getParentEmailBlocks.matchFulfilled,(t,{meta:n,payload:o})=>{const i=n.baseQueryMeta?.response.headers.get("X-WP-Total")||o?.length||null,s=n.baseQueryMeta?.response.headers.get("X-WP-TotalPages");t.parentEmailBlocksTotal=i,t.parentEmailBlocksTotalPages=s}),e.addMatcher(r.blocksApi.endpoints.getTemplateBlocks.matchFulfilled,(t,{meta:n,payload:o})=>{const i=n.baseQueryMeta?.response.headers.get("X-WP-Total")||o?.length||null,s=n.baseQueryMeta?.response.headers.get("X-WP-TotalPages");t.templateBlocks=o,t.templateBlocksTotal=i,t.templateBlocksTotalPages=s}),e.addMatcher(r.blocksApi.endpoints.editBlock.matchFulfilled,(t,{payload:n})=>{t.elementsList.map(o=>o.id?.toString()===n.id?.toString()?Object.assign(o,{lock:n.lock,title:n.title,blocktags:n.blocktags}):o)})}}),{resetPagesAndTotal:Kv,resetElementsList:Yv,toggleElementsView:Qv,removeBlockFromList:Xv}=io.actions,Lu=e=>e[Kn].blocksTotal,Mu=e=>e[Kn].templateBlocksTotal,Nu=e=>e[Kn].parentEmailBlocksTotal,Du=class extends Error{label;timeoutMs;constructor(e){super(`[sandbox:ready] iframe handshake timed out after ${e}ms`),this.name="SandboxReadyTimeoutError",this.label="sandbox:ready",this.timeoutMs=e}};function Ki(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.isInited=="function"&&typeof t.getTarget=="function"&&typeof t.onInit=="function"}function Yi(e,t,n){return e.isInited()&&e.getTarget()?Promise.resolve():(h.throwIfAborted(n),new Promise((o,i)=>{let s=!1,c,d;const u=f=>{s||(s=!0,c!==void 0&&(clearTimeout(c),c=void 0),d?.dispose(),n?.removeEventListener("abort",p),f())},p=()=>{u(()=>i(h.createAbortError(n?.reason)))};if(d=e.onInit(()=>{e.isInited()&&e.getTarget()&&u(()=>o())}),e.isInited()&&e.getTarget()){u(()=>o());return}t>0&&(c=setTimeout(()=>{u(()=>i(new Du(t)))},t)),n?.addEventListener("abort",p)}))}var Fu=()=>{try{return localStorage.getItem("em-debug-project-fonts")==="1"}catch{return!1}},Tn=(e,t)=>{Fu()},Bu=e=>[...e].sort((t,n)=>t.order-n.order).map(t=>t.hex.toUpperCase()),$u=(e,t)=>{const n=Array.isArray(e?.usedColors)?e.usedColors:[],o=new Set,i=[];for(const s of[...n,...Bu(t)]){const c=String(s??"").trim().toUpperCase();!c||o.has(c)||(o.add(c),i.push(s))}return{...e,usedColors:i}},Qi,Uu=e=>{Qi=e},Yn=e=>$u(e,Qi?.colors??[]),zu=e=>{const t=r.useMessageService(),n=ji(e),[o,i]=(0,l.useState)("");(0,l.useEffect)(()=>{Uu(n);const c=n?.fonts??[];r.setCachedProjectFonts(c),ed(c),Tn("parent: cache + host @font-face synced",{projectId:e,fontsCount:c.length,families:c.map(d=>d.family?.trim()||d.name)})},[n,e]),(0,l.useEffect)(()=>{const c=n?.fonts??[],d=Vc(c),u=JSON.stringify(d);if(u===o){Tn("parent: iframe send skipped (unchanged)",{entriesCount:d.length});return}Tn("parent: scheduling SANDBOX_SET_PROJECT_FONTS",{entriesCount:d.length,entries:d});const p=()=>{t.send(r.EVENT_TYPES.SANDBOX_SET_PROJECT_FONTS,d),i(u),Tn("parent: SANDBOX_SET_PROJECT_FONTS sent",{entriesCount:d.length})};if(t.inited){p();return}const f=t.onInit(()=>{p()});return()=>f.dispose()},[t,n,o]);const s=(0,l.useCallback)(()=>{Tn("parent: iframe reload — will resend project fonts map"),i("")},[]);Zr(s)};function Gu(e,t){const n=e,o=n?.data?.operation!==void 0?n.data:n;if(o?.operation===t)return o.file instanceof File?o.file:void 0}async function Wu(e,t){const{userId:n,folderId:o}=t.readContext();if(n==null||o==null||o==="")return{status:"skipped"};try{const i=await t.prepare(e),s=await t.upload({user_id:n,folder:String(o),file:i});if(s.error)return{status:"failed",error:s.error};const{extractUploadResult:c}=await(0,Ve.__vitePreload)(async()=>{const{extractUploadResult:u}=await Promise.resolve().then(()=>ye("./static/core/a50825ac.js")).then(p=>p.import_exports);return{extractUploadResult:u}},void 0,{}.url),d=c(s.data);return d.error||!d.file_url?{status:"skipped"}:{status:"uploaded",url:d.file_url}}catch(i){return{status:"failed",error:i}}}function Hu(){const[e,t]=(0,l.useState)(!1),n=r.useHeadless(),o=r.useEventEmitter(h.events.ON_BROWSER_EXTENSION_DETECTED_ID),i=(0,l.useCallback)(()=>{t(!1)},[]);return(0,l.useEffect)(()=>{const s=o.event(()=>{n||t(!0)});return()=>s.dispose()},[o,n]),{open:e,close:i}}function qu(){const[e,t]=(0,l.useState)(!1),n=r.useHeadless(),o=r.useEventEmitter(h.events.ON_BROWSER_TRANSLATE_DETECTED_ID),i=(0,l.useCallback)(()=>{t(!1)},[]);return(0,l.useEffect)(()=>{const s=o.event(()=>{n||t(!0)});return()=>s.dispose()},[o,n]),{open:e,close:i}}var Vu=["translated-ltr","translated-rtl"],Ku=".goog-te-banner-frame",so=!1;function Yu(e){if(e)return e;if(!(typeof document>"u"))return document}function Qu(e){const t=Yu(e);if(!t?.documentElement)return!1;const n=t.documentElement.classList;return Vu.some(o=>n.contains(o))?!0:t.querySelector(Ku)!=null}function Xu(){so=!1}function Ju(e){const t=Qu();return t&&!so&&e(),so=t,t}var Zu=500;function ep(){const e=r.useEventEmitter(h.events.ON_BROWSER_TRANSLATE_DETECTED_ID),t=(0,l.useRef)(null);(0,l.useEffect)(()=>{if(typeof window>"u")return;const n=()=>{Ju(()=>{e.fire()})},o=()=>{t.current!=null&&clearTimeout(t.current),t.current=setTimeout(()=>{t.current=null,n()},Zu)};n();const i=()=>{o()},s=()=>{document.visibilityState==="visible"&&o()},c=new MutationObserver(()=>{o()});return c.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),window.addEventListener("focus",i),document.addEventListener("visibilitychange",s),()=>{t.current!=null&&clearTimeout(t.current),Xu(),c.disconnect(),window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",s)}},[e])}var ao={},Xi=(0,l.createContext)(ao),Ji=(0,l.createContext)({current:ao}),Zi=(0,l.createContext)(()=>{});function tp({children:e}){const t=r.useDispatch(),n=r.useSelector(r.selectActiveSettingsTab),o=r.useEvent(h.SETTINGS_PANEL_EVENT),[i,s]=(0,l.useState)(ao),c=(0,l.useRef)(i);return c.current=i,(0,l.useEffect)(()=>{const d=o(u=>{const p=u?.type===h.ADVANCED_SETTINGS_PANEL;if((!u||!u.type&&!u.content&&!u.advancedTabs?.length)&&n==="Properties")s({}),t(r.resetToLastActiveSettingsTab());else if(n!=="Properties"&&t(r.setActiveSettingsTab(r.PROPERTIES)),u.advancedTabs?.length&&!p&&!u.content){const f=u.advancedTabs.map(g=>({content:g.content,label:g.label,key:g.key,className:g.className}));s(g=>({settings:{},extraTabs:f}))}else if(p&&u.content){const f=u.advancedTabs?.map(g=>({content:g.content,label:g.label,key:g.key,className:g.className}));s(g=>({settings:{},type:u.type,content:u.content,instanceKey:u.instanceKey,parent:u.parent,caption:u.caption,extraTabs:f,deletable:u.deletable}))}});return()=>d.dispose()},[o,s,t,n]),(0,a.jsx)(Zi.Provider,{value:s,children:(0,a.jsx)(Ji.Provider,{value:c,children:(0,a.jsx)(Xi.Provider,{value:i,children:e})})})}function lo(){return(0,l.useContext)(Xi)}function np(){return(0,l.useContext)(Ji)}function rp(){return(0,l.useContext)(Zi)}var es={widthCodeSplit:50,isResizing:!1,currentSide:null},ts=(0,l.createContext)({current:es}),ns=(0,l.createContext)(es.widthCodeSplit),rs=(0,l.createContext)({isResizing:!1,currentSide:null}),os=(0,l.createContext)({setWidthCodeSplit:()=>{},setIsResizing:()=>{},setCurrentSide:()=>{},setBlockMaxHeight:()=>{}}),is=(0,l.createContext)("unset");function op({children:e}){const[t,n]=(0,l.useState)(()=>+window.localStorage.getItem(r.LOCAL_STORAGE_ITEMS.em_code_mode_pane_sizes)||50),[o,i]=(0,l.useState)(!1),[s,c]=(0,l.useState)(null),[d,u]=(0,l.useState)("unset"),p=(0,l.useMemo)(()=>({widthCodeSplit:t,isResizing:o,currentSide:s}),[t,o,s]),f=(0,l.useMemo)(()=>({isResizing:o,currentSide:s}),[o,s]),g=(0,l.useRef)(p);g.current=p;const y=(0,l.useMemo)(()=>({setWidthCodeSplit:n,setIsResizing:i,setCurrentSide:c,setBlockMaxHeight:u}),[]);return(0,a.jsx)(os.Provider,{value:y,children:(0,a.jsx)(ts.Provider,{value:g,children:(0,a.jsx)(rs.Provider,{value:f,children:(0,a.jsx)(ns.Provider,{value:t,children:(0,a.jsx)(is.Provider,{value:d,children:e})})})})})}function ss(){return(0,l.useContext)(rs)}function as(){return(0,l.useContext)(ns)}function ip(){return(0,l.useContext)(ts)}function sp(){return(0,l.useContext)(is)}function ap(){return(0,l.useContext)(os)}var ls=(0,l.createContext)({previewAlertShow:!1,templateNotEmAlertShow:!1}),cs=(0,l.createContext)({setPreviewAlertShow:()=>{},setTemplateNotEmAlertShow:()=>{}});function lp({children:e}){const[t,n]=(0,l.useState)(!1),[o,i]=(0,l.useState)(!1),s=(0,l.useMemo)(()=>({previewAlertShow:t,templateNotEmAlertShow:o}),[t,o]),c=(0,l.useMemo)(()=>({setPreviewAlertShow:n,setTemplateNotEmAlertShow:i}),[]);return(0,a.jsx)(cs.Provider,{value:c,children:(0,a.jsx)(ls.Provider,{value:s,children:e})})}function cp(){return(0,l.useContext)(ls)}function dp(){return(0,l.useContext)(cs)}function up({className:e,sidePanelFloating:t,isCodeMode:n,codeModeDirection:o,children:i}){const s=sp(),c=(0,l.useMemo)(()=>{const d=Number.isFinite(s)?`${s}px`:"unset";return{"--ub-em-pane-block-height":t?n&&o==="bottom"?d:"calc(100% - 30px)":"100%"}},[t,n,o,s]);return(0,a.jsx)(_.ui_kit$Layout,{className:e,style:c,children:i})}function pp({maxPaneWidth:e,isCodeMode:t,codeModeDirection:n,isShowMobileSettings:o,desktopMobileSwitchPanel:i,children:s}){const c=r.useSelector(r.selectEmailWidth),{isResizing:d,currentSide:u}=ss(),p=t&&n!=="bottom"&&!o&&i?"100%":c,f=(0,l.useMemo)(()=>({maxWidth:typeof p=="number"?Math.min(p,e):e}),[p,e]);return(0,a.jsx)("div",{className:(0,rt.default)("email-pane__resizable",{"email-pane__resizable_drag":u||d}),style:f,children:s})}function mp({isCodeMode:e,codeModeDirection:t,sidePanelFloating:n,contentWrapperRef:o,children:i}){const s=as(),c=(0,l.useMemo)(()=>({flexGrow:1,overflowY:n?"scroll":"hidden",overflowX:"hidden",height:e&&t==="bottom"?`calc(${s}%)`:"100%",width:`${t==="left"?100-s:t==="bottom"?100:s}%`}),[e,t,n,s]);return(0,a.jsx)(_.ui_kit$Col,{style:c,id:"pane-content-wrapper",ref:o,children:i})}function fp({isCodeMode:e,codeModeDirection:t,children:n}){const o=as(),i=(0,l.useMemo)(()=>({width:`${t==="right"?100-o:t==="bottom"?100:o}%`,position:"relative",height:t==="bottom"?`calc(${100-o}%)`:"unset",display:e?"initial":"none"}),[e,t,o]);return(0,a.jsx)(_.ui_kit$Col,{style:i,children:n})}function gp({wrapperRef:e,children:t}){const{isResizing:n,currentSide:o}=ss();return(0,a.jsx)("div",{className:(0,rt.default)("email-pane__content-col email-pane__content-col_main",{"email-pane__content-col_disable":o||n}),ref:e,children:t})}function hp({isShowMobileSettings:e,headless:t,templateNotEmAlertEnabled:n}){const{__:o}=r.useI18n(),{previewAlertShow:i,templateNotEmAlertShow:s}=cp();return(0,a.jsxs)(a.Fragment,{children:[i&&e&&(0,a.jsx)(_.ui_kit$Alert,{title:o("Template is not mobile-friendly"),description:o("While editing, some elements of the email no longer fit the screen of the mobile device. Check that these elements are set to a smaller width for mobile devices."),type:"warning",className:"email-pane__col__alert",closable:!0}),s&&!t&&n&&(0,a.jsx)(_.ui_kit$Alert,{title:o("Template from another editor"),description:o("This template was created in another editor. Rebuild it from our components to get stable rendering, error-free editing, and full design control."),type:"warning",className:"email-pane__col__alert",closable:!0})]})}function ds(){const e=r.useElementEntityKind(),t=r.useSelector(r.selectElementSettings$1),n=r.useSelector(r.selectElementSettings);return e==="email"?t:n}function _p({isShowMobileSettings:e,propertiesPanelKey:t,onMouseLeave:n,email:o,onClosePanel:i}){const s=ds(),c=lo();return s?.type||c?.type||c?.content||c?.extraTabs?.length?(0,a.jsx)("div",{className:(0,rt.default)("email-pane__collapse-wrapper",{"mobile-view":e,"mobile-properties":e&&t!=="Structure"}),onMouseLeave:n,children:(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$PageLoader,{}),children:(0,a.jsx)(Hi,{email:o,formSettings:c,onClosePanel:i})})}):null}function yp({className:e,emailElementType:t}){return(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$PageLoader,{}),children:(0,a.jsx)(hu,{className:e,emailElementType:t,formSettings:lo()})})}function vp({isCodeMode:e,codeModeDirection:t}){const n=r.useElementEntityKind(),o=ds()?.type;return!(o===r.ELEMENT_TYPES.TEXT||o===r.ELEMENT_TYPES.LINK||o===r.ELEMENT_TYPES.IMG||o===r.ELEMENT_TYPES.BUTTON)||!e||t==="bottom"?null:(0,a.jsx)(yp,{className:(0,rt.default)("selected-element-panel__content selected-element-panel__content_abs",{"selected-element-panel__hidden":o===r.ELEMENT_TYPES.IMG}),emailElementType:n})}function bp({isCodeMode:e,codeModeDirection:t,email:n,onClosePanel:o}){const i=lo();return i?.type!=="img"||!e||t==="bottom"?null:(0,a.jsx)("div",{className:"email-pane__collapse-wrapper email-pane__collapse-wrapper_disabled",children:(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$PageLoader,{}),children:(0,a.jsx)(Hi,{email:n,formSettings:i,onClosePanel:o})})})}var Ep="code",Sp=(e,t)=>(0,a.jsx)(t,{className:"email-pane__tab-bar",...e}),{Content:wp}=_.ui_kit$Layout,kp=()=>{ro().catch(()=>{})},Jt=e=>(0,l.memo)(t=>(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$PageLoader,{}),children:(0,a.jsx)(e,{...t})})),Cp=Jt(vu),Tp=Jt(yu),Ip=Jt(bu),Ap=Jt(Su),xp=(0,l.memo)(e=>(0,a.jsx)(iu,{...e})),Pp=(0,l.memo)((0,l.forwardRef)((e,t)=>(0,a.jsx)(Bi,{...e,ref:t}))),Rp=(0,l.memo)(e=>(0,a.jsx)(Oi,{...e})),jp=Jt(_u),Op=Jt(ku),Lp=Jt(wu),us=({emailElement:e,isSuccess:t,setIsCollaborationEditor:n,isShowAddAllBlocksModal:o,triggerOpenSavedBlocksTab:i,setIsShowAddAllBlocksModal:s})=>{const{__:d,_x:u}=r.useI18n(),p=r.useMessageService(),{blockId:f}=r.useRouteParams(),g=r.useEditorProjectId(),y=r.useRouteEmailId(),m=r.useDispatch(),E=Vr(),k=r.useOpenPlanCatalog(),{modal:w}=_.ui_kit$App.useApp(),v=r.useAppConfig(),x=r.useConfigSource(),P=r.useHeadless(),K=r.useContainer(),J=qi("panel");gu(K),(0,l.useEffect)(()=>{Ht(K).notePagePainted()},[K]);const{token:N}=(0,_.ui_kit$useToken)(),L=r.useNotification(),A=r.usePushToDataLayer(),O=r.useProjectData(),z=vi(O?.id||g);zu(z);const B=r.useCookieManager(),U=r.useSelector(r.selectActiveSettingsTab),de=r.useCurrentUser(),me=r.toLanguageCode(r.useInterfaceLocale()),H=r.useStore(),Z=ip(),{setWidthCodeSplit:De,setIsResizing:ve,setCurrentSide:et,setBlockMaxHeight:be}=ap(),fe=r.useSelector(r.selectActiveModal$1),Y=r.useSelector(r.selectIsCodeMode),pe=r.useSelector(r.selectCodeModeDirection),[ie,se]=(0,l.useState)(Y);(0,l.useEffect)(()=>{Y&&se(!0)},[Y]);const Ae=r.useSelector(Lu),Te=r.useSelector(Mu),Fe=r.useSelector(Nu),X=r.useSelector(r.selectPropertiesPanelKey),[Ee]=r.useLazyClearAiChatQuery(),[Ie]=r.useUploadImageMutation(),ge=r.useSelector(r.selectEmailViewType)===r.MOBILE,[Re,Ue]=(0,l.useState)(r.LIGHT),[C,T]=(0,l.useState)(),[R,D]=(0,l.useState)(v.defaultBuildPanel||"empty"),[I,S]=(0,l.useState)("empty"),[ae,we]=(0,l.useState)(!1),[Ye,Qe]=(0,l.useState)([]),[ze,Ze]=(0,l.useState)([]),{setPreviewAlertShow:pt,setTemplateNotEmAlertShow:bt}=dp(),{open:ft,close:lt}=Hu(),{open:G,close:V}=qu();ep();const te=r.useRootElement(),ue=r.isEditorLockedByPlan(O,{isPlugin:!0}),he=r.usePlanFeatureGate("discussion"),Ge=r.usePlanFeatureGate("code_editor"),qe=Gi("ai"),st=qe.exceeded?r.getLimitUpgradePresetDefinition(qe.exceeded.presetId):null,Bt=v?.configSwither||!1;(0,l.useEffect)(()=>{m(r.resetParentBlocks())},[m]),(0,l.useEffect)(()=>{const b=window.localStorage.getItem(r.LOCAL_STORAGE_ITEMS.em_active_tab);b&&m(r.setActiveSettingsTab(b))},[B,m]);const Le=y||f,Xe=e.hasOwnProperty("type")?r.BLOCK:r.EMAIL,oe=rp(),ee=np(),$=(0,l.useRef)(null),le=(0,l.useRef)(null),xe=(0,l.useRef)(),Se=(0,l.useRef)(),Me=(0,l.useRef)(null),We=(0,l.useRef)(),Be=(0,l.useRef)(),ot=(0,l.useRef)(null),fn=(0,l.useRef)(!1),Ot=(0,l.useRef)(!1),ct=(0,l.useCallback)(()=>{Ot.current=!1},[]),Et=(0,l.useCallback)(()=>{Ot.current=!0},[]),Lt=(0,l.useCallback)(b=>{b?.type===r.ELEMENT_TYPES.SOCIAL&&Et()},[Et]),[jn,On]=(0,l.useState)(!1),[gn,Ln]=(0,l.useState)(!1),[Mn]=r.useEditMeMutation(),[gt,St]=(0,l.useState)(!1),[ce,ke]=(0,l.useState)(0),[Ne,nt]=(0,l.useState)(!1),je=(0,l.useCallback)(()=>nt(!1),[]),Yt=(0,l.useCallback)(()=>{nt(!1),k()},[k]),[$t,dt]=(0,l.useState)(!1),Nn=v.configSwither?localStorage.getItem("configSwither")==="pro"?!0:localStorage.getItem("configSwither")==="editor"?!1:v.mode==="pro":!1,Ut=(0,l.useCallback)(()=>{clearTimeout(ot.current);const b=".blocks-search__result-holder";te.querySelector(b)&&(Ae||Te||Fe)&&(te.querySelector(b).style.removeProperty("transition"),te.querySelector(b).style.opacity=0,ot.current=setTimeout(()=>{r.measureBlockPreviews(te,207/640),te.querySelector(b)&&(te.querySelector(b).style.transition="opacity 0.2s",te.querySelectorAll(b).forEach(j=>j.style.opacity=1))},200))},[Te,Ae,Fe]),Tt=(0,l.useRef)(void 0),It=(0,l.useCallback)(b=>{const j=b.target;j&&(window.clearTimeout(Tt.current),Tt.current=window.setTimeout(()=>{On(!!j.closest(".desktop_view")),Ln(!!j.closest(".mobile_view"))},100))},[]);(0,l.useEffect)(()=>()=>{window.clearTimeout(Tt.current)},[]),(0,l.useEffect)(()=>{const b=r.addDocumentListenerFromShadow(te,"mouseover",It);return()=>{b.dispose()}},[te,It]),(0,l.useEffect)(()=>{typeof n=="function"&&(ze.length>0?n(!0):n(!1))},[ze]);const[Dr]=r.useSendMessageMutation(),{data:ht={},refetch:M,status:q}=r.useGetDialogQuery({entity_id:Le},{skip:!Le||v.aiAssistentEnabled===!1||ue}),Q=r.useEventEmitter(h.events.AI_TEXT_REQUEST_ID).hasListeners(),re=r.useIsStandalone(),ne=!Q&&!re,W=(0,l.useMemo)(()=>ne?[{data:{role:"assistant",message:d("Typing..."),isLoading:!0}}]:[],[ne,d]),[Ce,_e]=(0,l.useState)([]),[He,hn]=(0,l.useState)(v.defaultBuildPanel!==""?r.BLOCKS:r.ATOMS),Dn=(0,l.useRef)(null),mt=(0,l.useCallback)(()=>{const b=Se.current?.getBoundingClientRect(),j=C?.getBoundingClientRect();p.send({operation:r.EVENT_TYPES.SANDBOX_WINDOW_CHARACTERISTIC,settings:{iframeOffsetTop:Y&&pe!=="bottom"?0:30,scrollTop:-b?.top+j?.top+30,innerHeight:window.innerHeight,previewHeight:j?.height,mode:Y&&pe!=="bottom"?Ep:"default"}})},[pe,Y,C,p]),Fr=t&&e,_n=(0,l.useCallback)(b=>{const j=window.navigator.platform.match("Mac");v.codeEnabled&&v.codeSideEnabled&&b.altKey&&b.keyCode===88&&(E.toggle(),Ge.isLocked&&(St(!0),ke(r.FEATURE_UPSELL_SLIDE.code_editor))),((j?b.metaKey:b.ctrlKey)&&b.shiftKey&&b.keyCode===76||(j?b.metaKey:b.ctrlKey)&&b.shiftKey&&b.keyCode===69||(j?b.metaKey:b.ctrlKey)&&b.shiftKey&&b.keyCode===82)&&b.preventDefault()},[v.codeEnabled,Ge.isLocked,v.codeSideEnabled,E]),wt=fe.includes("UPLOAD_IMAGE_")||fe.includes("UPLOAD_BACKGROUND_"),yn=(0,l.useRef)(!1),_t=(0,l.useCallback)(b=>{const j=b.target,F=j.closest(".email-pane__content-col")||j.closest(".email-pane__collapse-wrapper")||j.closest(".selected-element-panel-content")||j.closest(".selected-element-panel")||j.closest(".em-analytics__email-tab-properties")||j.closest(".em-analytics__email-tab-styles")||j.closest(".em-analytics__email-tab-history")||j.closest(".blocks-modal-container")||j.closest(".email-pane__sizes")||j.closest(".email-preview-menu")||j.closest(".monaco-editor")||j.closest(".ant-modal-wrap");yn.current=!!F},[]),Ga=(0,l.useCallback)(b=>{const j=yn.current,F=window.getSelection().toString().length>0||document.activeElement&&document.activeElement.tagName==="INPUT"&&document.activeElement.selectionStart!==document.activeElement.selectionEnd;yn.current=!1,!(j||F)&&(!document.querySelector(".easylogic-colorpicker")&&!te.querySelector(".easylogic-colorpicker")&&!b.target.closest(".email-pane__content-col")&&!b.target.closest(".blocks-modal-container")&&!b.target.closest(".email-pane__collapse-wrapper")&&!b.target.closest(".selected-element-panel__columns-settings__controls__column__remove")&&!b.target.closest(".email-preview__content-col_main")&&!b.target.closest(".email-preview-menu")&&!b.target.closest(".monaco-editor")&&!b.target.closest(".main__pane-close-btn")&&!b.target.closest(".main__pane-trigger")&&!b.target.closest(".ant-modal-wrap")&&!b.target.closest(".email-pane__sizes")&&!b.target.closest(".ant-input-clear-icon")&&!b.target.closest(".ant-color-picker")&&!b.target.closest(".control-font-family-dropdown")&&!Dn.current&&!b.target.closest(".email-preview-menu__history")&&!b.target.closest(".selected-element-panel-content")&&!b.target.closest(".ant-select-dropdown")&&!b.target.closest(".ant-picker-dropdown")&&!b.target.closest(".toggle_view")&&!b.target.closest(".upload-bg-image__menu")&&!b.target.closest(".email-pane__paths")&&!b.target.closest(".ant-tabs-extra-content")&&!b.target.closest(".anticon-delete")&&!wt&&fe!==r.MODALS.IMAGE_EDITOR_MODAL&&(U==="Properties"&&(Et(),m(r.resetToLastActiveSettingsTab()),p.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_ACTIVE_RESET}),Qe([])),U==="History"&&m(r.setActiveSettingsTab(r.BUILD)),m(r.switchIsPanelHistoryCollapsed(!0)),p.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:!1}),setTimeout(()=>{e.type?m(r.setElementSettings({type:null})):m(r.setElementSettings$1({type:null}))},300)),Dn.current=null)},[m,e.type,fe,U,p,wt]),[gv,Wa]=(0,l.useState)(!0),{data:qo=[],refetch:Br}=r.useGetCommentsQuery(Le,{skip:!Le||ue});(0,l.useEffect)(()=>{Le&&!ue&&Br()},[U,Le,ue,Br]),(0,l.useEffect)(()=>{Le&&!Object.keys(ht).length&&q==="fulfilled"&&M()},[U,Le,M,ht,q]),(0,l.useEffect)(()=>{const b=new h.Disposable,j=window.localStorage.getItem(r.LOCAL_STORAGE_ITEMS.em_active_tab);if(ht?.totalCount===0&&q!=="pending"){const Pe={project_id:g,connection:"chat",entity_id:Le,context:"default",locale:me};!j&&ne&&r.runOnceInFlight(`email-default-context:${Le}`,()=>{r.swallowPromiseRejection(Dr({body:Pe}).then(()=>{b.isDisposed()||q==="fulfilled"&&M()}))})}const F={data:{role:"assistant",message:d("Typing..."),isLoading:!0}};return ht?.documents?.length>0?(window.localStorage.removeItem(r.LOCAL_STORAGE_ITEMS.em_active_tab),_e(ht?.documents),ne&&ht?.documents[ht?.documents?.length-1].data?.userInfo&&_e([...ht?.documents,F])):j||_e(ne?[F]:[]),()=>b.dispose()},[Le,me,ht?.totalCount,ht?.documents,ne,g,M,Dr,q]),(0,l.useEffect)(()=>{oe({}),m(Xe==="email"?r.setElementSettings$1({}):r.setElementSettings({}))},[m,Xe]);const Ha=(0,l.useCallback)(b=>{m(r.setEmailSettings(Yn(b)))},[m]),qa=(0,l.useCallback)(b=>{m(r.setBlockSettings(Yn(b)))},[m]),Fn=(0,l.useCallback)(b=>{m(Xe==="email"?r.setElementSettings$1(Yn(b)):r.setElementSettings(Yn(b)))},[m,Xe]);(0,l.useEffect)(()=>{const b=We.current,j=Me.current;T(Y?j??b:b)},[Y,pe]);const[hv,_v]=(0,l.useState)(null),yv=(0,l.useCallback)(b=>{v.sidePanelFloating&&(Me.current=b),_v(b)},[v.sidePanelFloating]),Bn=(0,l.useCallback)(b=>{D(b),b==="search"?we(!0):(we(!1),S(b)),setTimeout(Ut,50)},[Ut]),vv=(0,l.useCallback)(b=>{const j=b.data.operation,F=b.data,Pe=b.data.action;if(j==="application_block_inserted"||b.data.operationId==="application_block_inserted"){const Oe=b.data.operationId?b.data.data:F||{},Nt=Oe.type==="project"||Oe.type==="template"||Oe.type==="common"?"block":"structure",bn=Oe.name||Oe.type||(Nt==="block"?"block":"structure");A({event:"add",action:"add_element_to_email",element_type:Nt,element_name:bn,entity_id:e?.id||y||f,project_id:O?.id||g})}if(j===r.EVENT_TYPES.APPLICATION_SCROLL_TO&&setTimeout(()=>{Me.current?.scrollTo({top:b.data.settings.value,behavior:"smooth"})},100),j===r.EVENT_TYPES.APPLICATION_PREVIEW_ALERT_SHOW&&pt(F.settings.show),j===r.EVENT_TYPES.APPLICATION_TEMPLATE_NOT_EM_ALERT_SHOW&&bt(!0),j===r.EVENT_TYPES.APPLICATION_ACTION&&Pe==="toggle_editor"&&E.toggle(),j===r.EVENT_TYPES.APPLICATION_IFRAME_SET_HEIGHT&&(te.querySelector(".email-pane__iframe").style.height=F.settings.height+"px"),j===r.EVENT_TYPES.APPLICATION_EMAIL_SETTINGS_SET){let Oe=Object.assign({},F.settings);delete Oe.preheader,Object.values(Oe).every(Nt=>!Nt)?(m(r.setEmailSettingsDisable(!0)),m(r.resetToLastActiveSettingsTab())):Ha(F.settings),F.settings.noBlocks,m(r.setMobileViewActive(F.settings.responsive)),Wa(Oe.structuresMedia)}if(j===r.EVENT_TYPES.APPLICATION_BLOCK_SETTINGS_SET&&(Object.values(F.settings).every(Oe=>!Oe)?(m(r.setBlockSettingsDisable(!0)),m(r.resetToLastActiveSettingsTab())):(qa(F.settings),Wa(F.settings.structuresMedia))),j===r.EVENT_TYPES.APPLICATION_ELEMENT_SETTINGS_SET){const Oe=Object.values(r.ELEMENT_TYPES).includes(F.type),Nt=ee.current,bn=Nt?.type==="advanced"&&!!Nt.content,At=F.tab?!0:!Oe&&!bn,{type:Ov,caption:Lv,settings:Mv}=F,tl=JSON.stringify([Ov,Lv,Mv]),Nv=tl!==$.current;if($.current=tl,At&&U==="Properties"&&m(r.resetToLastActiveSettingsTab()),F.type===r.ELEMENT_TYPES.EMPTY_TABLE||F.type===r.ELEMENT_TYPES.EMPTY_TD?(m(r.setActiveSettingsTab(r.BUILD)),F.type===r.ELEMENT_TYPES.EMPTY_TABLE?(hn(r.BLOCKS),F.tab?Bn(F.tab):Bn("common")):F.type===r.ELEMENT_TYPES.EMPTY_TD&&hn(r.ATOMS)):F.type&&U!=="Properties"?F.type===r.ELEMENT_TYPES.SOCIAL&&Ot.current?ct():(ct(),m(r.setActiveSettingsTab(r.PROPERTIES))):F.type!==r.ELEMENT_TYPES.SOCIAL&&ct(),!Nv)return;F.type===r.ELEMENT_TYPES.CAROUSEL||F.type===r.ELEMENT_TYPES.ACCORDION||F.type===r.ELEMENT_TYPES.SOCIAL?(oe(tn=>({settings:{...F.settings,type:At?null:F.type,caption:F.caption,parent:At?null:F.settings.parent},type:At?null:F.type,parent:At?null:F.settings.parent,caption:F.caption,extraTabs:tn.extraTabs})),Fn({})):(Fn({...F.settings,type:At?null:F.type,parent:At?null:F.settings.parent,caption:F.caption}),oe(tn=>!Oe&&tn.type==="advanced"&&tn.content?{...tn,settings:{...F.settings,type:F.type,parent:F.settings?.parent,caption:F.caption}}:tn.extraTabs?.length?{extraTabs:tn.extraTabs}:{})),F.settings?.path?.length>0&&Qe(F.settings?.path)}j===r.EVENT_TYPES.APPLICATION_ELEMENT_SETTINGS_CLOSE&&($.current=null,ee.current?.type===r.ELEMENT_TYPES.SOCIAL&&Et(),m(r.resetToLastActiveSettingsTab()))},[m,Ha,qa,Fn,U,Bn,te,A,e,y,f,O,ct,Et,E,g,ee,oe,pt,bt]);(0,l.useEffect)(()=>{r.identifyUser({id:de?.id,email:de?.email,username:de?.name})},[de]),(0,l.useEffect)(()=>{const b=de.email_builder_config,j=!ue,F=x.get()?.mode;if(!b||typeof b!="string")return;const Pe=j&&b==="simple"?"pro":b;Pe!==F&&m(r.changeConfig(Pe))},[ue,de.email_builder_config,de.id,m,H,x]),(0,l.useEffect)(()=>{if(Y&&Ge.isLocked&&E.toggle(),v.configSwither){let b=localStorage.getItem("configSwither")||v.mode||"editor";localStorage.setItem("configSwither",b),m(r.changeConfig(b))}},[]);const Va=b=>{setTimeout(()=>{if(ue)m(r.changeConfig("pro")),dt(!0),St(!0),A({event:"change",action:"change_config_mode",config_mode:"pro",entity_id:e?.id||y||f,project_id:O?.id||g});else{let j=b?"pro":"editor";localStorage.setItem("configSwither",j),m(r.changeConfig(j)),A({event:"change",action:"change_config_mode",config_mode:j,entity_id:e?.id||y||f,project_id:O?.id||g})}},200)},bv=()=>{Y&&E.toggle(),m(r.resetToLastActiveSettingsTab()),m(r.changeConfig("simple")),dt(!1),St(!1),A({event:"change",action:"change_config_mode",config_mode:"simple",entity_id:e?.id||y||f,project_id:O?.id||g})},Ev=(0,l.useCallback)(()=>{St(!1)},[]);r.useListenPostMessage(vv),(0,l.useEffect)(()=>{const b=p.addListener(j=>{const F=Gu(j,r.EVENT_TYPES.APPLICATION_NATIVE_IMAGE_DROP);if(!F)return;const Pe=()=>p.send({operation:r.EVENT_TYPES.SANDBOX_NATIVE_IMAGE_DROP_CLEAR});(async()=>{const Oe=await Wu(F,{readContext:()=>({userId:de?.id,folderId:O?.id??g}),prepare:At=>r.prepareImageForEditorUpload(At,v),upload:At=>Ie(At)});if(Oe.status==="failed"&&L.fromError("IMAGE_UPLOAD_ERROR",F,Oe.error,!0),Oe.status!=="uploaded"){Pe();return}p.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_SETTINGS_SET,type:r.ELEMENT_TYPES.IMG,settings:{src:Oe.url}});const Nt=H.getState(),bn=Xe==="email"?r.selectElementSettings$1(Nt):r.selectElementSettings(Nt);bn?.type===r.ELEMENT_TYPES.IMG&&Fn({...bn,src:Oe.url,changeKey:"src"})})()});return()=>b.dispose()},[p,Ie,de,g,O?.id,v,L,Fn,H,Xe]),(0,l.useEffect)(()=>{const b=p.addListener("application_atom_inserted",F=>{A({event:"add",action:"add_element_to_email",element_type:"atom",element_name:F||"atom",entity_id:e?.id||y||f,project_id:O?.id||g})}),j=p.addListener("application_block_inserted",F=>{const Pe=F?.type==="project"||F?.type==="template"||F?.type==="common"?"block":"structure",Oe=F?.name||F?.type||(Pe==="block"?"block":"structure");A({event:"add",action:"add_element_to_email",element_type:Pe,element_name:Oe,entity_id:e?.id||y||f,project_id:O?.id||g})});return()=>{b?.dispose(),j?.dispose()}},[p,A,e?.id,y,f,g,O?.id]);const Sv=b=>{let j=te.querySelector(".atoms__list");v.toggleSidePanel&&b===U?m(r.setActiveSettingsTab(r.DISABLED_TAB)):b==="Optimize"?xt.comingSoonHandler(d,w):b!=="Properties"&&b!=="History"?(m(r.setActiveSettingsTab(b)),A({event:"navigate",action:"navigate_email_pane_tab",tab_name:b==="Disabled_tab"?"DISABLED_TAB":b,entity_id:e?.id||y||f,project_id:O?.id||g}),p.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:!1}),p.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_ACTIVE_RESET}),Qe([])):(b==="Properties"||b==="History")&&A({event:"navigate",action:"navigate_email_pane_tab",tab_name:b,entity_id:e?.id||y||f,project_id:O?.id||g}),he.isLocked&&b==="Discuss"&&(St(!0),ke(r.FEATURE_UPSELL_SLIDE.discussion)),ue&&b==="Optimise"&&(St(!0),ke(6)),qe.isLocked&&b==="AiChat"&&(qe.state.state==="locked_by_limit"&&qe.exceeded?nt(!0):(St(!0),ke(9)))},Vo=(0,l.useRef)(null),$r=(0,l.useRef)(void 0),Mt=(0,l.useCallback)(()=>{const b=Me.current?.getBoundingClientRect();if(Vo?.current?.getBoundingClientRect().top>=0&&b){const j=Math.round(b.height-30);Vo.current.style.height=`${j}px`,be(j-30)}$r.current&&window.clearTimeout($r.current),$r.current=window.setTimeout(function(){p.isInited()&&mt()},100)},[mt,p,be]);(0,l.useEffect)(()=>()=>{window.clearTimeout($r.current)},[]),(0,l.useEffect)(()=>(U==="AiChat"&&!ue?le.current=setInterval(()=>{M({entity_id:Le})},5e3):clearInterval(le.current),clearInterval(le.current)),[Le,ue,M,U]);const wv=b=>hn(b||""),kv=()=>{we(!1),D(I)},Ko=()=>{let b=te.querySelector(".block-search__preview");b&&(b.style.opacity="0",b.style.transform="translateX(-99%)",setTimeout(function(){b.remove()},300))};let vn=[];const $n={display:"flex",alignItems:"center",justifyContent:"center"};v.blocksEmptyEnabled&&vn.push({label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"top",title:d("Empty blocks"),children:(0,a.jsx)("div",{style:$n,children:(0,a.jsx)(r.EmIcons,{icon:"BorderOuterOutlined",component:_.icons$BorderOuterOutlined,style:{fontSize:18}})})}),value:"empty"}),v.blocksSavedEnabled&&vn.push({label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"top",title:d("Saved blocks"),children:(0,a.jsx)("div",{style:$n,children:(0,a.jsx)(r.EmIcons,{icon:"AppstoreAddOutlined",component:_.icons$AppstoreAddOutlined,style:{fontSize:18}})})}),value:"project"}),v.blocksCommonEnabled&&vn.push({label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"top",title:d("Common blocks"),children:(0,a.jsx)("div",{style:$n,children:(0,a.jsx)(r.EmIcons,{icon:"AppstoreOutlined",component:_.icons$AppstoreOutlined,style:{fontSize:18}})})}),value:"common"}),v.blocksTemplateEnabled&&vn.push({label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"top",title:d("Template blocks"),children:(0,a.jsx)("div",{style:$n,children:(0,a.jsx)(r.EmIcons,{icon:"BuildOutlined",component:_.icons$BuildOutlined,style:{fontSize:18}})})}),value:"template"}),v.blocksSearchEnabled&&vn.push({label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"top",title:d("Blocks search"),children:(0,a.jsx)("div",{style:$n,children:(0,a.jsx)(r.EmIcons,{icon:"SearchOutlined",component:_.icons$SearchOutlined,style:{fontSize:18}})})}),value:"search"});const Ur=R!=="empty"||ae,Cv=!v.blocksSectionsShow||Ur?"100%":"calc(100% - 44px)";let Tv=[{label:(0,a.jsx)("div",{className:"email-pane__tab",children:d("Elements")}),key:r.ATOMS,className:"email-pane__collapse-panel email-pane__atoms",children:(0,a.jsx)(Rp,{})},{label:(0,a.jsx)("div",{className:"email-pane__tab",children:d("Blocks")}),key:r.BLOCKS,className:"email-pane__collapse-panel email-pane__blocks-search",style:{height:Cv},children:(0,a.jsxs)("div",{className:(0,rt.default)("email-pane__blocks-panel",{"email-pane__blocks-panel_scrollable":Ur}),children:[v.blocksSectionsShow&&(0,a.jsxs)("div",{className:"email-pane__blocks-panel-header",children:[(0,a.jsxs)(_.ui_kit$Space.Compact,{block:!0,children:[!ae&&(0,a.jsx)(_.ui_kit$Segmented,{block:!0,style:{width:"100%",marginTop:24},onChange:Bn,value:R,options:vn}),ae&&(0,a.jsx)("div",{style:{width:"100%",height:36}}),ae&&(0,a.jsx)("div",{style:{width:36,textAlign:"right",marginTop:22},children:(0,a.jsx)(r.EmIcons,{icon:"CloseOutlined",component:_.icons$CloseOutlined,style:{padding:"0 2px 0",cursor:"pointer"},onClick:kv})})]}),(0,a.jsx)("div",{className:"blocks-search__divider-wrapper",style:{marginTop:ae?28:12},children:(0,a.jsx)(_.ui_kit$Divider,{className:"blocks-search__divider"})})]}),(0,a.jsxs)("div",{className:"email-pane__blocks-panel-body",children:[(0,a.jsx)("div",{className:"blocks-search__empty-shadow",style:{display:R==="empty"&&!ae?"block":"none"},children:gv?(0,a.jsx)(pi,{}):(0,a.jsx)(di,{})}),(0,a.jsx)("div",{className:(0,rt.default)("email-pane__blocks-panel-results",{"email-pane__blocks-panel-results_visible":Ur}),children:(0,a.jsx)(Ap,{parentEmailId:e?.parent_email,blocksTab:R,search:ae,reloadBlockScreens:Ut,setIsShowAddAllBlocksModal:s})})]})]})}];const Un=[{disabled:gt,key:r.PROPERTIES,style:{height:"var(--ub-em-pane-block-height)"},className:"em-analytics__email-tab-properties",children:(0,a.jsx)(_p,{isShowMobileSettings:ge,propertiesPanelKey:X,onMouseLeave:Ko,email:e,onClosePanel:Lt})},{disabled:gt,key:r.HISTORY,style:{height:"var(--ub-em-pane-block-height)"},className:"em-analytics__email-tab-history",children:Fr&&(0,a.jsx)("div",{className:"email-pane__collapse-wrapper",onMouseLeave:Ko,children:(0,a.jsx)(Op,{setCollapsedHistory:()=>m(r.switchIsPanelHistoryCollapsed(!0)),emailElement:Fr})})},{key:r.DISABLED_TAB,className:"em-analytics__email-tab-properties"},{disabled:gt,label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"left",title:u("Build","tab"),children:(0,a.jsx)(r.EmIcons,{"data-testid":"contentIcon",icon:"PlusCircleOutlined",component:_.icons$PlusCircleOutlined,size:24,strokeWidth:v.iconStrokeWidth})}),key:r.BUILD,className:"em-analytics__email-tab-build",style:{height:"var(--ub-em-pane-block-height)",overflow:"hidden"},children:(0,a.jsx)("div",{className:(0,rt.default)("email-pane__collapse-wrapper",{"email-pane__collapse-wrapper_no-topleft-radius":U==="Build"||!U,"email-pane__collapse-wrapper_build":He==="Blocks"&&Ur}),onMouseLeave:Ko,children:(0,a.jsx)(_.ui_kit$Tabs,{className:(0,rt.default)("secondary-tabs email-pane__collapse",{"secondary-tabs_unset_scroll":He===r.BLOCKS}),size:"large",activeKey:He,onChange:wv,items:Tv})})},{disabled:gt,label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"left",title:u("Styles","tab"),children:(0,a.jsx)(r.EmIcons,{"data-testid":"stylesIcon",icon:"Styles",component:_.icons$Styles,size:24,strokeWidth:v.iconStrokeWidth})}),key:r.STYLES,className:"em-analytics__email-tab-styles",style:{height:"var(--ub-em-pane-block-height)",overflow:"hidden"},children:(0,a.jsx)("div",{className:"email-pane__collapse-wrapper",children:(0,a.jsx)(Tp,{email:e})})}];v.commentsEnabled&&Un.push({disabled:gt,label:(0,a.jsxs)(_.ui_kit$Tooltip,{placement:"left",title:u("Discuss","tab"),children:[(0,a.jsx)(r.EmIcons,{"data-testid":"commentsIcon",icon:"CommentOutlined",component:_.icons$CommentOutlined,size:24,strokeWidth:v.iconStrokeWidth}),he.isLocked&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:v.iconStrokeWidth,className:"free-mode-firewall-icon free-mode-firewall-icon_emailpane"}),!!qo.length&&(0,a.jsx)("span",{className:"email-pane__comment-counter",children:qo.filter(b=>b.comment_status!=="deleted").length})]}),key:"Discuss",className:"email-pane__tab-discuss em-analytics__email-tab-discuss",style:{height:"var(--ub-em-pane-block-height)",overflow:"hidden"},children:(0,a.jsx)("div",{className:"email-pane__collapse-wrapper",children:(0,a.jsx)(_.ui_kit$Tabs,{className:"secondary-tabs email-settings__collapse discuss-wrapper",size:"large",activeKey:"Discuss",items:[{label:(0,a.jsx)(a.Fragment,{children:d("Discuss")}),key:"Discuss",forceRender:!0,className:"email-settings__collapse-panel",children:Le?(0,a.jsx)(Lp,{email:e,comments:qo,subjectId:Le,isLoggedIn:!0,emailElementType:Xe}):(0,a.jsx)("div",{className:"aside-content-wrapper",children:e.hasOwnProperty("type")?(0,a.jsx)(_.ui_kit$Alert,{description:d("Save the block before commenting."),type:"info",showIcon:!0,style:{marginBottom:20}}):(0,a.jsx)(_.ui_kit$Alert,{description:d("Save the email before commenting."),type:"info",showIcon:!0,style:{marginBottom:20}})})}]})})});const Iv=()=>{Ee({entity_id:Le}).then(b=>{b.error?L.error({title:b.error.data.code,description:b.error.data.message}):b.data.success&&L.success({title:d("Success"),description:b.data.success}),ue||M()})};v.aiAssistentEnabled&&Un.push({disabled:gt,label:(0,a.jsxs)(_.ui_kit$Tooltip,{placement:"left",title:u("AI assistant","tab"),children:[(0,a.jsx)(r.EmIcons,{"data-testid":"aiAssistentIcon",icon:"AI",component:_.icons$AI,size:24,strokeWidth:v.iconStrokeWidth}),qe.isLocked&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:v.iconStrokeWidth,className:"free-mode-firewall-icon free-mode-firewall-icon_emailpane"}),ht?.totalCount>0&&Le&&(0,a.jsx)("span",{className:"email-pane__comment-counter",children:ht?.totalCount})]}),key:"AiChat",className:"email-pane__tab-discuss em-analytics__email-tab-discuss",style:{height:"var(--ub-em-pane-block-height)",overflow:"hidden"},children:(0,a.jsx)(a.Fragment,{children:(0,a.jsx)("div",{className:"email-pane__collapse-wrapper",children:(0,a.jsx)(_.ui_kit$Tabs,{className:"secondary-tabs email-settings__collapse discuss-ai-wrapper",size:"large",activeKey:"AiChat",tabBarExtraContent:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"top",title:d("Clear chat"),children:(0,a.jsx)(_.ui_kit$Popconfirm,{description:d("Clear chat history?"),onConfirm:Iv,okText:d("Yes"),cancelText:d("No"),icon:"",placement:"leftTop",title:!1,children:(0,a.jsx)(_.ui_kit$Button,{type:"text",icon:(0,a.jsx)(r.EmIcons,{icon:"ClearChat",component:_.icons$ClearChat,style:{fontSize:16}}),style:{marginRight:16}})})}),items:[{label:(0,a.jsx)(a.Fragment,{children:d("AI assistant")}),key:"AiChat",forceRender:!0,className:"email-settings__collapse-panel",children:Le||window.localStorage.getItem(r.LOCAL_STORAGE_ITEMS.em_active_tab)?(0,a.jsx)(Cp,{messages:Ce.length>0?Ce:W,newEmailAiGeneratorRef:fn}):(0,a.jsx)("div",{className:"aside-content-wrapper",children:e.hasOwnProperty("type")?(0,a.jsx)(_.ui_kit$Alert,{description:d("Save the block before commenting."),type:"info",showIcon:!0,style:{marginBottom:20}}):(0,a.jsx)(_.ui_kit$Alert,{description:d("Save the email before commenting."),type:"info",showIcon:!0,style:{marginBottom:20}})})}]})})})}),v.optimizeEnabled&&Un.push({disabled:gt,label:(0,a.jsxs)(_.ui_kit$Tooltip,{placement:"left",title:u("Optimize","tab"),children:[(0,a.jsx)(r.EmIcons,{"data-testid":"optimizeIcon",icon:"Speed",component:_.icons$Speed,size:24,strokeWidth:v.iconStrokeWidth}),ue&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:v.iconStrokeWidth,className:"free-mode-firewall-icon free-mode-firewall-icon_emailpane"})]}),key:"Optimise",className:"em-analytics__email-tab-optimise",style:{height:"var(--ub-em-pane-block-height)",overflow:"hidden"},children:(0,a.jsx)("div",{className:"email-pane__collapse-wrapper",children:(0,a.jsx)(_.ui_kit$Tabs,{className:"secondary-tabs secondary-tabs_optimise email-settings__collapse optimise-wrapper",size:"large",activeKey:"Optimise",items:[{label:(0,a.jsx)(a.Fragment,{children:d("Optimize")}),key:"Optimise",forceRender:!0,className:"email-settings__collapse-panel",children:(0,a.jsx)(Ip,{})}]})})}),v.settingsEnabled&&Un.push({disabled:gt,label:(0,a.jsx)(_.ui_kit$Tooltip,{placement:"left",title:u("Settings","tab"),children:(0,a.jsx)(r.EmIcons,{"data-testid":"settingsIcon",icon:"SettingOutlined",component:_.icons$SettingOutlined,size:24,strokeWidth:v.iconStrokeWidth})}),key:"Edit",className:"em-analytics__email-tab-edit",style:{height:"var(--ub-em-pane-block-height)",overflow:"hidden"},children:(0,a.jsx)("div",{className:"email-pane__collapse-wrapper",children:(0,a.jsx)(jp,{email:e})})});const Ka=U===r.DISCUSS,Ya=(0,l.useRef)(0),Qa=(0,l.useRef)(0),Xa=(0,l.useRef)(0),Av=(0,l.useCallback)(()=>(te.querySelector(".email-pane__col_preview")?.getBoundingClientRect().width??0)-(v.sidePanelFloating?0:38),[te,v.sidePanelFloating]);(0,l.useEffect)(()=>{Le&&!ue&&Br()},[Le,ue,Br]),(0,l.useEffect)(()=>{const b=p.onInit(()=>{p.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:!1}),p.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_DISCUSS,value:Ka})});return()=>b.dispose()},[Ka,p]),(0,l.useEffect)(()=>{if(!C||!Ki(p))return;const b=new AbortController;return Yi(p,r.DEFAULT_SANDBOX_READY_TIMEOUT_MS,b.signal).then(()=>mt()).catch(()=>{}),()=>b.abort()},[C,mt,p]);const Yo=(0,l.useCallback)(b=>{const j=b??r.selectEmailWidth(H.getState());p.send({operation:r.EVENT_TYPES.SANDBOX_IFRAME_SETSIZE,settings:{iframeWidth:typeof j=="number"?j+2:j}}),xe.current?.resize()},[H,p]);(0,l.useEffect)(()=>{if(!ge&&U!=="Disabled_tab"){const b=te.querySelector(".email-pane__row")?.getBoundingClientRect().width;Se?.current?.getBoundingClientRect().width+540>b&&m(r.setEmailWidth("100%"))}},[m,U,te,ge]);const Qo=(0,l.useCallback)(()=>{const b=Se.current;b&&(b.style.borderWidth="1px",v.sidePanelFloating||(b.style.marginLeft="-1px",b.style.marginRight="-1px"),b.style.borderLeftColor=null,b.style.borderRightColor=null)},[v.sidePanelFloating]),Ja=(0,l.useCallback)(b=>{const j=Z.current.widthCodeSplit;ve(!1),Z.current.currentSide&&(setTimeout(()=>Yo(),50),et(null)),b.target.classList.contains("email-pane__handle")||Qo(),window.localStorage.setItem(r.LOCAL_STORAGE_ITEMS.em_code_mode_pane_sizes,JSON.stringify(j))},[Yo,Z,ve,et,Qo]),Za=b=>j=>{j.target.classList.contains("email-pane__handle")&&(j.preventDefault(),Ya.current=j.target.parentNode.offsetWidth,Qa.current=j.pageX,Xa.current=Av(),et(b),Dn.current=b)},zr=b=>{const j=Se.current,{currentSide:F}=Z.current;typeof b=="string"&&(!F||F===b)?(te.querySelector(".email-pane__iframe").style.width="calc(100% + 1px)",b==="right"?(j.style.borderRightColor=N.colorPrimary,j.style.borderRightWidth="2px"):(j.style.borderLeftColor=N.colorPrimary,j.style.borderLeftWidth="2px",te.querySelector(".email-pane__iframe").style.marginLeft="-1px")):F||(Qo(),te.querySelector(".email-pane__iframe").style.width="1px",te.querySelector(".email-pane__iframe").style.removeProperty("margin-left"))},xv=(0,l.useCallback)(()=>{ve(!0)},[ve]),Xo=(0,l.useCallback)(b=>{const{currentSide:j}=Z.current;if(!j)return;const F=(b.pageX-Qa.current)*2,Pe=Ya.current+(j==="left"?-F:F),Oe=Math.min(Xa.current,1200);Pe>318&&Pe<Oe&&(m(r.setEmailWidth(Math.min(Pe,1200))),xe.current?.resize())},[m,Z]),Jo=(0,l.useCallback)(b=>{if(Z.current.isResizing)if(pe==="bottom"){const j=Be.current.getBoundingClientRect().height,F=Be.current.getBoundingClientRect().top,Pe=(b.clientY-F)/j*100;if(Pe<20||Pe>80)return;De(Pe),Mt()}else{const j=Be.current.getBoundingClientRect().width,F=Be.current.getBoundingClientRect().left,Pe=(b.clientX-F)/j*100,Oe=Se.current.getBoundingClientRect().width;if(v.desktopMobileSwitchPanel&&typeof Oe=="number"&&Oe<=425&&m(r.setEmailWidth(425)),Pe<20||Pe>80)return;De(Pe)}},[Z,De,pe,Mt,m,v.desktopMobileSwitchPanel]);(0,l.useEffect)(()=>{Mt()},[Y,Mt]);const Pv=b=>{b?.stopPropagation?.();const j=Re==="light"?r.DARK:r.LIGHT;p.send({operation:r.EVENT_TYPES.SANDBOX_SWITCH_THEME,data:{theme:j}}),Ue(j)},el=(b="panel")=>{const j=b==="panel",F=Re===r.DARK,Pe={size:j?18:16,strokeWidth:j?v.iconStrokeWidth:2};return(0,a.jsx)(_.ui_kit$Tooltip,{title:d(F?"Light theme":"Dark theme"),placement:j?"top":"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:j?F?"primary":"text":"default",icon:F?(0,a.jsx)(r.EmIcons,{icon:"LightMode",component:_.icons$LightMode,...Pe}):(0,a.jsx)(r.EmIcons,{icon:"DarkMode",component:_.icons$DarkMode,...Pe}),shape:"circle",size:j?void 0:"small",onClick:Pv,className:"toggle_view theme_view email-pane__theme-toggle",style:j?void 0:{left:4,top:4,zIndex:999,padding:0,position:"absolute"}})})},Zo=b=>{const j=typeof b=="number"?Math.min(b,1200):b;m(r.setEmailWidth(j)),setTimeout(()=>Yo(j),700);const F=typeof j=="number"?j:j==="100%"?"full":j,Pe=typeof j=="number"&&j<=425?"mobile":"desktop";A({event:"change",action:"change_email_size",email_id:e?.id||y||f,project_id:O?.id||g,width:F,view_type:Pe})};(0,l.useEffect)(()=>{const b=new h.Disposable;return b.addDisposable(r.addWindowListenerFromShadow(te,"mousedown",_t,!0)),b.addDisposable(r.addWindowListenerFromShadow(te,"click",Ga)),b.addDisposable(r.addWindowListenerFromShadow(te,"mouseup",j=>Ja(j),!0)),()=>{b.dispose()}},[te,Ga,_t,Ja]),(0,l.useEffect)(()=>{const b=Me.current;if(!b||typeof ResizeObserver!="function")return;const j=new ResizeObserver(Mt);return j.observe(b),()=>j.disconnect()},[Mt,v.sidePanelFloating]),(0,l.useEffect)(()=>(window.addEventListener("scroll",Mt,!0),window.addEventListener("mousemove",Xo,!0),window.addEventListener("mousemove",Jo),window.addEventListener("keydown",_n),()=>{window.removeEventListener("mousemove",Xo,!0),window.removeEventListener("mousemove",Jo),window.removeEventListener("scroll",Mt,!0),window.removeEventListener("keydown",_n)}),[Mt,Xo,Jo,_n]);const Rv=b=>{const j=Y?"visual":"code",F=!Y;if(Y?E.toggle():typeof b=="string"?(E.setDirection(b),!Y&&E.toggle()):E.toggle(),F){const Pe=Xe==="block"?"block":"email",Oe=typeof b=="string"?b:pe||"toggle";A({event:"activate",action:"activate_code_mode",entity_type:Pe,entity_id:e?.id||y||f,project_id:O?.id||g,code_mode_direction:Oe})}A({event:"change",action:"change_editor_mode",editor_mode:j,entity_id:e?.id||y||f,project_id:O?.id||g}),m(r.resetToLastActiveSettingsTab()),setTimeout(()=>{m(Xe==="block"?r.setElementSettings({type:null}):r.setElementSettings$1({type:null}))},300),p.send({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_ACTIVE_RESET}),m(r.resetPanes())};(0,l.useEffect)(()=>{v.emailPaneDesktopSize&&m(r.setEmailWidth(v.emailPaneDesktopSize))},[m,v.emailPaneDesktopSize]);const jv=()=>{hn(r.BLOCKS),Bn("project")};return(0,l.useEffect)(()=>{i&&jv()},[i]),(0,a.jsx)(r.ElementEntityKindProvider,{kind:Xe,children:(0,a.jsxs)(up,{className:(0,rt.default)("email-pane",{"email-pane_code-mode":Y,"email-pane_only_code_mode_mobile":v.onlyCodeModeInMobile,"email-pane_code-mode-bottom":Y&&pe==="bottom","email-pane_no-element-navigation":!v.switchDesktopMobilePropsEnabled&&!v.stepToOtherElementEnabled&&!v.deleteButtonEnabled,"email-pane_is-mobile":ge,"email-pane_path-enabled":v.pathEnabled}),sidePanelFloating:!!v.sidePanelFloating,isCodeMode:!!Y,codeModeDirection:String(pe),children:[(0,a.jsxs)(wp,{className:"email-pane__container",ref:We,children:[(0,a.jsx)(vp,{isCodeMode:Y,codeModeDirection:pe}),(0,a.jsx)(hp,{isShowMobileSettings:ge,headless:!!P,templateNotEmAlertEnabled:!!v.templateNotEmAlertShow}),(0,a.jsxs)(_.ui_kit$Row,{ref:Be,className:(0,rt.default)("email-pane__row",{"email-pane__left":Y&&pe==="right","email-pane__right":Y&&pe==="left","email-pane__bottom":Y&&pe==="bottom","email-pane__sizeSwitcher":v.desktopMobileSwitchPanel,"email-pane__reverse":v.menuDirection==="left","email-pane__pinch":!v.sidePanelFloating}),children:[(0,a.jsxs)(mp,{isCodeMode:Y,codeModeDirection:pe,sidePanelFloating:v.sidePanelFloating,contentWrapperRef:yv,children:[(0,a.jsx)("div",{className:"email-pane__iframe-scroll-top",id:"iframe-scroll-top"}),v.desktopMobileSwitchPanel&&(0,a.jsxs)(_.ui_kit$Space,{className:"email-pane__sizes-panel-wrapper",orientation:"vertical",size:10,children:[(0,a.jsxs)(_.ui_kit$Space,{className:"email-pane__sizes-panel",size:0,children:[el("panel"),(0,a.jsx)(_.ui_kit$Tooltip,{title:d("Desktop view"),placement:"top",open:jn,children:(0,a.jsx)(_.ui_kit$Button,{type:ge?"text":"primary",icon:(0,a.jsx)(r.EmIcons,{icon:"DesktopOutlined",component:_.icons$DesktopOutlined,size:18,strokeWidth:v.iconStrokeWidth}),shape:"circle",onClick:()=>Zo(v.emailPaneDesktopSize||1e3),className:"toggle_view desktop_view"})}),(0,a.jsx)(_.ui_kit$Tooltip,{title:d("Mobile view"),placement:"top",open:gn,children:(0,a.jsx)(_.ui_kit$Button,{type:ge?"primary":"text",icon:(0,a.jsx)(r.EmIcons,{icon:"MobileOutlined",component:_.icons$MobileOutlined,size:18,strokeWidth:v.iconStrokeWidth}),shape:"circle",onClick:()=>Zo(425),className:"toggle_view mobile_view"})})]}),v.codeSideEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:d("Code mode"),placement:"right",children:(0,a.jsx)(_.ui_kit$Button,{type:Y?"primary":"default",icon:(0,a.jsx)(r.EmIcons,{icon:"Code",component:_.icons$Code}),shape:"circle",onClick:()=>Rv("right")})})]}),(0,a.jsxs)(_.ui_kit$Row,{className:(0,rt.default)("email-pane__col-wrapper",{container:Y&&pe==="bottom"||!Y,"email-pane__col-wrapper_reverse":v.menuDirection==="left","email-pane__col-wrapper_pinch":!v.sidePanelFloating}),style:{flexGrow:1,maxWidth:"unset",paddingTop:v.desktopMobileSwitchPanel&&Y&&pe!=="bottom"?"60px":""},children:[(0,a.jsxs)(_.ui_kit$Col,{className:"email-pane__col email-pane__col_preview",style:{flexGrow:1,maxWidth:"unset"},ref:v.sidePanelFloating?null:Me,children:[v.desktopMobileSwitchRule&&(0,a.jsx)(Cd,{onSelectWidth:Zo,themeToggle:el("rule")}),(0,a.jsxs)(pp,{maxPaneWidth:1200,isCodeMode:Y,codeModeDirection:pe,isShowMobileSettings:ge,desktopMobileSwitchPanel:v.desktopMobileSwitchPanel,children:[(0,a.jsx)("div",{className:"email-pane__handle left",onMouseDown:Za("left"),onMouseEnter:()=>zr("left"),onMouseLeave:zr}),(0,a.jsx)("div",{className:"email-pane__handle right",onMouseDown:Za("right"),onMouseEnter:()=>zr("right"),onMouseLeave:zr}),(0,a.jsx)(gp,{wrapperRef:Se,children:(0,a.jsx)(Pp,{ref:xe,className:"email-pane__iframe",email:e,handlerSendPosition:Mt,clip:hv})})]})]}),(0,a.jsx)(_.ui_kit$Col,{style:{display:Y&&pe!=="bottom"||v.disableSideMenu?"none":"initial"},ref:Vo,onPointerEnter:kp,className:(0,rt.default)("email-pane__content-col email-pane__content-col_menu email-pane__content-col_tabs email-pane__col email-pane__col_settings",{"email-pane__col_disabled":U===r.DISABLED_TAB}),children:(!Y||pe==="bottom")&&J&&(0,a.jsx)(_.ui_kit$Tabs,{className:(0,rt.default)("email-pane__col_settings-inner",{"email-pane__col_settings-inner_reverse":v.menuDirection==="left"}),size:"medium",activeKey:U,onTabClick:Sv,renderTabBar:Sp,tabPlacement:"right",items:Un,tabBarExtraContent:Bt&&(0,a.jsx)("div",{style:{paddingTop:15,textAlign:"center"},children:ue?(0,a.jsx)(_.ui_kit$Switch,{variant:"editorMode",checkedChildren:"Pro",unCheckedChildren:"Pro",onChange:Va,checked:$t}):(0,a.jsx)(_.ui_kit$Switch,{variant:"editorMode",checkedChildren:"Pro",unCheckedChildren:"Pro",onChange:Va,defaultChecked:Nn})})})})]}),(0,a.jsx)("div",{className:"email-pane__iframe-scroll-bottom",id:"iframe-scroll-bottom"})]}),(0,a.jsxs)(fp,{isCodeMode:Y,codeModeDirection:pe,children:[(0,a.jsx)("div",{className:"email-pane__code-divider",onMouseDown:xv}),(0,a.jsx)("div",{className:"code-mode__pane code-mode__pane_editor email-pane__pane email-pane__pane_editor",children:(0,a.jsx)("div",{className:"code-mode__pane-content email-pane__pane-content",children:ie&&(0,a.jsx)(xp,{email:e,setOtherUsers:Ze,readOnly:v.lockEditor,newEmailAiGeneratorRef:fn})})})]})]}),v.pathEnabled&&(0,a.jsxs)("div",{className:"email-pane__paths",children:[(0,a.jsx)(su,{elementPath:Ye}),(0,a.jsx)(lu,{fallbackHtml:e?.html})]}),(0,a.jsx)("div",{className:"collaborator-list",children:(0,a.jsx)(r.CollaboratorList,{users:ze,isEditor:!1,isPlugin:!0,token:N})})]}),(0,a.jsx)(bp,{isCodeMode:Y,codeModeDirection:pe,email:e,onClosePanel:Lt}),(0,a.jsx)(Pu,{}),(0,a.jsx)(r.PlanUpgradePrompt,{open:gt,onCancel:bv,onTrialActivated:Ev,initialSlide:ce}),st&&qe.exceeded?(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(oo,{open:Ne,onClose:je,title:d(st.titleKey),subtitle:d(st.subtitleKey),usageResource:st.usageResource,previousDisplay:r.presetLimitDisplay(qe.exceeded.previousLimit),nextDisplay:r.presetLimitDisplay(qe.exceeded.nextLimit),onChangePlan:Yt})}):null,(0,a.jsx)(cu,{open:ft,onClose:lt}),(0,a.jsx)(uu,{open:G,onClose:V})]})})};us.propTypes={};var Mp=e=>(0,a.jsx)(tp,{children:(0,a.jsx)(op,{children:(0,a.jsx)(lp,{children:(0,a.jsx)(us,{...e})})})}),Np=(0,l.memo)(Mp),Dp=({open:e,onClose:t})=>{const{__:n}=r.useI18n(),o=r.getSupportEmail(),[i,s=""]=n("To send a test email, you need to confirm your email address. If you haven’t received the confirmation link, contact support in the chat or email {supportEmail}.").split("{supportEmail}");return(0,a.jsx)(_.ui_kit$Modal,{width:440,open:e,onCancel:t,title:(0,a.jsxs)("div",{style:{paddingBottom:8},children:[(0,a.jsx)(r.EmIcons,{icon:"EmailConfirmation",component:_.icons$EmailConfirmation,size:20,strokeWidth:2})," ",n("Email confirmation required")]}),footer:[(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",onClick:t,children:n("Got it")},"ok")],children:(0,a.jsxs)("p",{children:[i,(0,a.jsx)("a",{href:`mailto:${o}`,children:o}),s]})})},Qn=e=>{const t=r.useCurrentUser(),[n,o]=(0,l.useState)({owner:!1,admin:!1,user:!1}),i=r.useProjectData(),{data:s}=r.useGetProjectQuery(e,{skip:!e||!t.id||!!i}),c=i||s;return(0,l.useEffect)(()=>{if(c){const d=r.getMyProjectRole(c,t);o({owner:d==="owner",admin:d==="admin",user:d==="user"})}},[c,t]),n},co=r.getLimitUpgradePresetDefinition("preview_exceeded"),ps=({emailElement:e,isCollaborationEditor:t})=>{const{__:n}=r.useI18n(),o=r.useDispatch(),i=Vr(),s=r.useOpenPlanCatalog(),c=r.useSendPostMessage(),{blockId:d}=r.useRouteParams(),u=r.useRouteEmailId(),p=r.useSelector(r.selectActiveModal$1)===r.MODALS.SEND_TEST_EMAIL,f=kn(p),[g,y]=(0,l.useState)(!1),[m,E]=r.useSendLivePreviewMutation(),k=r.useCurrentUser(),w=r.useDocumentHistoryReader(),v=r.useProjectPlanLimitPreflight(),{owner:x}=Qn(),P=Jr(),K=Pd(),J=r.useContentReader(),N=r.useSelector(r.selectIsPanelHistoryCollapsed),L=r.useSelector(r.selectIsCodeMode),A=r.useSelector(r.selectCodeModeDirection),{token:O}=(0,_.ui_kit$useToken)(),z=r.useNotification(),B=r.useAppConfig(),U=e.hasOwnProperty("type")?r.BLOCK:r.EMAIL,de=r.useEventEmitter(h.events.ON_SHARE_ID),me=r.useEventEmitter(h.events.ON_SHOW_PREVIEW_ID),[H,Z]=(0,l.useState)(!1),[De,ve]=(0,l.useState)(0),[et,be]=(0,l.useState)(!1),fe=kn(et),Y=(0,l.useCallback)(()=>be(!1),[]),pe=(0,l.useCallback)(()=>{be(!1),s()},[s]),[ie,se]=(0,l.useState)(n("—")),[Ae,Te]=(0,l.useState)(!1),Fe=r.useProjectData(),X=r.usePlanFeatureGate("version_history"),Ee=r.usePlanFeatureGate("code_editor"),Ie=r.usePlanFeatureGate("preview_service"),ge=r.usePlanFeatureGate("undo_redo"),Re=r.isEditorLockedByPlan(Fe,{isPlugin:!0}),Ue=r.usePushToDataLayer(),C=e?.project,T=he=>{const Ge=U==="block"?"block":"email";typeof he=="string"?(i.setDirection(he),!L&&i.toggle()):i.toggle(),Ue({event:"activate",action:"activate_code_mode",entity_type:Ge,entity_id:e?.id||u||d,project_id:e?.project||C}),setTimeout(()=>{o(U==="block"?r.setElementSettings({type:null}):r.setElementSettings$1({type:null}))},300),c({operation:r.EVENT_TYPES.SANDBOX_ELEMENT_ACTIVE_RESET}),Ee.isLocked&&(Z(!0),ve(r.FEATURE_UPSELL_SLIDE.code_editor))},R=(0,l.useCallback)(async()=>!0,[v]),D=async()=>{if(Re){Z(!0),ve(8);return}await R()&&(o(r.openModal$1(r.MODALS.SEND_TEST_EMAIL)),Ue({event:"open",action:"open_test_email_modal",entity_type:U==="block"?"block":"email",entity_id:e?.id||u||d,project_id:e?.project||C}))},I=()=>{Z(!0),ve(r.FEATURE_UPSELL_SLIDE.undo_redo)},S=()=>{P.undo()},ae=()=>{P.redo()},we=async()=>{const he=(await de.fire({project:C,id:u})).find(Ge=>Ge===!1||typeof Ge=="string");he!==!1&&navigator.clipboard.writeText(he||r.buildEmailRawShareUrl(u,C)).then(()=>{z.success(n("A shareable link to this page has been copied to the clipboard.")),Ue({event:"click",action:"share_email",entity_type:U==="block"?"block":"email",entity_id:e?.id||u||d,project_id:e?.project||C})})},Ye=async()=>{if(!g){if(!await R())return;const he={email:u,subject:encodeURIComponent("#"+e.project+" "+e.title).replaceAll(/%20/gi,"+").replaceAll(/%0A/gi,"%0D%0A"),content:encodeURIComponent(J()).replaceAll(/%20/gi,"+").replaceAll(/%0A/gi,"%0D%0A")};m(he),y(!0),Ue({event:"click",action:"open_email_inbox_tests",entity_type:U==="block"?"block":"email",entity_id:e?.id||u||d,project_id:e?.project||C})}},Qe=(0,l.useCallback)(async()=>{await R()&&(se(n("—")),be(!0))},[n,R]);(0,l.useEffect)(()=>{E.isError&&(z.error(E),y(!1))},[E]),(0,l.useEffect)(()=>{if(E.isSuccess&&g){if(E.data?.status===401)z.error({title:E.data.code,description:E.data.message});else if(E.data){let he=document.createElement("A");he.setAttribute("target","_blank"),he.setAttribute("href",E.data.message),he.click()}y(!1)}},[E,g,z]);const[ze,Ze]=(0,l.useState)(!1),pt=()=>{c({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:N}),o(r.switchIsPanelHistoryCollapsed(!N))},bt=()=>w(e?.id),ft=()=>{N?(Ze(!0),bt().then(he=>{he.isSuccess?he.data.data.length:he.isError&&z.error(he),pt(),o(r.setActiveSettingsTab(r.HISTORY)),Ze(!1),Ue({event:"open",action:"open_version_control",entity_type:U==="block"?"block":"email",entity_id:e?.id||u||d,project_id:e?.project||C}),X.isLocked&&(Z(!0),ve(r.FEATURE_UPSELL_SLIDE.version_history))})):(o(r.resetToLastActiveSettingsTab()),pt())},lt=()=>{N||(pt(),o(r.resetToLastActiveSettingsTab())),L&&i.toggle(),Z(!1)};let G=[];const V=(0,l.useCallback)(async()=>{const he=await me.fire({project:C,id:u});he.find(Ge=>Ge===!1||typeof Ge=="string")!==!1&&(window.open(he.find(Ge=>Ge)||r.buildEmailRawSharePath(u,C)),Ue({event:"click",action:"open_email_preview",entity_type:U==="block"?"block":"email",entity_id:e?.id||u||d,project_id:e?.project||C}))},[me,C,u,Ue,U,e,d]),te=(0,l.useCallback)(async()=>{window.open(r.buildGetElementPreviewPath(r.EMAIL,u,C)),Ue({event:"click",action:"open_web_version",entity_type:U==="block"?"block":"email",entity_id:e?.id||u||d,project_id:e?.project||C})},[C,u,Ue,U,e,d]);B.previewModeEnabled&&G.push({key:"Preview_mode",icon:(0,a.jsx)(r.EmIcons,{icon:"EyeOutlined",component:_.icons$EyeOutlined,size:18,strokeWidth:B.iconStrokeWidth}),label:n("Preview mode"),onClick:V}),B.livePreviewEnabled&&G.push({key:"Live_preview",icon:g?(0,a.jsx)(r.EmIcons,{icon:"LoadingOutlined",component:_.icons$LoadingOutlined,style:{fontSize:16}}):(0,a.jsx)(r.EmIcons,{icon:"CheckCircleVerified",component:_.icons$CheckCircleVerified,size:18,strokeWidth:B.iconStrokeWidth}),label:n("Live preview"),onClick:k.id?.toString()===e.project_author?.toString()&&k?.subscription?.post_name==="community"&&x?Qe:Ye}),B.webversionEnabled&&G.push({key:"Web version",icon:(0,a.jsx)(r.EmIcons,{icon:"Web",component:_.icons$Web,size:18,strokeWidth:B.iconStrokeWidth}),label:n("Web version"),onClick:te}),B.sharePreviewEnabled&&G.push({key:"Share",icon:(0,a.jsx)(r.EmIcons,{icon:"ShareAltOutlined",component:_.icons$ShareAltOutlined,size:18,strokeWidth:B.iconStrokeWidth}),label:n("Share"),onClick:we,className:"em-analytics__email-share"});const ue=[{key:"Left_mode",icon:(0,a.jsx)(r.EmIcons,{icon:"PanelLeft",component:_.icons$PanelLeft,size:18,strokeWidth:B.iconStrokeWidth,style:{color:A==="left"&&L?O.colorPrimary:"inherit"}}),label:n("Left Code panel"),onClick:()=>T("left")},{key:"Right_mode",icon:(0,a.jsx)(r.EmIcons,{icon:"PanelLeft",component:_.icons$PanelLeft,size:18,strokeWidth:B.iconStrokeWidth,style:{transform:"rotate(180deg)",color:A==="right"&&L?O.colorPrimary:"inherit"}}),label:n("Right Code panel"),onClick:()=>T("right")},{key:"Bottom_mode",icon:(0,a.jsx)(r.EmIcons,{icon:"PanelLeft",component:_.icons$PanelLeft,size:18,strokeWidth:B.iconStrokeWidth,style:{transform:"rotate(-90deg)",color:A==="bottom"&&L?O.colorPrimary:"inherit"}}),label:n("Bottom Code panel"),onClick:()=>T("bottom")}];return(0,a.jsxs)("div",{className:"email-preview-menu email-preview-menu_new",children:[(0,a.jsxs)(_.ui_kit$Space,{size:32,children:[(0,a.jsxs)(_.ui_kit$Space,{className:"email-preview-menu__versions",size:8,style:{borderRadius:`calc(${r.emCssVar("borderRadius")} * 1px)`},children:[(0,a.jsx)(_.ui_kit$Tooltip,{title:n(t?r.COLLABORATION_EDITOR_WARNING_TEXT:"Undo (Ctrl+Z)"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:"text",icon:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.EmIcons,{icon:"UndoOutlined",component:_.icons$UndoOutlined,size:22,strokeWidth:B.iconStrokeWidth}),ge.isLocked&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:B.iconStrokeWidth,className:"free-mode-firewall-icon"})]}),onClick:ge.isLocked?I:S,disabled:!ge.isLocked&&!K.canUndo})}),(0,a.jsx)(_.ui_kit$Tooltip,{title:n(t?r.COLLABORATION_EDITOR_WARNING_TEXT:"Redo (Ctrl+Shift+Z)"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:"text",icon:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.EmIcons,{icon:"RedoOutlined",component:_.icons$RedoOutlined,size:22,strokeWidth:B.iconStrokeWidth}),ge.isLocked&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:B.iconStrokeWidth,className:"free-mode-firewall-icon"})]}),onClick:ge.isLocked?I:ae,disabled:!ge.isLocked&&!K.canRedo})}),B.historyEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:n("Version history"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:N?"text":"primary",ghost:!N,onClick:ft,disabled:e.isNew||ze,className:"email-preview-menu__history",icon:ze?(0,a.jsx)(_.ui_kit$Spin,{size:"small"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.EmIcons,{icon:"HistoryOutlined",component:_.icons$HistoryOutlined,size:22,strokeWidth:B.iconStrokeWidth,className:"email-preview-menu__list-item-icon email-preview-menu__list-item-icon_revert"}),X.isLocked&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:B.iconStrokeWidth,className:"free-mode-firewall-icon"})]})})})]}),(0,a.jsxs)(_.ui_kit$Space,{size:8,style:{borderRadius:`calc(${r.emCssVar("borderRadius")} * 1px)`},children:[B.codeEnabled&&(0,a.jsx)(_.ui_kit$Dropdown,{arrow:!0,placement:"bottom",menu:{items:ue},trigger:"hover",mouseEnterDelay:0,className:"email-preview-menu__code",children:(0,a.jsx)(_.ui_kit$Button,{type:L?"primary":"text",ghost:L,icon:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.EmIcons,{icon:"Code",component:_.icons$Code,size:22,strokeWidth:B.iconStrokeWidth}),Ee.isLocked&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:B.iconStrokeWidth,className:"free-mode-firewall-icon"})]}),onClick:T})},"Code mode"),B.previewIconEnabled&&(Ie.isLocked?(0,a.jsx)(_.ui_kit$Tooltip,{title:n("Preview mode"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{type:"text",icon:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.EmIcons,{icon:"EyeOutlined",component:_.icons$EyeOutlined,size:22,strokeWidth:B.iconStrokeWidth,className:"email-preview-menu__list-item-icon"}),(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:B.iconStrokeWidth,className:"free-mode-firewall-icon"})]}),onClick:()=>{Z(!0),ve(r.FEATURE_UPSELL_SLIDE.preview_service)}})}):(0,a.jsx)(_.ui_kit$Dropdown,{arrow:!0,placement:"bottom",menu:{items:G},className:"email-preview-menu__preview",children:(0,a.jsx)(_.ui_kit$Button,{type:"text",target:"_blank",rel:"noreferrer",icon:(0,a.jsx)(r.EmIcons,{icon:"EyeOutlined",component:_.icons$EyeOutlined,size:22,strokeWidth:B.iconStrokeWidth,className:"email-preview-menu__list-item-icon"}),onClick:B.previewModeEnabled?V:void 0})},"Preview")),B.sendTestEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:n("Send a test email"),placement:"bottom",children:(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__email-open-test email-preview-menu__test",type:"text",icon:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.EmIcons,{icon:"SendOutlined",component:_.icons$SendOutlined,size:22,strokeWidth:B.iconStrokeWidth,className:"email-preview-menu__list-item-icon"}),Re&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:14,strokeWidth:B.iconStrokeWidth,className:"free-mode-firewall-icon"})]}),onClick:D})})]})]}),f&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Iu,{isModalVisible:p,email:e})}),(0,a.jsx)(Dp,{open:Ae,onClose:()=>Te(!1)}),(0,a.jsx)(r.PlanUpgradePrompt,{open:H,onCancel:lt,initialSlide:De}),fe&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(oo,{open:et,onClose:Y,title:n(co.titleKey),subtitle:n(co.subtitleKey),usageResource:co.usageResource,previousDisplay:ie,nextDisplay:r.presetLimitDisplay("infinity"),onChangePlan:pe})})]})};ps.propTypes={};var Fp=[["brace-percent",/<!--\{%/],["brace-hash",/<!--\{#/],["proscript",/<!--\[%/],["getresponse",/<!--\[\[(?:if|else\]\]|endif\]\])/i],["mailchimp",/<!--\*\|/],["expert-sender",/<!--<\/?(?:if|else|var)/i]],Bp=200;function ms(e=new Set){const t=new Set;return(n,o)=>{if(!Fp.some(([s,c])=>!e.has(s)&&c.test(n)))return;const i=o??`new:${n.length}:${n.slice(0,200)}`;t.has(i)||(t.size>=Bp&&t.clear(),t.add(i))}}function fs(){return{isConfigured:()=>!1,toEditorForm:e=>e,toOutputForm:e=>e,keepWrappedOnOutput:new Set,editorPolicy:{},warnAboutUnconfiguredInput:ms()}}var $p=fs();function on(e){return e?.getInstance(h.TEMPLATE_DIRECTIVES_ID)??$p}function Up({html:e,renderGuid:t,showToken:n,showId:o,...i},s){const{requested:c}=r.getCurrentProject(s),d=r.getAppConfig(s);return r.filterUndefined({...i,code:on(s).toOutputForm(e),project:c===void 0?i.project:c,utm_parameters:d.UTMEnabled?i.utm_parameters:void 0,tags:void 0,template:void 0,guid:void 0,emailtags:void 0,project_title:void 0,project_author:void 0,is_template:void 0,is_inited:void 0})}var zp=zt.__commonJSMin(((e,t)=>{r.init__polyfill_node_global(),(function(n,o){typeof define=="function"&&define.amd?define([],o):typeof e<"u"?o():(o(),n.FileSaver={})})(e,function(){"use strict";function n(p,f){return typeof f>"u"?f={autoBom:!1}:typeof f!="object"&&(f={autoBom:!f}),f.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(p.type)?new Blob(["\uFEFF",p],{type:p.type}):p}function o(p,f,g){var y=new XMLHttpRequest;y.open("GET",p),y.responseType="blob",y.onload=function(){u(y.response,f,g)},y.onerror=function(){},y.send()}function i(p){var f=new XMLHttpRequest;f.open("HEAD",p,!1);try{f.send()}catch{}return 200<=f.status&&299>=f.status}function s(p){try{p.dispatchEvent(new MouseEvent("click"))}catch{var f=document.createEvent("MouseEvents");f.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),p.dispatchEvent(f)}}var c=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof r._polyfill_node_global_default=="object"&&r._polyfill_node_global_default.global===r._polyfill_node_global_default?r._polyfill_node_global_default:void 0,d=c.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),u=c.saveAs||(typeof window!="object"||window!==c?function(){}:"download"in HTMLAnchorElement.prototype&&!d?function(p,f,g){var y=c.URL||c.webkitURL,m=document.createElement("a");f=f||p.name||"download",m.download=f,m.rel="noopener",typeof p=="string"?(m.href=p,m.origin===location.origin?s(m):i(m.href)?o(p,f,g):s(m,m.target="_blank")):(m.href=y.createObjectURL(p),setTimeout(function(){y.revokeObjectURL(m.href)},4e4),setTimeout(function(){s(m)},0))}:"msSaveOrOpenBlob"in navigator?function(p,f,g){if(f=f||p.name||"download",typeof p!="string")navigator.msSaveOrOpenBlob(n(p,g),f);else if(i(p))o(p,f,g);else{var y=document.createElement("a");y.href=p,y.target="_blank",setTimeout(function(){s(y)})}}:function(p,f,g,y){if(y=y||open("","_blank"),y&&(y.document.title=y.document.body.innerText="downloading..."),typeof p=="string")return o(p,f,g);var m=p.type==="application/octet-stream",E=/constructor/i.test(c.HTMLElement)||c.safari,k=/CriOS\/[\d]+/.test(navigator.userAgent);if((k||m&&E||d)&&typeof FileReader<"u"){var w=new FileReader;w.onloadend=function(){var P=w.result;P=k?P:P.replace(/^data:[^;]*;/,"data:attachment/file;"),y?y.location.href=P:location=P,y=null},w.readAsDataURL(p)}else{var v=c.URL||c.webkitURL,x=v.createObjectURL(p);y?y.location=x:location.href=x,y=null,setTimeout(function(){v.revokeObjectURL(x)},4e4)}});c.saveAs=u.saveAs=u,typeof t<"u"&&(t.exports=u)})})),sn=zp(),In="NEXT_BUTTON",uo="SAVE_BUTTON",po="KEYBOARD",Gp="EXTERNAL",Wp=new Set([uo,In,po]);function Hp(e){return e!=null&&e!==""&&Wp.has(e)}function gs(e){if(!e||e==="all")return;const t=Number(e);return Number.isFinite(t)?[t]:void 0}var hs=(0,l.createContext)(null);function qp(){const e=(0,l.useContext)(hs);if(!e)throw new Error("useEmailSaveController must be used within EmailSaveContext.Provider");return e}var Vp=2;function Kp({email:e,documentSession:t,save:n,saveState:o}){const i=r.useDispatch(),{__:s}=r.useI18n(),c=r.useEditorProjectId();r.useRouteEmailId();const d=+c,u=Number.isFinite(d)&&d>0?d:e?.project,p=r.useCookieManager(),f=r.useContainer(),g=r.useNotification(),y=r.useAppConfig(),m=r.useConfigSource(),[E,k]=(0,l.useState)(0),w=(0,l.useRef)(""),[v,x]=(0,l.useState)(!1),P=r.useEventEmitter(h.events.ON_NEXTBUTTON_CLICK_ID),K=r.useEventEmitter(h.events.ON_SAVEBUTTON_CLICK_ID);r.useEvent(h.events.ON_EMAIL_INIT_ID);const J=y.activeNextButton===!1,N=y.disableDoubleClickNextButton!==!1,L=(0,l.useRef)(!1),A=(0,l.useRef)(void 0),O=(0,l.useRef)(null),z=(0,l.useRef)(null),B=(0,l.useRef)(e);B.current=e;const U=(0,l.useCallback)(()=>{A.current=void 0},[]),de=(0,l.useCallback)(X=>{m.merge({activeNextButton:!X},"user")},[m]),me=(0,l.useCallback)((X,Ee)=>{const Ie=r.saveRefusalReason(Ee);if(Ie==="locked"){g.error({id:"EMAIL_ACCESS_TO_LOCKED_ERROR",data:r.getEmailDesc(X),message:s("No access to edit the letter.")});return}if(Ie==="too-many-tags"){g.error({id:"EMAIL_TOO_MANY_TAGS_ERROR",data:r.getEmailDesc(X),message:s("Maximum 10 tags available.")});return}const ge=r.failedTerms(Ee);if(ge){ge.failed.forEach(Re=>{if(ge.kind==="group"){g.fromError("GROUP_CREATING_ERROR",{id:Re.id??0,name:Re.name,parent:Re.parent??0},Ee);return}g.fromError("TAG_CREATING_ERROR",Re.name,Ee)});return}g.fromError(X.isNew?"EMAIL_CREATING_ERROR":"EMAIL_EDITING_ERROR",r.getEmailDesc(X),Ee)},[g,s]),H=(0,l.useCallback)(X=>{const Ee=Hp(X),Ie=()=>{x(!1),X===In&&(L.current=!1,de(!1))};if(!e){Ie();return}const ge=async()=>{(Ue=>{n("publish",{project:Ue.isNew?u:Ue.project,folder:gs(p.get(r.APP_COOKIES.em_folder)),source:X}).then(C=>{if(x(!1),L.current=!1,!C){X===In&&de(!1),Ee&&(me(Ue,o().error),U());return}Ee&&(g.success({id:"EMAIL_SAVING_SUCCESS",message:s("The email was successfully saved."),data:r.getEmailDesc(Ue)}),U())})})(e)};x(!0),ge()},[e,i,c,s,t,p,u,g,me,n,o,de,U]);r.useCommand(r.SAVE_COMMAND_ID,(0,l.useCallback)(X=>H(X||Gp),[H]));const Z=(0,l.useRef)(void 0),De=(0,l.useRef)(H);De.current=H;const ve=(0,l.useCallback)(X=>{w.current=X,k(Ee=>Ee+1)},[]);(0,l.useEffect)(()=>()=>{Z.current!==void 0&&clearTimeout(Z.current)},[]),(0,l.useEffect)(()=>{if(E===0)return;const X=w.current;B.current?.isNew&&(A.current=X),Z.current!==void 0&&clearTimeout(Z.current),Z.current=setTimeout(()=>{Z.current=void 0,De.current(X)})},[E]);const et=(0,l.useCallback)(X=>{(X.ctrlKey||X.metaKey)&&X.keyCode===83&&(X.preventDefault(),ve(po))},[ve]);(0,l.useEffect)(()=>(document.addEventListener("keydown",et),()=>{document.removeEventListener("keydown",et)}),[et]);const be=(0,l.useCallback)(X=>{const Ee=X.data.operation,Ie=X.data.action;Ee===r.EVENT_TYPES.APPLICATION_ACTION&&Ie==="save_email"&&ve(po)},[ve]);r.useListenPostMessage(be),(0,l.useEffect)(()=>{e?.isNew&&(z.current=null,O.current=null)},[e?.isNew,e?.renderGuid]),(0,l.useEffect)(()=>{L.current=!1},[e?.id]);const fe=p.get(r.APP_COOKIES.em_folder),Y=f?r.provideAutosaveUiFacts(f):void 0;(0,l.useEffect)(()=>{Y?.set({...Y?.get()??{isUserBusy:!1,saveContext:{}},saveContext:{project:u,folder:gs(fe)}})},[Y,u,fe]);const pe=(0,l.useRef)(!1),ie=o().failures;(0,l.useEffect)(()=>{ie>=Vp&&!pe.current&&(pe.current=!0,g.warning({message:s("Changes are not being saved. Check your connection.")})),ie===0&&(pe.current=!1)},[ie,g,s]);const se=v,Ae=o().saving,Te=(0,l.useCallback)(X=>{ve(X||uo)},[ve]),Fe=(0,l.useCallback)(async(X,Ee)=>{if(X===In){if(L.current)return;L.current=!0;try{N&&de(!0),(await P.fire(Ee)).every(Ie=>Ie!==!1)?ve(In):(de(!1),L.current=!1)}catch(Ie){g.fromError("NEXT_BUTTON_CLICK_EVENT_ERROR",r.getEmailDesc(Ee),Ie,!0),de(!1),L.current=!1}return}try{(await K.fire(Ee)).every(Ie=>Ie!==!1)&&ve(X||uo)}catch(Ie){g.fromError("SAVE_BUTTON_CLICK_EVENT_ERROR",r.getEmailDesc(Ee),Ie,!0)}},[N,P,K,g,de,ve]);return(0,l.useMemo)(()=>({requestSave:Te,requestSaveWithEvents:Fe,isLoading:se,isAutosaveLoading:Ae,nextButtonDisabled:J}),[Te,Fe,se,Ae,J])}var Yp="NEXT_BUTTON",Qp="SAVE_BUTTON",_s=({email:e=null,disabled:t})=>{const{__:n}=r.useI18n(),o=r.useAppConfig(),i=r.useContentReader(),s=r.useNotification(),{requestSaveWithEvents:c,isLoading:d,isAutosaveLoading:u,nextButtonDisabled:p}=qp(),f=d||u,[g,y]=(0,l.useState)(null);(0,l.useEffect)(()=>{window?.navigator?.userAgent.includes("Macintosh")&&y(!0)},[]);const m=o.saveButtonEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:n(g?"Save by ⌘S":"Save by Ctrl+S"),placement:"bottom",children:(0,a.jsx)("span",{className:"em-analytics__email-save-tooltip-target",children:(0,a.jsx)(_.ui_kit$Button,{disabled:t||u,type:o.nextButtonEnabled?"default":"primary",block:"false",className:"em-analytics__email-save",loading:f,icon:(0,a.jsx)(r.EmIcons,{icon:"SaveOutlined",component:_.icons$SaveOutlined,size:16,strokeWidth:o.iconStrokeWidth}),onClick:async k=>{const w=k.currentTarget,v={...e,html:i()};try{await c(Qp,v)}catch(x){s.fromError("SAVE_BUTTON_CLICK_EVENT_ERROR",r.getEmailDesc(v),x,!0)}finally{try{w?.blur?.()}catch{}}},children:o.saveButtonText||n("Save")})})},"save-button"),E=o.nextButtonEnabled&&(0,a.jsx)(_.ui_kit$Button,{disabled:t||p,type:"primary",block:"false",className:"em-analytics__email-save",icon:o.primaryCommandButtonIcon,loading:d,onClick:async()=>{const k={...e,html:i()};await c(Yp,k)},children:o.nextButtonText||n("Continue")},"next-button");return(0,a.jsx)(a.Fragment,{children:o.saveButtonEnabled&&o.nextButtonEnabled?(0,a.jsx)(_.ui_kit$Space,{children:[m,E]}):[m,E]})};_s.propTypes={email:$e.default.shape({id:$e.default.string,isNew:$e.default.bool,title:$e.default.string,lock:$e.default.bool,subject:$e.default.string,html:$e.default.string,description:$e.default.string,utm_parameters:$e.default.shape({utm_source:$e.default.string,utm_medium:$e.default.string,utm_campaign:$e.default.string,utm_term:$e.default.string,utm_content:$e.default.string}),project:$e.default.number,is_template:$e.default.bool}),disabled:$e.default.bool};var ys=({element:e,context:t="list"})=>{const{__:n,_x:o}=r.useI18n(),[i]=r.useEditEmailMutation(),[s]=r.useEditBlockMutation(),c=r.useNotification(),d=r.usePushToDataLayer();e.hasOwnProperty("type");const u=(f,g)=>{if(f.error)return c.error(f),!1;c.success(n("The ")+(g.hasOwnProperty("type")?n("block"):o("email","letter"))+" "+n("“")+f.data.title+n("”")+n("was successfully")+" "+(g.lock?g.hasOwnProperty("type")?o("unlocked.","block"):o("unlocked.","email"):g.hasOwnProperty("type")?o("locked.","block"):o("locked.","email")))},p=()=>{const f=!e.lock,g=f?"lock_email":"unlock_email";e.hasOwnProperty("type")?s({blockId:e.id,lock:f}).then(y=>{u(y,e),y.error||d({event:f?"lock":"unlock",action:f?"lock_block":"unlock_block",entity_type:"block",entity_id:e.id,project_id:e.project,context:t})}):i({emailId:e.id,lock:f}).then(y=>{u(y,e),y.error||d({event:f?"lock":"unlock",action:g,entity_type:"email",entity_id:e.id,project_id:e.project,context:t})})};return(0,a.jsx)("div",{className:e.hasOwnProperty("type")?"em-analytics__block-lock":"em-analytics__email-lock",onClick:p,children:e.lock?n("Unlock"):n("Lock")})};ys.propTypes={element:$e.default.shape({lock:$e.default.bool,id:$e.default.string})};var Xp=({open:e,codeSize:t,onMinimize:n,onDownloadAsIs:o,onCancel:i})=>{const{__:s}=r.useI18n(),c=r.formatCodeSize(t);return(0,a.jsx)(_.ui_kit$Modal,{open:e,onCancel:i,footer:null,className:"code-size-warning-modal",width:480,children:(0,a.jsxs)("div",{className:"code-size-warning-modal__content",children:[(0,a.jsx)("h3",{className:"code-size-warning-modal__title",children:s("Code Size Warning")}),(0,a.jsxs)("div",{className:"code-size-warning-modal__message",children:[(0,a.jsxs)("p",{children:[s("The current code size is")," ",(0,a.jsx)("strong",{children:c}),","," ",s("which exceeds the recommended 90 KB limit.")]}),(0,a.jsx)("p",{children:s("Large emails may have delivery issues and load slowly. We recommend minimizing code before exporting.")})]}),(0,a.jsxs)(_.ui_kit$Space,{className:"code-size-warning-modal__actions",size:"medium",children:[(0,a.jsx)(_.ui_kit$Button,{type:"primary",onClick:n,size:"large",children:s("Minimize code")}),(0,a.jsx)(_.ui_kit$Button,{onClick:o,size:"large",children:s("Download as is")})]})]})})};function Jp(e){return e.includes("em-narrow-table")}function Zp(e){if(!e||Jp(e))return!1;const t=e.includes("nl-container"),n=/row-content\s+stack/.test(e)||/stack\s+row-content/.test(e),o=/\brow-\d/.test(e),i=/_block\s+block-\d/.test(e),s=e.includes('role="presentation"');return t&&n&&(o||i)&&s}function em(e){return e?e.includes("em-narrow-table"):!1}function tm(e){return e.includes("em-narrow-table")}function nm(e){return e.includes("i-amphtml")||e.includes("amp-runtime")||e.includes("amp-version")}function rm(e){if(!e||tm(e)||nm(e))return!1;const t=e.includes("es-wrapper"),n=/es-(?:header|content|footer)-body/.test(e);return t||n}function vs(){r.useAppConfig();const e=r.useIntegratorConfigValue("beeFreeConverterEnabled"),t=r.useIntegratorConfigValue("stripoConverterEnabled"),n=r.useIntegratorConfigValue("aiLayoutConverterEnabled"),o=e===!0,i=t===!0,s=n===!0;return{beeFreeConverterEnabled:o,stripoConverterEnabled:i,aiLayoutConverterEnabled:s,anyConverterEnabled:o||i||s}}function bs(e,t){return!e||em(e)?null:Zp(e)?t.beeFreeConverterEnabled?"beefree":null:rm(e)?t.stripoConverterEnabled?"stripo":null:t.aiLayoutConverterEnabled?"ai":null}var om=()=>"useblocks",im={unisender:{id:"unisender",name:"Unisender",icon:"/images/integrations/unisender.svg",description:"Export emails to Unisender",cardDescription:"Mass mailing automation, audience segmentation, and campaign performance analytics.",apps:["emailmaker"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter Unisender API key",helpUrl:"https://app.unisender.com/ru/v5/cp/user/info/api"},{name:"sender_email",type:"email",label:"Sender Email",required:!0,placeholder:"sender@example.com",extra:"This email must be verified in Unisender"},{name:"sender_name",type:"text",label:"Sender Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"list_id",type:"number",label:"Contact List ID",required:!0,placeholder:"e.g., 123456"}]},mailganer:{id:"mailganer",name:"Mailganer",icon:"/images/integrations/mailganer.svg",description:"Export emails to Mailganer",cardDescription:"Contact sync, content personalization, and real-time campaign results tracking.",apps:["emailmaker"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter Mailganer API key",helpUrl:"https://mailganer.com/app/profile/"},{name:"from_email",type:"email",label:"Sender Email",required:!1,placeholder:"sender@example.com",extra:"This email must be verified in Mailganer"},{name:"from_name",type:"text",label:"Sender Name",required:!1,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Mailing Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"theme",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},sendsay:{id:"sendsay",name:"Sendsay",icon:"/images/integrations/sendsay.svg",description:"Export emails to Sendsay",cardDescription:"Mailing automation, audience segmentation, and email personalization.",apps:["emailmaker"],settingsFields:[{name:"login",type:"text",label:"Account Login",required:!0,placeholder:"e.g., myaccount or myaccount/sublogin",extra:"Your Sendsay account login (not email). For sublogin use format: account/sublogin",fullWidth:!0},{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter Sendsay API key",helpUrl:"https://docs.sendsay.ru/sendsay-api/how-to-get-apikey"},{name:"from_email",type:"email",label:"Sender Email",required:!1,placeholder:"sender@example.com",extra:"This email must be verified in Sendsay"},{name:"from_name",type:"text",label:"Sender Name",required:!1,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Draft Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"subject",type:"text",label:"Email Subject",required:!0,placeholder:"e.g., Special offer for you!"}]},klaviyo:{id:"klaviyo",name:"Klaviyo",icon:"/images/integrations/klaviyo.svg",description:"Export emails to Klaviyo",apps:["useblocks"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"e.g., pk_xxxxxxxx",helpUrl:"https://help.klaviyo.com/hc/en-us/articles/7423954176283-How-to-create-a-private-API-key",extra:"Use a custom key with templates:write and campaigns:write (or Full access). Campaigns-only is not enough — export creates a template first."},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"This email must be verified in Klaviyo"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"list_id",type:"text",label:"List ID",required:!0,placeholder:"e.g., ABC123",helpText:"Find your List ID in Klaviyo: Lists & Segments → List → Settings"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},campaign_monitor:{id:"campaign_monitor",name:"Campaign Monitor",icon:"/images/integrations/campaign_monitor.svg",description:"Export emails to Campaign Monitor",apps:["useblocks"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter API Key",fullWidth:!0,helpUrl:"https://help.campaignmonitor.com/s/article/api-keys"},{name:"client_id",type:"text",label:"Client ID",required:!0,placeholder:"e.g., 4a397ccaaa55eb4e6aa1221e1e2d7122",helpText:"Find in Account Settings → API Keys"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"Must be verified in Campaign Monitor"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Campaign Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"list_id",type:"text",label:"List ID",required:!0,placeholder:"e.g., a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",helpText:"Find in Lists → List ID"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},constant_contact:{id:"constant_contact",name:"Constant Contact",icon:"/images/integrations/constant_contact.svg",description:"Export emails to Constant Contact",apps:["useblocks"],settingsFields:[{name:"access_token",type:"password",label:"Access Token",required:!0,placeholder:"OAuth2 Bearer token",fullWidth:!0,helpText:"Get from Constant Contact Developer Portal. Token expires in 24 hours.",helpUrl:"https://developer.constantcontact.com/api_guide/getting_started.html"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"Must be confirmed in Constant Contact"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Campaign Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"list_id",type:"text",label:"Contact List ID",required:!0,placeholder:"e.g., fa32f620-6d82-11e8-8b59-fa163e56c9b0",helpText:"Find via GET /contact_lists API"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},bento:{id:"bento",name:"Bento",icon:"/images/integrations/bento.svg",description:"Export emails to Bento",apps:["useblocks"],settingsFields:[{name:"publishable_key",type:"password",label:"Publishable Key",required:!0,placeholder:"Enter Publishable Key",fullWidth:!0,helpUrl:"https://app.bentonow.com/account/teams"},{name:"secret_key",type:"password",label:"Secret Key",required:!0,placeholder:"Enter Secret Key",fullWidth:!0},{name:"site_uuid",type:"text",label:"Site UUID",required:!0,placeholder:"Your site UUID",helpText:"Find in Bento dashboard"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"Must be an author in your Bento account"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Broadcast Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"},{name:"inclusive_tags",type:"text",label:"Tags (inclusive)",required:!1,placeholder:"e.g., subscribers,newsletter",helpText:"Comma-separated tags to send to. Default: subscribers"}]},dotdigital:{id:"dotdigital",name:"Dotdigital",icon:"/images/integrations/dotdigital.svg",description:"Export emails to Dotdigital",apps:["useblocks"],settingsFields:[{name:"username",type:"text",label:"API Username",required:!0,placeholder:"API user email",helpText:"API user email from Settings → Access → API users",helpUrl:"https://developer.dotdigital.com/docs/setting-up-an-api-user"},{name:"password",type:"password",label:"API Password",required:!0,placeholder:"API user password",fullWidth:!0},{name:"region",type:"text",label:"Region",required:!0,placeholder:"r1, r2, or r3",helpText:"r1=Europe, r2=North America, r3=Asia Pacific"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",fullWidth:!0,extra:"Use an email registered as a Custom from address in Dotdigital (see support.dotdigital.com — “Create a custom from address”). If it does not match, export uses your account default sender."},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Campaign Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},getresponse:{id:"getresponse",name:"GetResponse",icon:"/images/integrations/getresponse.svg",description:"Export emails to GetResponse",apps:["useblocks"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter API Key",fullWidth:!0,helpUrl:"https://app.getresponse.com/api"},{name:"from_field_id",type:"text",label:"From Field ID",required:!0,placeholder:"e.g., V",helpText:"Find via GET /from-fields API"}],exportFields:[{name:"name",type:"text",label:"Newsletter Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"campaign_id",type:"text",label:"Campaign ID",required:!0,placeholder:"e.g., C",helpText:"List/campaign ID from GET /campaigns"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},brevo:{id:"brevo",name:"Brevo",icon:"/images/integrations/brevo.svg",description:"Export emails to Brevo",apps:["useblocks"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter API Key",fullWidth:!0,helpUrl:"https://help.brevo.com/hc/en-us/articles/209467485-Create-and-manage-your-API-keys"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"Must be verified in Brevo"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Campaign Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"list_id",type:"number",label:"List ID",required:!0,placeholder:"e.g., 2",helpText:"Find in Contacts → Lists"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},activecampaign:{id:"activecampaign",name:"ActiveCampaign",icon:"/images/integrations/activecampaign.svg",description:"Export emails as draft campaigns to ActiveCampaign",apps:["useblocks"],settingsFields:[{name:"api_url",type:"text",label:"API URL",required:!0,placeholder:"e.g., https://youraccount.api-us1.com",helpText:"Find in Settings → Developer → API Access",helpUrl:"https://help.activecampaign.com/hc/en-us/articles/207317590-Getting-started-with-the-API"},{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter API Key",fullWidth:!0},{name:"list_id",type:"text",label:"List ID",required:!0,placeholder:"e.g., 1",extra:"Find in Lists → Click your list → The ID is in the URL (e.g., /app/contacts?listid=1)"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"Must be verified in ActiveCampaign"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Campaign Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},salesforce_mc:{id:"salesforce_mc",name:"Salesforce",icon:"/images/integrations/salesforce.svg",description:"Export emails to Salesforce",apps:["useblocks"],settingsFields:[{name:"subdomain",type:"text",label:"Tenant Subdomain",required:!0,placeholder:"e.g., mc563885gzs27c5t9-63k636ttgm",helpText:"Find in Installed Packages → API Integration → REST Base URI",helpUrl:"https://developer.salesforce.com/docs/marketing/marketing-cloud/guide/your-subdomain-tenant-specific-endpoints.html"},{name:"client_id",type:"text",label:"Client ID",required:!0,placeholder:"From Installed Package"},{name:"client_secret",type:"password",label:"Client Secret",required:!0,placeholder:"From Installed Package"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"Must be verified in Marketing Cloud"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Email Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},hubspot:{id:"hubspot",name:"HubSpot Email",icon:"/images/integrations/hubspot.svg",description:"Export emails to HubSpot",apps:["useblocks"],settingsFields:[{name:"api_key",type:"password",label:"Private App Access Token",required:!0,placeholder:"e.g., pat-na1-xxxx",helpUrl:"https://developers.hubspot.com/docs/api/private-apps"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"This email must be verified in HubSpot"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"name",type:"text",label:"Email Name",required:!0,placeholder:"e.g., Newsletter June 2026"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},mailchimp:{id:"mailchimp",name:"Mailchimp",icon:"/images/integrations/mailchimp.svg",description:"Export emails to Mailchimp",apps:["useblocks"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"e.g., xxxxxxxx-us1",helpUrl:"https://mailchimp.com/help/about-api-keys/"},{name:"from_email",type:"email",label:"From Email",required:!0,placeholder:"sender@example.com",extra:"This email must be verified in Mailchimp"},{name:"from_name",type:"text",label:"From Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"list_id",type:"text",label:"Audience ID",required:!0,placeholder:"e.g., a1b2c3d4e5",helpText:"Find your Audience ID in Audience settings → Audience name and defaults"},{name:"subject",type:"text",label:"Email Subject",required:!1,placeholder:"e.g., Special offer for you!"}]},enkod:{id:"enkod",name:"enKod",icon:"/images/integrations/enkod.svg",description:"Export emails to enKod",cardDescription:"Multi-channel campaigns automation (email, SMS, push, WhatsApp, and more).",apps:["emailmaker"],settingsFields:[{name:"api_key",type:"password",label:"API Key",required:!0,placeholder:"Enter enKod API key",helpUrl:"https://help.enkod.io/doku.php/api:start"},{name:"sender_email",type:"email",label:"Sender Email",required:!0,placeholder:"sender@example.com"},{name:"sender_name",type:"text",label:"Sender Name",required:!0,placeholder:"e.g., Your Company"}],exportFields:[{name:"subject",type:"text",label:"Email Subject",required:!0,placeholder:"e.g., Special offer for you!"}]}},sm=(e,t)=>!e.apps||e.apps.length===0?!0:e.apps.includes(t),mo=e=>{const t=im[e];if(t&&sm(t,om()))return t},am=(e,t)=>{const n={placeholder:e.placeholder?t(e.placeholder):void 0,style:{width:"100%"}};switch(e.type){case"number":return(0,a.jsx)(_.ui_kit$InputNumber,{...n,min:1});case"email":return(0,a.jsx)(_.ui_kit$Input,{...n,type:"email"});default:return(0,a.jsx)(_.ui_kit$Input,{...n})}},lm=({integration:e,visible:t,loading:n=!1,onConfirm:o,onCancel:i,__:s})=>{const[c]=_.ui_kit$Form.useForm(),d=e.exportFields||[];(0,l.useEffect)(()=>{t||c.resetFields()},[t,c]);const u=()=>{n||c.validateFields().then(g=>{o(g)})},p=()=>{c.resetFields(),i()};if(d.length===0)return null;const f=d.find(g=>g.helpText);return(0,a.jsxs)(_.ui_kit$Modal,{title:s(`Export to ${e.name}`),open:t,onOk:u,onCancel:p,okText:s("Export"),cancelText:s("Cancel"),confirmLoading:n,cancelButtonProps:{disabled:n},children:[f&&(0,a.jsx)(_.ui_kit$Alert,{title:s(f.label),description:s(f.helpText),type:"info",showIcon:!0,style:{marginBottom:16}}),(0,a.jsx)(_.ui_kit$Form,{form:c,layout:"vertical",children:d.map(g=>(0,a.jsx)(_.ui_kit$Form.Item,{label:s(g.label),name:g.name,rules:[...g.required?[{required:!0,message:s(`Please enter ${g.label.toLowerCase()}`)}]:[],...g.type==="number"?[{type:"number",message:s(`${g.label} must be a number`)}]:[]],children:am(g,s)},g.name))})]})},Xn=r.createApi({reducerPath:"unisenderApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createEmailMessage:e.mutation({query:t=>{const n="https://api.unisender.com/ru/api/createEmailMessage",o=new URLSearchParams;return o.append("format","json"),Object.entries(t).forEach(([i,s])=>{o.append(i,String(s))}),{url:`?proxy_url=${encodeURIComponent(n)}`,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()}}})})}),{useCreateEmailMessageMutation:cm}=Xn,Jn=r.createApi({reducerPath:"mailganerApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://mailganer.com"}),endpoints:e=>({createMailing:e.mutation({query:t=>{const n=new URLSearchParams;return n.append("api_key",t.api_key),n.append("name",t.name),n.append("html-content",t.html_content),t.theme&&n.append("theme",t.theme),t.from_name&&n.append("from_name",t.from_name),t.from_email&&n.append("from_email",t.from_email),t.segment_id&&n.append("segment_id",String(t.segment_id)),t.utm_campaign&&n.append("utm_campaign",t.utm_campaign),t.utm_source&&n.append("utm_source",t.utm_source),t.utm_medium&&n.append("utm_medium",t.utm_medium),{url:"/api/v1/mailing/create/",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}}})})}),{useCreateMailingMutation:dm}=Jn,Zn=r.createApi({reducerPath:"sendsayApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://api.sendsay.ru"}),endpoints:e=>({createDraft:e.mutation({query:t=>{const n={action:"issue.draft.set",apikey:t.api_key,return_fresh_obj:1,obj:{name:t.name,letter:{subject:t.subject,"from.name":t.from_name||void 0,"from.email":t.from_email||void 0,message:{html:t.html_content}}}};return{url:`/general/api/v100/json/${t.login.split("/").map(o=>encodeURIComponent(o)).join("/")}`,method:"POST",headers:{"Content-Type":"application/json"},body:n}}})})}),{useCreateDraftMutation:um}=Zn,er=r.createApi({reducerPath:"altcraftApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({addTemplate:e.mutation({query:t=>{const n=`${t.api_url}/api/v1.1/templates/add`,o={token:t.api_key,name:t.name,channels:[{sid:"email",fields:{html:t.html_content,text:"",subject:t.subject||t.name,from_email:t.from_email||"",from_name:t.from_name||"",replyto_email:"",replyto_name:"",is_not_inline:!0}}],is_draft:t.is_draft??!1};return{url:`?proxy_url=${encodeURIComponent(n)}`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}}})})}),{useAddTemplateMutation:pm}=er,mm=e=>e.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/\s+/g," ").trim(),tr=r.createApi({reducerPath:"enkodApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://api.enkod.ru"}),endpoints:e=>({createMessage:e.mutation({query:t=>{const n=mm(t.html_content)||t.subject,o={message:{subject:t.subject,fromEmail:t.sender_email||"",fromName:t.sender_name||"",html:t.html_content,plainText:n},isDraft:!0};return{url:"/v1/message/onetime/",method:"POST",headers:{"Content-Type":"application/json",Apikey:t.api_key},body:o}}})})}),{useCreateMessageMutation:fm}=tr,gm=e=>{const t=e.split("-");return t.length>1?t[1]:"us1"},hm=e=>`https://${gm(e)}.api.mailchimp.com/3.0`,nr=r.createApi({reducerPath:"mailchimpApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s=hm(t.api_key),c=btoa(`anystring:${t.api_key}`),d={type:"regular",recipients:{list_id:t.list_id},settings:{subject_line:t.subject,from_name:t.from_name,reply_to:t.from_email}},u=await i({url:`?proxy_url=${encodeURIComponent(`${s}/campaigns`)}`,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(d)});if(u.error){const y=u.error,m=y?.data?.detail||y?.error||String(u.error),E=y?.data?.errors;return{error:{status:"CUSTOM_ERROR",error:E?.length?E.map(k=>k.detail||k.title).join("; "):m}}}const p=u.data;if(!p?.id)return{error:{status:"CUSTOM_ERROR",error:u.data?.errors?.map(y=>y.detail||y.title).join("; ")||"Failed to create campaign"}};const f={html:t.html},g=await i({url:`?proxy_url=${encodeURIComponent(`${s}/campaigns/${p.id}/content`)}`,method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(f)});if(g.error){const y=g.error;return{error:{status:"CUSTOM_ERROR",error:y?.data?.detail||y?.error||String(g.error)}}}return{data:{id:p.id,status:p.status,web_id:p.web_id}}}})})}),{useCreateCampaignMutation:_m}=nr,fo="https://a.klaviyo.com/api",ym="2025-04-15",vm=e=>({"Content-Type":"application/json",Accept:"application/json",Authorization:`Klaviyo-API-Key ${e}`,revision:ym}),rr=r.createApi({reducerPath:"klaviyoApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s=vm(t.api_key),c={data:{type:"template",attributes:{name:`Email ${Date.now()}`,editor_type:"CODE",html:t.html}}},d=await i({url:`?proxy_url=${encodeURIComponent(`${fo}/templates`)}`,method:"POST",headers:s,body:JSON.stringify(c)});if(d.error){const w=d.error,v=w?.data?.errors,x=w?.data?.detail;return{error:{status:"CUSTOM_ERROR",error:v?.length?v.map(P=>P.detail||P.status).join("; "):x||w?.error||String(d.error)}}}const u=d.data?.data?.id;if(!u)return{error:{status:"CUSTOM_ERROR",error:"Failed to create template"}};const p={data:{type:"campaign",attributes:{name:`Campaign ${Date.now()}`,audiences:{included:[t.list_id],excluded:[]},send_strategy:{method:"immediate"},"campaign-messages":{data:[{type:"campaign-message",attributes:{definition:{channel:"email",label:t.subject,content:{subject:t.subject,from_email:t.from_email,from_label:t.from_name,reply_to_email:t.from_email}}}}]}}}},f=await i({url:`?proxy_url=${encodeURIComponent(`${fo}/campaigns`)}`,method:"POST",headers:s,body:JSON.stringify(p)});if(f.error){const w=f.error,v=w?.data?.errors,x=w?.data?.detail;return{error:{status:"CUSTOM_ERROR",error:v?.length?v.map(P=>P.detail||P.status).join("; "):x||w?.error||String(f.error)}}}const g=f.data,y=g?.data?.relationships?.["campaign-messages"]?.data?.[0]?.id,m=g?.data?.id;if(!y)return{error:{status:"CUSTOM_ERROR",error:"Failed to get campaign message from campaign"}};const E={data:{type:"campaign-message",id:y,relationships:{template:{data:{type:"template",id:u}}}}},k=await i({url:`?proxy_url=${encodeURIComponent(`${fo}/campaign-message-assign-template`)}`,method:"POST",headers:s,body:JSON.stringify(E)});if(k.error){const w=k.error,v=w?.data?.errors,x=w?.data?.detail;return{error:{status:"CUSTOM_ERROR",error:v?.length?v.map(P=>P.detail||P.status).join("; "):x||w?.error||String(k.error)}}}return{data:{id:m,campaign_message_id:y}}}})})}),{useCreateCampaignMutation:bm}=rr,Em="https://api.hubapi.com",Sm=e=>({"Content-Type":"application/json",Authorization:`Bearer ${e}`}),or=r.createApi({reducerPath:"hubspotApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createEmail:e.mutation({queryFn:async(t,n,o,i)=>{const s=Sm(t.api_key),c={name:t.name,subject:t.subject,from:{fromName:t.from_name,replyTo:t.from_email},content:{templatePath:"@hubspot/email/dnd/plain_text.html",widgets:{"module-0-1-1":{body:{html:t.html,path:"@hubspot/rich_text",schema_version:2},child_css:{},css:{},id:"module-0-1-1",name:"module-0-1-1",order:2,styles:{},type:"module"},"module-1-1-1":{body:{align:"center",path:"@hubspot/email_footer",schema_version:2,unsubscribe_link_type:"both"},child_css:{},css:{},id:"module-1-1-1",name:"module-1-1-1",order:3,styles:{},type:"module"}}}},d=await i({url:`?proxy_url=${encodeURIComponent(`${Em}/marketing/v3/emails/`)}`,method:"POST",headers:s,body:JSON.stringify(c)});if(d.error){const p=d.error,f=p?.data?.errors,g=p?.data?.message;return{error:{status:"CUSTOM_ERROR",error:f?.length?f.map(y=>y.message||y.errorType).join("; "):g||p?.error||String(d.error)}}}const u=d.data;return u?.id?{data:{id:u.id}}:{error:{status:"CUSTOM_ERROR",error:d.data?.errors?.map(p=>p.message||p.errorType).join("; ")||"Failed to create email"}}}})})}),{useCreateEmailMutation:wm}=or,ir=r.createApi({reducerPath:"salesforceMcApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createEmail:e.mutation({queryFn:async(t,n,o,i)=>{const s=`https://${t.subdomain}.auth.marketingcloudapis.com/v2/token`,c=await i({url:`?proxy_url=${encodeURIComponent(s)}`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"client_credentials",client_id:t.client_id,client_secret:t.client_secret})});if(c.error){const m=c.error;return{error:{status:"CUSTOM_ERROR",error:m?.data?.error_description||m?.data?.error||m?.error||String(c.error)}}}const d=c.data,u=d?.access_token,p=d?.rest_instance_url;if(!u||!p)return{error:{status:"CUSTOM_ERROR",error:d?.error_description||d?.error||"Failed to get access token"}};const f={name:t.name,assetType:{id:208,name:"htmlemail"},views:{html:{content:t.html},text:{},subjectline:{content:t.subject},preheader:{}},data:{email:{options:{characterEncoding:"utf-8"}}}},g=await i({url:`?proxy_url=${encodeURIComponent(`${p.replace(/\/$/,"")}/asset/v1/content/assets`)}`,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify(f)});if(g.error){const m=g.error,E=m?.data?.errors,k=m?.data?.message;return{error:{status:"CUSTOM_ERROR",error:E?.length?E.map(w=>w.message||w.documentation).join("; "):k||m?.error||String(g.error)}}}const y=g.data;return y?.id?{data:{id:y.id}}:{error:{status:"CUSTOM_ERROR",error:g.data?.errors?.map(m=>m.message).join("; ")||"Failed to create email"}}}})})}),{useCreateEmailMutation:km}=ir,Cm=e=>e.replace(/\/$/,""),Tm=e=>e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()||" ",sr=r.createApi({reducerPath:"activecampaignApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s=Cm(t.api_url),c=t.api_key,d={"Content-Type":"application/json","Api-Token":c},u=await i({url:`?proxy_url=${encodeURIComponent(`${s}/api/3/addresses`)}`,method:"GET",headers:{"Api-Token":c}});if(u.error)return{error:{status:"CUSTOM_ERROR",error:"Failed to load mailing addresses. Check your API URL and Key."}};const p=u.data?.addresses??[],f=p.find(P=>P.isDefault==="1")??p[0];if(!f?.id)return{error:{status:"CUSTOM_ERROR",error:"NO_MAILING_ADDRESS"}};const g={message:{name:t.name,fromname:t.from_name,fromemail:t.from_email,email:t.from_email,reply2:t.from_email,subject:t.subject,html:t.html,text:Tm(t.html),preheader_text:"",format:"mime"}},y=await i({url:`?proxy_url=${encodeURIComponent(`${s}/api/3/messages`)}`,method:"POST",headers:d,body:JSON.stringify(g)});if(y.error){const P=y.error;return{error:{status:"CUSTOM_ERROR",error:P?.data?.message||P?.error||"Failed to create message."}}}const m=y.data?.message?.id;if(!m)return{error:{status:"CUSTOM_ERROR",error:"Message created but no ID returned."}};const E=`${s}/admin/api.php?api_action=campaign_create&api_output=json`,k=new URLSearchParams;k.append("type","single"),k.append("name",t.name),k.append("sdate","2099-12-31 12:00:00"),k.append("status","0"),k.append("public","1"),k.append("trackreads","1"),k.append("tracklinks","all"),k.append("htmlunsub","1"),k.append("textunsub","1"),k.append("addressid",String(f.id)),k.append(`p[${t.list_id}]`,t.list_id),k.append(`m[${m}]`,"100");const w=await i({url:`?proxy_url=${encodeURIComponent(E)}`,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Api-Token":c},body:k.toString()});if(w.error){const P=w.error;return{error:{status:"CUSTOM_ERROR",error:P?.data?.result_message||P?.error||"Message created, but campaign creation failed."}}}const v=w.data;if(Number(v?.result_code)===0)return{error:{status:"CUSTOM_ERROR",error:v?.result_message||"Campaign creation failed (v1 API)."}};const x=v?.id;return x?{data:{campaignId:String(x)}}:{error:{status:"CUSTOM_ERROR",error:v?.result_message||"Campaign created but no ID returned."}}}})})}),{useCreateCampaignMutation:Im}=sr,Am="https://api.brevo.com/v3",ar=r.createApi({reducerPath:"brevoApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s={name:t.name,subject:t.subject,sender:{name:t.from_name,email:t.from_email},htmlContent:t.html,recipients:{listIds:[t.list_id]}},c=await i({url:`?proxy_url=${encodeURIComponent(`${Am}/emailCampaigns`)}`,method:"POST",headers:{"Content-Type":"application/json","api-key":t.api_key},body:JSON.stringify(s)});if(c.error){const u=c.error;return{error:{status:"CUSTOM_ERROR",error:u?.data?.message||u?.data?.code||u?.error||String(c.error)}}}const d=c.data;return d?.id?{data:{id:d.id}}:{error:{status:"CUSTOM_ERROR",error:c.data?.message||"Failed to create campaign"}}}})})}),{useCreateCampaignMutation:xm}=ar,Pm="https://api.createsend.com/api/v3.3",Rm=e=>`Basic ${btoa(`${e}:x`)}`,lr=r.createApi({reducerPath:"campaignMonitorApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s={Name:t.name,Subject:t.subject,FromName:t.from_name,FromEmail:t.from_email,ReplyTo:t.from_email,HtmlUrl:t.html_url,ListIDs:[t.list_id],InlineCss:!0},c=await i({url:`?proxy_url=${encodeURIComponent(`${Pm}/campaigns/${t.client_id}.json`)}`,method:"POST",headers:{"Content-Type":"application/json",Authorization:Rm(t.api_key)},body:JSON.stringify(s)});if(c.error){const p=c.error;return{error:{status:"CUSTOM_ERROR",error:p?.data?.Message||p?.error||String(c.error)}}}const d=c.data,u=typeof d=="string"?d:d?.id;return!u||typeof u!="string"?{error:{status:"CUSTOM_ERROR",error:d?.Message||"Failed to create campaign"}}:{data:{id:u}}}})})}),{useCreateCampaignMutation:jm}=lr,Es="https://api.cc.email/v3",Om=e=>e.includes("[[trackingImage]]")?e:e.replace(/<body([^>]*)>/i,"<body$1>[[trackingImage]]"),cr=r.createApi({reducerPath:"constantContactApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s=Om(t.html),c={name:t.name,email_campaign_activities:[{format_type:5,from_email:t.from_email,reply_to_email:t.from_email,from_name:t.from_name,subject:t.subject,html_content:s}]},d=await i({url:`?proxy_url=${encodeURIComponent(`${Es}/emails`)}`,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(c)});if(d.error){const m=d.error;return{error:{status:"CUSTOM_ERROR",error:m?.data?.error_message||m?.data?.error_key||m?.error||String(d.error)}}}const u=d.data,p=u?.campaign_activities?.find(m=>m.role==="primary_email")?.campaign_activity_id,f=u?.campaign_id;if(!p||!f)return{error:{status:"CUSTOM_ERROR",error:"Failed to create campaign"}};const g={campaign_activity_id:p,campaign_id:f,role:"primary_email",contact_list_ids:[t.list_id],segment_ids:[],current_status:"DRAFT",format_type:5,from_email:t.from_email,from_name:t.from_name,reply_to_email:t.from_email,subject:t.subject,html_content:s},y=await i({url:`?proxy_url=${encodeURIComponent(`${Es}/emails/activities/${p}`)}`,method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(g)});if(y.error){const m=y.error;return{error:{status:"CUSTOM_ERROR",error:m?.data?.error_message||m?.data?.error_key||m?.error||String(y.error)}}}return{data:{campaign_id:f}}}})})}),{useCreateCampaignMutation:Lm}=cr,Mm="https://api.getresponse.com/v3",Nm=e=>`api-key ${e}`,dr=r.createApi({reducerPath:"getresponseApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createNewsletter:e.mutation({queryFn:async(t,n,o,i)=>{const s=t.html.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim(),c={name:t.name,type:"draft",subject:t.subject,fromField:{fromFieldId:t.from_field_id},replyTo:{fromFieldId:t.from_field_id},campaign:{campaignId:t.campaign_id},content:{html:t.html,plain:s||"Newsletter"},flags:["openrate","clicktrack"],sendSettings:{selectedCampaigns:[t.campaign_id]}},d=await i({url:`?proxy_url=${encodeURIComponent(`${Mm}/newsletters`)}`,method:"POST",headers:{"Content-Type":"application/json","X-Auth-Token":Nm(t.api_key)},body:JSON.stringify(c)});if(d.error){const p=d.error;return{error:{status:"CUSTOM_ERROR",error:p?.data?.message||p?.data?.code||p?.error||String(d.error)}}}const u=d.data;return u?.newsletterId?{data:{newsletterId:u.newsletterId}}:{error:{status:"CUSTOM_ERROR",error:d.data?.message||"Failed to create newsletter"}}}})})}),{useCreateNewsletterMutation:Dm}=dr,Fm=e=>`https://${e||"r1"}-api.dotdigital.com/v2`,Ss=(e,t)=>`Basic ${btoa(`${e}:${t}`)}`,ws=e=>e&&typeof e=="object"&&"data"in e&&e.data!==void 0?e.data:e,ks=e=>e.trim().toLowerCase(),ur=r.createApi({reducerPath:"dotdigitalApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createCampaign:e.mutation({queryFn:async(t,n,o,i)=>{const s=t.html.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim(),c=Fm(t.region),d={"Content-Type":"application/json",Authorization:Ss(t.username,t.password)},u=await i({url:`?proxy_url=${encodeURIComponent(`${c}/custom-from-addresses`)}`,method:"GET",headers:{Authorization:Ss(t.username,t.password)}});let p=[];if(!u.error){const w=ws(u.data);Array.isArray(w)?p=w:w&&typeof w=="object"&&Array.isArray(w.items)&&(p=w.items)}const f=ks(t.from_email),g=p.find(w=>w.email&&ks(w.email)===f),y={name:t.name,subject:t.subject,fromName:t.from_name,htmlContent:t.html,plainTextContent:s||"Newsletter"},m=!g?.id;g?.id!=null&&(y.fromAddress={id:g.id});const E=await i({url:`?proxy_url=${encodeURIComponent(`${c}/campaigns`)}`,method:"POST",headers:d,body:JSON.stringify(y)});if(E.error){const w=E.error;return{error:{status:"CUSTOM_ERROR",error:w?.data?.message||w?.error||String(E.error)}}}const k=ws(E.data);return k?.id?{data:{id:k.id,usedAccountDefaultFromAddress:m}}:{error:{status:"CUSTOM_ERROR",error:E.data?.message||k?.message||"Failed to create campaign"}}}})})}),{useCreateCampaignMutation:Bm}=ur,$m="https://app.bentonow.com/api/v1",Um=(e,t)=>`Basic ${btoa(`${e}:${t}`)}`,pr=r.createApi({reducerPath:"bentoApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({createBroadcast:e.mutation({queryFn:async(t,n,o,i)=>{const s={broadcasts:[{name:t.name,subject:t.subject,content:t.html,type:"raw",from:{email:t.from_email,name:t.from_name},inclusive_tags:t.inclusive_tags||"subscribers",exclusive_tags:"",segment_id:t.segment_id||"",batch_size_per_hour:500,approved:!1}]},c=`${$m}/batch/broadcasts?site_uuid=${encodeURIComponent(t.site_uuid)}`,d=await i({url:`?proxy_url=${encodeURIComponent(c)}`,method:"POST",headers:{"Content-Type":"application/json",Authorization:Um(t.publishable_key,t.secret_key),"User-Agent":"EmailMaker/1.0"},body:JSON.stringify(s)});if(d.error){const u=d.error;return{error:{status:"CUSTOM_ERROR",error:u?.data?.message||u?.error||String(d.error)}}}return{data:{count:d.data?.count??1}}}})})}),{useCreateBroadcastMutation:zm}=pr,Gm=()=>{const{__:e}=r.useI18n(),[t,{isLoading:n}]=cm(),[o,{isLoading:i}]=dm(),[s,{isLoading:c}]=um(),[d,{isLoading:u}]=pm(),[p,{isLoading:f}]=fm(),[g,{isLoading:y}]=_m(),[m,{isLoading:E}]=bm(),[k,{isLoading:w}]=wm(),[v,{isLoading:x}]=km(),[P,{isLoading:K}]=Im(),[J,{isLoading:N}]=xm(),[L,{isLoading:A}]=jm(),[O,{isLoading:z}]=Lm(),[B,{isLoading:U}]=Dm(),[de,{isLoading:me}]=Bm(),[H,{isLoading:Z}]=zm(),De=n||i||c||u||f||y||E||w||x||K||N||A||z||U||me||Z,Ue={unisender:async(T,R,D,I)=>{try{const S=await t({api_key:T.api_key,sender_name:T.sender_name,sender_email:T.sender_email,subject:I,body:D,list_id:R.list_id,generate_text:1,lang:"ru"}).unwrap();return S.result?.message_id?{success:!0,message:e("Email successfully created!"),link:{url:`https://app.unisender.com/ru/v5/spa/email-campaign/editor/${S.result.message_id}?step=send`,text:e("Open in Unisender")}}:S.error?{success:!1,error:S.error+(S.code?` (${S.code})`:"")}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create email")}}},mailganer:async(T,R,D,I)=>{try{const S=await o({api_key:T.api_key,name:R.name,html_content:D,theme:R.theme||I,from_name:T.from_name,from_email:T.from_email}).unwrap();return S.status===1&&S.public_id?{success:!0,message:e("Mailing successfully created!"),link:S.step1_url?{url:S.step1_url,text:e("Open in Mailganer")}:void 0}:S.error?{success:!1,error:S.error}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create mailing")}}},sendsay:async(T,R,D,I)=>{try{const S=await s({login:T.login,api_key:T.api_key,name:R.name,subject:R.subject,html_content:D,from_name:T.from_name,from_email:T.from_email}).unwrap();return S.obj?.id?{success:!0,message:e("Draft successfully created!"),link:{url:`https://app.sendsay.ru/content/drafts/email/${S.obj.id}/settings`,text:e("Open in Sendsay")}}:S.errors&&S.errors.length>0?{success:!1,error:S.errors.map(ae=>ae.explain).join(", ")}:S.error?{success:!1,error:S.explain||S.error}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create draft")}}},altcraft:async(T,R,D,I)=>{try{const S=await d({api_url:T.api_url,api_key:T.api_key,name:R.name,html_content:D,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email}).unwrap();return S.error===0?{success:!0,message:e("Template successfully created!")}:{success:!1,error:S.error_text||e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create template")}}},enkod:async(T,R,D,I)=>{try{const S=await p({api_key:T.api_key,subject:R.subject,html_content:D,sender_name:T.sender_name,sender_email:T.sender_email}).unwrap();if(S.success||S.messageId||S.id){const ae=S.messageId||S.id;return{success:!0,message:e("Draft successfully created!"),link:ae?{url:`https://app.enkod.ru/ensend/messages/detail/${ae}/preview`,text:e("Open in enKod")}:void 0}}else if(S.error||S.message)return{success:!1,error:S.error||S.message||e("Unknown error")};return{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create draft")}}},mailchimp:async(T,R,D,I)=>{try{const S=await g({api_key:T.api_key,list_id:R.list_id,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();if(S.id){const ae=T.api_key?.split("-")[1]||"us1";return{success:!0,message:e("Campaign successfully created!"),link:{url:`https://${ae}.admin.mailchimp.com/campaigns/#r:campaignId=${S.id}`,text:e("Open in Mailchimp")}}}return{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create campaign")}}},klaviyo:async(T,R,D,I)=>{try{const S=await m({api_key:T.api_key,list_id:R.list_id,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();return S.id?{success:!0,message:e("Campaign successfully created!"),link:{url:`https://www.klaviyo.com/campaign/${S.id}/wizard/1`,text:e("Open in Klaviyo")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create campaign")}}},hubspot:async(T,R,D,I)=>{try{const S=await k({api_key:T.api_key,name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();return S.id?{success:!0,message:e("Email successfully created!"),link:{url:`https://app.hubspot.com/email/0/edit/${S.id}`,text:e("Open in HubSpot")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create email")}}},salesforce_mc:async(T,R,D,I)=>{try{const S=await v({subdomain:T.subdomain,client_id:T.client_id,client_secret:T.client_secret,name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();return S.id?{success:!0,message:e("Email successfully created!"),link:{url:`https://app.s7.exacttarget.com/ContentBuilder?app=contentbuilder&id=${S.id}`,text:e("Open in Marketing Cloud")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create email")}}},activecampaign:async(T,R,D,I)=>{try{const S=await P({api_url:T.api_url,api_key:T.api_key,list_id:T.list_id,name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();if(S.campaignId){const ae=(T.api_url||"").replace(/\/$/,"").match(/https?:\/\/([^.]+)\.api-/),we=ae?ae[1]:"",Ye=we?`https://${we}.activehosted.com/app/campaigns/${S.campaignId}`:"https://www.activecampaign.com/app/campaigns";return{success:!0,message:e("Draft campaign created! Open it to review and schedule."),link:{url:Ye,text:e("Open draft campaign")}}}return{success:!1,error:e("Unknown error")}}catch(S){const ae=S.message||S.error||"";if(ae==="NO_MAILING_ADDRESS"){const we=(T.api_url||"").replace(/\/$/,"").match(/https?:\/\/([^.]+)\.api-/),Ye=we?we[1]:"",Qe=Ye?`https://${Ye}.activehosted.com/app/settings/addresses`:"https://www.activecampaign.com/app/settings/addresses";return{success:!1,error:e("No mailing address found. Add one in ActiveCampaign: ")+Qe}}return{success:!1,error:ae||e("Failed to create campaign")}}},brevo:async(T,R,D,I)=>{try{const S=await J({api_key:T.api_key,list_id:Number(R.list_id),name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();return S.id?{success:!0,message:e("Campaign successfully created!"),link:{url:`https://app.brevo.com/marketing-campaign/edit/${S.id}`,text:e("Open in Brevo")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create campaign")}}},campaign_monitor:async(T,R,D,I)=>{try{const S=R.html_url?.trim();if(!S)return{success:!1,error:e("HTML URL is required. Save the email first, or paste a custom URL to your hosted HTML.")};const ae=await L({api_key:T.api_key,client_id:T.client_id,list_id:R.list_id,name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html_url:S.trim()}).unwrap();return ae.id?{success:!0,message:e("Campaign successfully created!"),link:{url:`https://app.createsend.com/campaigns/#/${ae.id}`,text:e("Open in Campaign Monitor")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create campaign")}}},constant_contact:async(T,R,D,I)=>{try{return(await O({access_token:T.access_token,list_id:R.list_id,name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap()).campaign_id?{success:!0,message:e("Campaign successfully created!"),link:{url:"https://app.constantcontact.com/pages/email/campaigns",text:e("Open in Constant Contact")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create campaign")}}},getresponse:async(T,R,D,I)=>{try{const S=await B({api_key:T.api_key,from_field_id:T.from_field_id,campaign_id:R.campaign_id,name:R.name,subject:R.subject||I,html:D}).unwrap();return S.newsletterId?{success:!0,message:e("Newsletter successfully created!"),link:{url:`https://app.getresponse.com/letter/${S.newsletterId}`,text:e("Open in GetResponse")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create newsletter")}}},dotdigital:async(T,R,D,I)=>{try{const S=await de({username:T.username,password:T.password,region:T.region||"r1",name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D}).unwrap();return S.id?{success:!0,message:S.usedAccountDefaultFromAddress?e("Campaign created. Dotdigital used your account default sender because this From email is not registered as a custom from address. Add the address in Dotdigital and export again to use it."):e("Campaign successfully created!"),link:{url:"https://login.dotdigital.com/",text:e("Open in Dotdigital")}}:{success:!1,error:e("Unknown error")}}catch(S){return{success:!1,error:S.message||e("Failed to create campaign")}}},bento:async(T,R,D,I)=>{try{return await H({publishable_key:T.publishable_key,secret_key:T.secret_key,site_uuid:T.site_uuid,name:R.name,subject:R.subject||I,from_name:T.from_name,from_email:T.from_email,html:D,inclusive_tags:R.inclusive_tags}).unwrap(),{success:!0,message:e("Broadcast successfully created!"),link:{url:"https://app.bentonow.com/",text:e("Open in Bento")}}}catch(S){return{success:!1,error:S.message||e("Failed to create broadcast")}}}};return{exportToIntegration:async(T,R,D,I,S)=>{const ae=Ue[T];return ae?ae(R,D,I,S):{success:!1,error:e("Unknown integration")}},isLoading:De}},Rt={INFO:"info",STORAGE:"storage",STYLES:"styles",MEMBERS:"members",INTEGRATIONS:"integrations",PLUGIN:"plugin"},Jv=Rt.INFO,Zv=[Rt.INFO,Rt.STORAGE,Rt.STYLES,Rt.MEMBERS,Rt.INTEGRATIONS,Rt.PLUGIN],eb={mainsettings:Rt.INFO,ftpsettings:Rt.STORAGE,webhooksettings:Rt.INTEGRATIONS},Wm=async(e,t,n)=>{try{const{notification:o,...i}=e,s=await r.fetchBaseQuery({baseUrl:"https://racs.rest/v3"})(i,t,n);if(s.error)throw new Error;return s}catch(o){return(e?.notification).error(o),{error:o}}},mr=r.createApi({reducerPath:"exportPngApi",baseQuery:Wm,endpoints:e=>({makeTemporaryMailForPng:e.mutation({query:({file:t,title:n,notification:o})=>{const i=new Blob([t],{type:"text/html"}),s=new FormData;return s.append("file",i,"base.html"),s.append("contentType","text/html"),{url:"?resource=exportPngApi",method:"POST",body:s,notification:o}}}),deleteTemporaryMail:e.mutation({query:({id:t,notification:n})=>({url:`/${t}?resource=exportPngApi`,method:"DELETE",notification:n})})})}),{useMakeTemporaryMailForPngMutation:Hm,useDeleteTemporaryMailMutation:qm}=mr,fr=r.createApi({reducerPath:"webHookApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({postDataByWebHook:e.mutation({query:({url:t,body:n})=>({url:`?proxy_url=${encodeURIComponent(t)}`,method:"POST",body:n})})})}),{usePostDataByWebHookMutation:Vm}=fr,Km=async(e,t,n)=>{try{const{notification:o,...i}=e,s=await r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"})(i,t,n);if(s.error)throw new Error;return s}catch(o){return(e?.notification).error(o),{error:o}}},gr=r.createApi({reducerPath:"htmlToPdfPlusApi",baseQuery:Km,endpoints:e=>({generateHtmlToPdf:e.mutation({query:({htmlContent:t,notification:n})=>({url:"emails/pdf",method:"POST",body:t,notification:n,responseHandler:o=>o.blob()})})})}),{useGenerateHtmlToPdfMutation:Ym}=gr,hr=r.createApi({reducerPath:"proxyApi",tagTypes:["Proxy"],baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/wp-json/cors-proxy/v1/get"}),endpoints:e=>({getFile:e.query({queryFn({url:t,tryFetch:n=!0,type:o},i){const s=r.clientFromApi(i),c=n?fetch(t):Promise.reject(),d=p=>{switch(o){case"json":return p.json();case"text":return p.text();default:return p.blob()}},u=p=>d(p).then(f=>({data:f}));return c.then(p=>u(p)).catch(()=>s.corsProxy.get_list({format:"blob",extraQuery:{url:encodeURIComponent(t)}}))}})})}),{useGetFileQuery:tb,useLazyGetFileQuery:Qm}=hr,nb="email",rb=100;function Xm(e){return yt.sanitizeFileName(String(e??"").trim()).slice(0,100).trimEnd()||"email"}function Cs(e){const t=Xm(e);return{archive:`${t}.zip`,desktop:`${t}-desktop.png`,mobile:`${t}-mobile.png`}}function Jm(e,t){const n=Cs(e);return{[n.desktop]:t.desktop,[n.mobile]:t.mobile}}var go=()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/a50825ac.js")).then(e=>e.import_exports),void 0,{}.url),Zm=1,ef=2,tf=375,Dt={fontSize:"16px"},nf={position:"absolute",bottom:-4,right:-4,borderRadius:"100%",backgroundColor:r.emCssVar("colorBgContainer")},rf={position:"relative",display:"inline-flex"},qt=({icon:e,locked:t,strokeWidth:n,className:o})=>(0,a.jsxs)("span",{className:o,style:rf,children:[e,t&&(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:12,strokeWidth:n,style:nf})]}),of=({email:e,autoSaveBlockResult:t})=>{const{__:n,_x:o}=r.useI18n(),i=r.useDispatch(),s=r.useEmailAttributesWriter(),[c]=Qm(),[d]=r.useUploadImageMutation(),u=r.useAppNavigate(),{owner:p,admin:f}=Qn(),g=r.useCurrentUser(),y=r.useProjectData(),{modal:m}=_.ui_kit$App.useApp(),E=r.useNotification(),{confirm:k}=m,w=r.useAppStore(),v=()=>on(h.getContainer(w)).keepWrappedOnOutput,x=(M,q,Q,re)=>yt.prepareHTML(M,q,Q,re,v()),P=(M,q,Q,re,ne,W)=>yt.getEML(M,q,Q,re,ne,W,v()),K=(M,q,Q,re,ne)=>yt.htmlToFilesData(M,q,Q,re,ne,v()),J=r.useCookieManager(),N=r.useAppConfig(),L=vs(),{beeFreeConverterEnabled:A,aiLayoutConverterEnabled:O}=L,z=r.useEditorProjectId(),B=r.useEventEmitter(h.events.ON_EMAIL_CLONE_ID),U=r.useEventEmitter(h.events.ON_BROWSER_EXTENSION_DETECTED_ID),[de]=Vm(),me=!0,{data:H}=r.useGetProjectIntegrationsQuery(y?.id??0,{skip:me}),{data:Z}=r.useGetProjectWebhookQuery(y?.id??0,{skip:me}),[De]=r.useLazyGetIntegrationCredentialsQuery(),{exportToIntegration:ve,isLoading:et}=Gm(),be=r.usePushToDataLayer(),[fe,Y]=(0,l.useState)(()=>!Ht(h.getContainer(w)).contentShown()),[pe,ie]=(0,l.useState)(!1),[se,Ae]=(0,l.useState)(null),[Te,Fe]=(0,l.useState)(""),[X,Ee]=(0,l.useState)(!1),[Ie,ge]=(0,l.useState)(0),[Re,Ue]=(0,l.useState)(null),[C,T]=(0,l.useState)(""),[R,D]=(0,l.useState)(!1),I=r.usePlanFeatureGate("export_html"),S=r.usePlanFeatureGate("export_pdf"),ae=r.usePlanFeatureGate("export_png");r.usePlanFeatureGate("export_webhook");const we=r.usePlanFeatureGate("export_platforms"),Ye=r.usePlanFeatureGate("export_amp"),Qe=r.usePlanFeatureGate("template_import"),ze=r.usePlanFeatureGate("code_minify"),Ze=M=>{Ee(!0),ge(r.FEATURE_UPSELL_SLIDE[M])},[pt]=r.emailsApi.useDeleteEmailMutation(),bt=async(M,q)=>{try{const Q=await pt(M.id).unwrap();M.project,E.success(n('The email "')+Q.title+o('" was successfully removed.',"email")),be({event:"delete",action:"delete_email",entity_type:"email",entity_id:M.id,project_id:M.project,context:"editor"})}catch(Q){E.error(Q)}},[ft,lt]=r.useAddEmailMutation(),[G]=Hm(),[V]=qm(),[te]=Ym(),ue=r.useProjectData(),he=r.useInvalidateTerms(),Ge=r.useSelector(r.selectIsHeaderCodeMenuOpen);(0,l.useEffect)(()=>{Ge.switched&&Y(!1)},[Ge]);const qe=()=>{const{title:M}=e;return M===null?n("New email title"):M},st=(M,q,Q=!1)=>{const re=r.getCodeSize(M);Q&&r.isCodeSizeExceeded(re)?(Fe(M),Ae(()=>q),ie(!0)):q(M)},Bt=()=>{if(ie(!1),ze.isLocked){Ze("code_minify");return}if(se&&Te){r.getCodeSize(Te);const M=r.minifyHtml(Te);r.getCodeSize(M),se(M),Ae(null),Fe("")}},Le=()=>{ie(!1),se&&Te&&(se(Te),Ae(null),Fe(""))},Xe=()=>{ie(!1),Ae(null),Fe("")},oe=r.useContentReader(),ee=r.useContentReplacer(),$=r.useEvent(h.events.ON_EMAIL_INIT_ID),le=r.useEventEmitter(h.events.ON_LAYOUT_CONVERT_REQUEST_ID);(0,l.useEffect)(()=>{const M=$(()=>{Y(!1)});return()=>M.dispose()},[$]);const xe=async(M,q=oe())=>{const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q);return q=await x(q,[re.width],e.utm_parameters,async ne=>{ot(ne)}),G({file:q,title:qe(),notification:E}).unwrap().then(ne=>{const W={id:ne._id,...ne};return M(W,()=>V({id:W.id,notification:E}))}).catch(ne=>{E.error({title:ne.data?.code,description:ne.data?.message})})},Se=(M,q=1)=>xe((Q,re)=>({hrefs:M.map(ne=>r.previewHrefForRacs(Q.id,void 0,!1,q,void 0,void 0,ne)),dispose:re})),Me=(M,q,Q=2)=>xe((re,ne)=>({data:M.map(W=>({selector:W,href:r.previewHrefForRacs(re.id,void 0,!1,Q,W)})),dispose:ne}),q),We=async(M,q)=>{const Q=typeof M=="string"?(await c({url:M}))?.data:M;if(!Q)return typeof M=="string"?M:"";let re=r.decodeFileNameFromPath(q);if(typeof M=="string"&&/^https?:\/\//i.test(M)){const He=r.decodeFileNameFromUrl(M);He&&(re=He)}const ne=Q,{ensureFileExtension:W,extractUploadResult:Ce}=await go();re=await W(re,ne.type||"");const _e=new File([ne],re.toLowerCase(),{type:ne.type||""});try{const He=Ce(await d({user_id:g.id,folder:String(ue.id),file:_e}).unwrap());if(He.error)return typeof M=="string"?M:"";if(He.file_url)return He.file_url}catch{}return typeof M=="string"?M:""},Be=async M=>{const q=M.document.querySelectorAll("[em-operation=exportAsPicture]"),Q=new Map;for(let re=0,ne=q.length;re<ne;re++){const W=q[re];W.setAttribute("em-export-id",String(re)),Q.set(`[em-export-id='${re}']`,W)}Q.size&&M.handleRender(async({contentDocument:re,managedNodeController:ne})=>{try{const{data:W,dispose:Ce}=await Me([...Q.keys()],r.getOuterHtml(re),ef);try{const _e=W.map(async({href:He,selector:hn},Dn)=>{const mt=Q.get(hn);if(mt.tagName==="TD"){mt.removeAttribute("style");for(const _t of[...mt.classList])_t.startsWith("em-mob-")&&mt.classList.remove(_t)}ne.commit();const Fr=await We(He,`${Dn}-${mt.tagName.toLowerCase()}.png`),_n=parseInt(getComputedStyle(mt).width);let wt=new Image(_n);wt.setAttribute("border","0"),wt.setAttribute("style",`display: block; width: 100%; max-width: ${_n}px;`),wt.alt="",wt.src=Fr;const yn=mt.querySelector("a");if(yn){const _t=document.createElement("a");_t.setAttribute("target","_blank"),_t.setAttribute("href",yn.getAttribute("href")),_t.appendChild(wt),wt=_t}if(mt.tagName==="TD"){const _t=mt.cloneNode();_t.removeAttribute("em-operation"),_t.appendChild(wt),wt=_t}mt.replaceWith(wt),ne.commit()});await Promise.all(_e)}catch{}finally{Ce()}}catch{}})},ot=M=>{const q=M.document;if(ue?.limits?.preview_limit==="0"&&z&&g?.counters?.emails_counter>2&&!q.querySelector(".em-powered-logo")){const Q=`<a href="${`https://https://racs.rest/v3/v3/link?app=useblocks&project=${z}&email=${e.id}&link=https%3A%2F%2Fuseblocks.io`}" target="_blank"><img src="https://https://racs.rest/v3/v3/pixel/123.png?image=https://cdn.useblocks.io/blocks/powered.png&project=${z}&email=${e.id}" width="150" height="50" border="0" alt="" style="display: inline-block; width: 100%; max-width: 150px;"></a>`;q.querySelector("body > table:last-child > tbody:last-child > tr:last-child, body > div > table:last-child > tbody:last-child > tr:last-child")&&q.querySelector("body > table:last-child > tbody:last-child > tr:last-child, body > div > table:last-child > tbody:last-child > tr:last-child").insertAdjacentHTML("afterend",`<tr em="block" class="em-powered-logo">
856
856
  <td align="center" bgcolor="#FFFFFF">${Q}</td>
857
- </tr>`)}},fn=async()=>{const M=oe();st(M,async q=>{try{const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q),ne=await x(q,[re.width],e.utm_parameters,async He=>{ot(He)}),W=await te({htmlContent:ne,notification:E}).unwrap(),Ce=window.URL.createObjectURL(new Blob([W],{type:"application/pdf"})),_e=document.createElement("a");_e.href=Ce,_e.setAttribute("download",`${qe()}.pdf`),document.body.appendChild(_e),_e.click(),document.body.removeChild(_e),window.URL.revokeObjectURL(Ce)}catch{}})},Ot=M=>{const q=oe();st(q,Q=>{be({event:"click",action:"export_email",export_type:"HTML"});const re=document.querySelector(".email-preview"),ne=getComputedStyle(re);x(Q,[ne.width],e.utm_parameters,async W=>{await Be(W),ot(W),await r.processAmp(W,M)}).then(W=>{const Ce=new Blob([W],{type:"text/html;charset=utf-8"});(0,sn.saveAs)(Ce,`${qe()}.html`)}).catch(W=>{})},!0)},ct=M=>{const q=oe();st(q,Q=>{be({event:"click",action:"export_email",export_type:"TEXT"});const re=document.querySelector(".email-preview"),ne=getComputedStyle(re);x(Q,[ne.width],e.utm_parameters,async W=>{await Be(W),ot(W),await r.processAmp(W,M);const[{htmlToText:Ce},{EmailTextPlainConvertOptions:_e}]=await Promise.all([(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/230f23ec.js")),void 0,{}.url),(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/6541580a.js")),void 0,{}.url)]);W.handleReadHtml(He=>{He.html=Ce(He.contentDocument,_e)})}).then(W=>{const Ce=new Blob([W],{type:"text/plain;charset=utf-8"});(0,sn.saveAs)(Ce,`${qe()}.txt`)}).catch(W=>{})})},Et=()=>{const M=oe();st(M,q=>{be({event:"click",action:"export_email",export_type:"MARKDOWN"});const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q),{utm_parameters:ne}=e;x(q,[re.width],ne,async W=>{ot(W),await r.processAmp(W,"html");const{htmlToMarkdown:Ce}=await(0,Ve.__vitePreload)(async()=>{const{htmlToMarkdown:_e}=await Promise.resolve().then(()=>ye("./static/core/b743a76d.js"));return{htmlToMarkdown:_e}},void 0,{}.url);W.handleReadHtml(_e=>{_e.html=Ce(_e.contentDocument)})}).then(W=>{const Ce=new Blob([W],{type:"text/markdown;charset=utf-8"});(0,sn.saveAs)(Ce,`${qe()}.md`)}).catch(W=>r.reportError(W,{origin:"markdown-export"}))})},Lt=M=>{const q=oe();st(q,Q=>{be({event:"click",action:"export_email",export_type:"Clipboard"});const re=document.querySelector(".email-preview"),ne=getComputedStyle(re);x(Q,[ne.width],e.utm_parameters,async W=>{await Be(W),ot(W),await r.processAmp(W,M)}).then(W=>navigator.clipboard.writeText(W).then(function(){E.success(n("The email has been copied to the clipboard."))})).catch(W=>{})},!0)},jn=async M=>{Re&&mo(Re)},On=()=>{Ue(null),T("")},gn=async()=>{if(!R){D(!0);try{const M=await Se([800,tf],Zm);if(!M)return;const{hrefs:q,dispose:Q}=M;try{const[re,ne]=await Promise.all(q.map(_e=>yt.getImageByUrl(_e).then(He=>yt.imageToBlob(He)))),W=qe(),Ce=await yt.htmlFilesToZip(Jm(W,{desktop:re,mobile:ne}));(0,sn.saveAs)(Ce,Cs(W).archive),be({event:"click",action:"export_email",export_type:"Image"})}finally{Q()}}catch{E.error({title:n("Error"),description:n("Failed to export the email as images. Please try again.")})}finally{D(!1)}}},Ln=M=>{const q=J.get(r.APP_COOKIES.em_token);return fetch(`https://app.useblocks.io/api/wp-json/cors-proxy/v1/get?url=${encodeURIComponent(M)}`,{headers:{authorization:`Bearer ${q}`}}).then(Q=>Q.blob())},Mn=M=>new Promise((q,Q)=>{const re=()=>Ln(M).then(q,Q);fetch(M).then(ne=>q(ne.blob()),re).catch(()=>{})}),gt=(M,q)=>{const Q=oe();st(Q,re=>{be({event:"click",action:"export_email",export_type:"Outlook"});const ne=document.querySelector(".email-preview"),W=getComputedStyle(ne),Ce=async(_e,He)=>{_e.document,await r.processAmp(_e,He),await Be(_e),ot(_e)};P(e.title,re,[W.width,W.height],e.utm_parameters,M?_e=>Ce(_e,"html"):_e=>Ce(_e),q?{embedImagesAsBase64:!0,getImageBlob:Mn}:void 0).then(_e=>{const He=new Blob([_e],{type:"text/html;charset=utf-8"});(0,sn.saveAs)(He,`${qe()}.eml`)}).catch(_e=>{})})},St=M=>{k({centered:!0,mask:{closable:!0},title:n("Embed images in the file?"),content:n('If "Yes", images will be included in the file itself. This is useful for offline viewing or if external images are blocked, but increases file size. If "No", images will be loaded from external links.'),okText:n("Yes"),cancelText:n("No"),onOk:()=>gt(M,!0),onCancel:()=>gt(M,!1)})},ce=async()=>{const M=oe();st(M,async q=>{be({event:"click",action:"export_email",export_type:"ZIP"});const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q),ne=await K(q,[re.width,void 0],e.utm_parameters,Mn,async Ce=>{await Be(Ce),ot(Ce),Tt&&await r.processAmp(Ce,"html")});Tt&&(ne["amp.html"]=await x(q,[re.width],e.utm_parameters,async Ce=>{await Be(Ce),ot(Ce),await r.processAmp(Ce,"amp")}));const W=await yt.htmlFilesToZip(ne);(0,sn.saveAs)(W,`${qe()}.zip`)},!0)},ke=async()=>{if(be({event:"click",action:"duplicate_email",entity_type:"email",entity_id:e.id,project_id:e.project,context:"editor"}),e.isNew)E.warning({title:n("To create a copy, you need to save the email.")});else{if((await B.fire(e)).some(M=>M===!1))return;ft({title:xt.generateCopyTitle(e.title),...e.meta!==void 0?{meta:e.meta}:{},project:Number(ue?.id),description:e.description,html:xt.generateCopyHtml(oe()||"",String(e.title)),parent_email:e.parent_email||6892,common_styles:e.common_styles||"",utm_parameters:{utm_source:e.utm_parameters?.utm_source,utm_medium:e.utm_parameters?.utm_medium,utm_campaign:e.utm_parameters?.utm_campaign,utm_term:e.utm_parameters?.utm_term,utm_content:e.utm_parameters?.utm_content},emailtags:e.emailtags,folder:e.folder}).unwrap().then(M=>{u(`/projects/${ue.id}/emails/${M.id}`),E.success({title:n('The copy of email "')+e.title+n('" was successfully created.')}),be({event:"duplicate",action:"duplicate_email_success",entity_type:"email",entity_id:e.id,cloned_entity_id:M.id,project_id:e.project,context:"editor"}),he("folder")}).catch(M=>{E.error({title:M.data.code,description:M.data.message})})}},Ne=()=>{be({event:"click",action:"click_delete_email_menu_item",entity_type:"email",entity_id:e.id,project_id:e.project,context:"editor"}),e.isNew?E.success(n("The draft of the email has been deleted.")):nt(e,u)},nt=(M,q)=>{be({event:"open",action:"open_delete_email_modal",entity_type:"email",entity_id:M.id,project_id:M.project,context:"editor"}),k({mask:{closable:!0},centered:!0,title:o('Are you sure to delete "',"email")+M.title+n('" email?'),icon:(0,a.jsx)(r.EmIcons,{icon:"DeleteOutlined",component:_.icons$DeleteOutlined,size:22,style:{color:_.ui_kit$iconColors.danger,marginInlineEnd:12,flexShrink:0}}),okText:n("Yes"),cancelText:n("No"),onOk:()=>bt(M,q)})},je=()=>{go().catch(()=>{}),r.uploadFile("application/zip, message/rfc822, text/html",Yt)},Yt=async M=>{const q=M[0];try{i(r.setIsGlobalLoading(!0));const{createDocumentProcessor:Q,createFileProcessor:re,importEmail:ne}=await go(),{html:W,hasBrowserExtensionArtifacts:Ce}=await ne(q,re(c,d,g,ue,N),Q(q))??{html:"",hasBrowserExtensionArtifacts:!1};Ce&&U.fire();const[_e]=yt.getFileNameAndExt(q.name.replaceAll("&nbsp;"," ")),He=_e||xt.getTitleFromHtml(W)||"";ee(W,{undoable:!0}),s({title:He}),i(r.setIsGlobalLoading(!1)),le.fire({html:W})}catch(Q){i(r.setIsGlobalLoading(!1));const re=Q instanceof Error?Q.message:Q;E.error({title:re})}be({event:"upload_file",action:"import_email"})},$t=()=>{const M=oe();M&&(be({event:"click",action:"convert_layout"}),le.fire({html:M}))},dt=[];N.emailDropdownMenuClone&&dt.push({label:n("Clone"),icon:(0,a.jsx)(r.EmIcons,{icon:"CopyOutlined",component:_.icons$CopyOutlined,size:16,strokeWidth:N.iconStrokeWidth}),key:"Clone",className:"em-analytics__email-clone",disabled:lt.isLoading,onClick:ke}),N.emailDropdownMenuImport&&dt.push({label:o("Import","verb"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"CloudUploadOutlined",component:_.icons$CloudUploadOutlined,style:Dt}),locked:Qe.isLocked,strokeWidth:N.iconStrokeWidth}),key:"Import",className:"em-analytics__editor-page__import",onClick:()=>{if(Qe.isLocked){Ze("template_import");return}be({event:"click",action:"import_email"}),je()}});const Nn=oe(),Ut=!e.hasOwnProperty("type")&&bs(Nn,L)!==null;N.emailDropdownMenuConvert&&Ut&&dt.push({label:n("Convert"),icon:(0,a.jsx)(r.EmIcons,{icon:"SwapOutlined",component:_.icons$SwapOutlined,size:16,strokeWidth:N.iconStrokeWidth}),key:"ConvertLayout",className:"em-analytics__email-convert",onClick:$t}),(p||f||g.id?.toString()===e.author?.toString())&&(N.emailDropdownMenuLock&&dt.push({label:(0,a.jsx)(ys,{element:e,context:"editor"},"Lock"),icon:e.lock?(0,a.jsx)(r.EmIcons,{icon:"UnLock",component:_.icons$UnLock,size:16,strokeWidth:N.iconStrokeWidth}):(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:16,strokeWidth:N.iconStrokeWidth}),disabled:e.isNew}),N.emailDropdownMenuRemove&&dt.push({label:n("Remove"),icon:(0,a.jsx)(r.EmIcons,{icon:"DeleteOutlined",component:_.icons$DeleteOutlined,size:16,strokeWidth:N.iconStrokeWidth}),key:"Remove",className:"em-analytics__email-remove",style:{color:"#ff4d4f"},onClick:Ne}));const Tt=e.isAmp,It=[],Dr=()=>[...Tt?[{key:"html_txt",label:`${n("Plain text")} (HTML)`,onClick:()=>ct("html")},{key:"сode_txt",label:`${n("Plain text")} (AMP)`,onClick:()=>ct("amp")}]:[{key:"plain_txt",label:n("Plain text"),onClick:()=>ct()}],{key:"markdown",label:n("Markdown"),onClick:()=>Et()}];N.exportHtmlEnabled&&It.push({key:"html",label:n("Code"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileTextOutlined",component:_.icons$FileTextOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:Tt?{children:[{key:"сode_html",label:n("AMP"),onClick:()=>Ye.isLocked?Ze("export_amp"):Ot("amp")},{key:"html_amp",label:n("HTML"),onClick:()=>Ot("html")}]}:{onClick:()=>Ot()}}),N.exportZipEnabled&&It.push({key:"zip",label:n("ZIP"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileZipOutlined",component:_.icons$FileZipOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:{onClick:()=>ce().catch(M=>{})}}),N.exportClipboardEnabled&&It.push({key:"clipboard",label:n("Clipboard"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"SnippetsOutlined",component:_.icons$SnippetsOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:Tt?{children:[{key:"clipboard_html",label:n("AMP"),onClick:()=>Ye.isLocked?Ze("export_amp"):Lt("amp")},{key:"clipboard_amp",label:n("HTML"),onClick:()=>Lt("html")}]}:{onClick:()=>Lt()}}),N.exportTextEnabled&&It.push({key:"text",label:n("Text"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileOutlined",component:_.icons$FileOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:N.exportMarkdownEnabled?{children:Dr()}:Tt?{children:[{key:"сode_txt",label:n("AMP"),onClick:()=>Ye.isLocked?Ze("export_amp"):ct("amp")},{key:"html_txt",label:n("HTML"),onClick:()=>ct("html")}]}:{onClick:()=>ct()}}),N.exportOutlookEnabled&&It.push({key:"outlook",icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileWordOutlined",component:_.icons$FileWordOutlined,style:Dt}),locked:we.isLocked,strokeWidth:N.iconStrokeWidth}),label:n("Outlook"),onClick:()=>we.isLocked?Ze("export_platforms"):St(!!Tt)}),N.exportPdfEnabled&&It.push({key:"pdf",icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FilePdfOutlined",component:_.icons$FilePdfOutlined,style:Dt}),locked:S.isLocked,strokeWidth:N.iconStrokeWidth}),label:n("PDF"),onClick:()=>S.isLocked?Ze("export_pdf"):fn()}),N.exportPngEnabled&&It.push({key:"img",icon:(0,a.jsx)(qt,{icon:R?(0,a.jsx)(r.EmIcons,{icon:"LoadingOutlined",component:_.icons$LoadingOutlined,spin:!0,style:Dt}):(0,a.jsx)(r.EmIcons,{icon:"FileImageOutlined",component:_.icons$FileImageOutlined,style:Dt}),locked:ae.isLocked,strokeWidth:N.iconStrokeWidth}),label:n("PNG"),disabled:!ae.isLocked&&R,onClick:()=>ae.isLocked?Ze("export_png"):gn()});const ht=e.author;return(0,a.jsxs)(_.ui_kit$Space,{children:[N.emailDropdownMenuEnabled?(0,a.jsx)(_.ui_kit$Dropdown,{arrow:{pointAtCenter:!0},placement:"bottom",menu:{items:dt},children:(0,a.jsx)(_.ui_kit$Button,{type:"default",block:!1,className:"email-page-header__btn email-page-header__btn_extra",onClick:()=>{},children:(0,a.jsx)(r.EmIcons,{icon:"DotsHoriz",component:_.icons$DotsHoriz,size:18,strokeWidth:N.iconStrokeWidth})})},"Actions"):N.emailDropdownMenuImport&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Import","verb"),placement:"bottom",children:N.emailDropdownMenuImportButton?(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__editor-page__import",icon:(0,a.jsx)(r.EmIcons,{icon:"CloudUploadOutlined",component:_.icons$CloudUploadOutlined,size:16,strokeWidth:N.iconStrokeWidth}),onClick:()=>{be({event:"click",action:"import_email"}),je()},children:n("Import")}):(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__editor-page__import",type:"text",icon:(0,a.jsx)(r.EmIcons,{icon:"CloudUploadOutlined",component:_.icons$CloudUploadOutlined,size:22,strokeWidth:N.iconStrokeWidth}),onClick:()=>{be({event:"click",action:"import_email"}),je()}})}),N.emailExportEnabled&&(0,a.jsx)(_.ui_kit$Dropdown,{arrow:{pointAtCenter:!0},placement:"bottom",menu:{items:It},children:(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__email-page__export",type:"default",icon:(0,a.jsx)(r.EmIcons,{icon:"CloudDownloadOutlined",component:_.icons$CloudDownloadOutlined,size:16,strokeWidth:N.iconStrokeWidth}),children:n("Export")},"Export")},"Export"),!e.hasOwnProperty("type")&&(0,a.jsx)(_s,{disabled:fe,email:e},"Save"),!!e.hasOwnProperty("type")&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Au,{disabled:fe,rightCol:void 0,block:e,isEditableRights:p||f||g.id?.toString()===ht?.toString(),autoSaveBlockResult:t})},"Save"),(0,a.jsx)(Xp,{open:pe,codeSize:r.getCodeSize(Te),onMinimize:Bt,onDownloadAsIs:Le,onCancel:Xe}),Re&&mo(Re)&&(0,a.jsx)(lm,{integration:mo(Re),visible:!!Re,loading:et,onConfirm:jn,onCancel:On,__:n}),(0,a.jsx)(r.PlanUpgradePrompt,{open:X,sideOnOk:void 0,onCancel:()=>Ee(!1),initialSlide:Ie})]})},_r=r.createApi({reducerPath:"confirmationMailApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/",responseHandler:e=>e.text()}),endpoints:e=>({getConfirmationMail:e.query({query:({userId:t,email:n})=>({url:`?proxy_url=${encodeURIComponent(`https://webhook.latenode.com/5868/prod/1fbda9c1-3211-4b12-be45-9cd2ea73d73d?user_id=${t}&user_email=${n}`)}`})})})}),{useLazyGetConfirmationMailQuery:sf}=_r,af=()=>{const{__:e}=r.useI18n(),t=r.useNotification(),n=r.useCurrentUser(),[o]=sf(),[i,s]=(0,l.useState)(!1),c=r.usePushToDataLayer();(0,l.useEffect)(()=>{n.hasOwnProperty("email_confirmation")&&s(n.email_confirmation)},[n,i]);const d=()=>{c({event:"click",action:"click_resend_confirmation_email",user_email:n.email,user_id:n.id}),o({userId:n.id,email:n.email}).then(({data:u,error:p})=>{u?t.success(e("Confirmation email has been sent to {confirmedEmail}.").replace("{confirmedEmail}",n.email)):p&&t.error(p)})};return n?.email_confirmation||!n?.privacy_policy_agreement?null:(0,a.jsx)("div",{className:"main__ribbon",children:(0,a.jsxs)("span",{children:[(0,a.jsx)(r.EmIcons,{icon:"EmailConfirmation",component:_.icons$EmailConfirmation,size:16,style:{marginRight:10,verticalAlign:"-0.15em"}}),e("Confirmation email was sent to")," ",(0,a.jsx)("em",{children:n.email}),". ",e("Didn't receive an email?")," ",(0,a.jsxs)(_.ui_kit$Button,{type:"primary",size:"small",className:"main__ribbon-resend",style:{fontSize:16,lineHeight:1,display:"inline-flex",alignItems:"center",gap:8},onClick:d,children:[e("Resend"),(0,a.jsx)(r.EmIcons,{icon:"SendOutlined",component:_.icons$SendOutlined,size:16,style:{flexShrink:0}})]})]})})},lf=({className:e,leftBlock:t,rightBlock:n,isHeaderCodeMenuOpen:o=!1})=>{const{token:i}=(0,_.ui_kit$useToken)(),s=(0,l.useRef)(),c=r.useAppConfig();return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(af,{}),c.headerShow&&(0,a.jsx)("header",{className:(0,rt.default)("header",{[e]:e}),style:{borderColor:i.colorBorder},children:!o&&(0,a.jsx)(r.CSSTransition,{nodeRef:s,in:!o,timeout:300,classNames:"transition",children:(0,a.jsxs)("div",{className:"header__container container",children:[(0,a.jsx)("div",{className:"header__left",style:{flexGrow:1},children:t}),(0,a.jsx)("div",{className:"header__right",children:(0,a.jsx)(_.ui_kit$Space,{size:10,children:n})})]})})})]})},cf=e=>{},Ts=h.createIdentifier$1("canvas.headerFlow");function df(e){const t=(0,l.useCallback)(n=>e?e.subscribe(n):()=>{},[e]);return(0,l.useSyncExternalStore)(t,()=>e?.isReady()===!0)}var Is=({email:e,isCollaborationEditor:t})=>{const[n]=_.ui_kit$Form.useForm(),{__:o}=r.useI18n();let i=r.useDispatch();const s=r.useEmailAttributesWriter(),c=r.useAppNavigate(),d=r.useOpenPlanCatalog(),u=qi("header"),p=r.useCurrentUser(),f=r.useContainer().getInstance(Ts),g=r.useProjectData(),{owner:y,admin:m}=Qn(),{token:E}=(0,_.ui_kit$useToken)(),k=r.useAppConfig(),w=r.usePushToDataLayer(),v=(0,l.useRef)(),x=(0,l.useRef)(),P=(0,l.useRef)(),K=r.useEventEmitter(h.events.ON_PREVIOUSBUTTON_CLICK_ID),J=r.useEventEmitter(h.events.ON_PREHEADER_CHANGED_ID),N=r.useEventEmitter(h.events.ON_SUBJECT_CHANGED_ID),L=r.useSelector(r.selectCodeModeDirection),A=e.hasOwnProperty("type")?r.BLOCK:r.EMAIL,O=r.useSelector(r.selectElementSettings$1),z=r.useSelector(r.selectElementSettings),B=A==="email"?O:z,U=r.useSelector(r.selectIsCodeMode),[de,me]=(0,l.useState)(!1),[H,Z]=(0,l.useState)(!1),[De,ve]=(0,l.useState)(!1),et=(0,l.useCallback)(()=>ve(!1),[]),be=(0,l.useCallback)(()=>{ve(!1),d()},[d]),fe=Gi("email_generate"),Y=fe.exceeded?r.getLimitUpgradePresetDefinition(fe.exceeded.presetId):null;(0,l.useEffect)(()=>{const I=!!B?.type&&(B?.type===r.ELEMENT_TYPES.TEXT||B?.type===r.ELEMENT_TYPES.LINK||B.type===r.ELEMENT_TYPES.BUTTON)&&U&&L!=="bottom";me(I),i(r.setHeaderCodeMenuOpen(I))},[B,L,U]);const pe=(0,l.useCallback)(()=>{w({event:"click",action:"click_back_button",entity_type:A==="block"?"block":"email",entity_id:e?.id,project_id:e?.project||g?.id,context:"editor"}),K.fire(e)},[c,K,e,g?.id,w,A]),{document:ie}=r.useCurrentSession(),se=df(ie);r.usePrevious(([I])=>{se&&I!==e.subject&&N.fire(e.subject)},[e.subject,se]);const Ae=(0,l.useCallback)(I=>{const S=I.target.value;N.fire(S)},[N]),Te=(0,l.useCallback)(I=>{const S=I.target.value;J.fire(S)},[J]);r.usePrevious(([I])=>{se&&I!==e.preheader&&J.fire(e.preheader)},[e.preheader,se]);const Fe=(0,l.useCallback)((I,S="?")=>{I.subject?.length,I.preheader?.length,n.setFieldValue("subject",I.subject??""),n.setFieldValue("preheader",I.preheader??"")},[n]),X=(0,l.useRef)(void 0);(0,l.useEffect)(()=>{const I=e?.renderGuid??(e?.id!=null?String(e.id):void 0);!se||!I||X.current===I||(X.current=I,Fe(e,"identity"))},[se,e,Fe]);const Ee=(0,l.useCallback)(I=>{const S=I.target.value.trim();s({subject:S})},[s]),Ie=r.useEvent(h.events.BEFORE_SAVE_EMAIL),ge=(0,l.useCallback)(async I=>{const S=x.current?.input;if(document.activeElement===S){const we=S.value.trim();we!==I.subject&&(I.subject=we,s({subject:we}))}const ae=P.current?.input;if(document.activeElement===ae){const we=ae.value.trim();we!==I.preheader&&(I.preheader=we,s({preheader:we}))}await f?.whenDelivered()},[f,s]);(0,l.useEffect)(()=>{const I=Ie(ge);return()=>I.dispose()},[Ie,ge]);const Re=(0,l.useCallback)(I=>{const S=I.target.value.trim();s({preheader:S})},[s]),Ue=r.useEvent(h.events.ON_HEADER_APPLIED_ID);(0,l.useEffect)(()=>{const I=Ue(({field:S,value:ae})=>{n.setFieldValue(S,ae)});return()=>I.dispose()},[Ue,n]),cf(e.title===null?o("New email title"):e.title);const C=(0,l.useCallback)(()=>{i(r.setActiveSettingsTab(r.AICHAT)),setTimeout(()=>{const I=document.querySelector('li.ai-response-change-context[role="theme-and-preheader-generator"]');I&&I.click()},100)},[i]),T=(0,l.useCallback)(()=>{fe.isLocked?fe.state.state==="locked_by_limit"&&fe.exceeded?ve(!0):Z(!0):C()},[fe,C]),R=(0,a.jsx)(a.Fragment,{children:(0,a.jsxs)(_.ui_kit$Space,{ref:v,size:10,children:[k.headerArrowBackVisible&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Back"),placement:"left",children:(0,a.jsx)(_.ui_kit$Button,{type:"text",icon:(0,a.jsx)(r.EmIcons,{icon:"ArrowLeftOutlined",component:_.icons$ArrowLeftOutlined,size:22,strokeWidth:k.iconStrokeWidth}),onClick:pe,shape:"circle"})}),(0,a.jsx)("div",{children:(k.headerTitleVisible||k.headerPreheaderVisible)&&(0,a.jsxs)(_.ui_kit$Form,{form:n,layout:"vertical",name:"subject_preheader_form",autoComplete:"off",initialValues:{subject:"",preheader:""},children:[k.headerTitleVisible&&(0,a.jsx)("div",{style:{marginTop:se?-3:0},children:(0,a.jsxs)(_.ui_kit$Space,{style:{width:"100%"},align:"baseline",size:12,children:[(0,a.jsx)("div",{className:"subject_preheader_form__title",children:o("Subject")}),se?(0,a.jsxs)("div",{className:"ant-page-header-heading",children:[(0,a.jsx)(_.ui_kit$Form.Item,{name:"subject",noStyle:!0,children:(0,a.jsx)(_.ui_kit$Input,{className:"ant-page-header-heading-title",ref:x,placeholder:o("Enter subject line here"),variant:"borderless",autoComplete:"off","data-lpignore":"true","data-1p-ignore":"","data-bwignore":"true","data-form-type":"other",onChange:Ae,onPressEnter:Ee,onBlur:I=>{Ee(I),document.querySelector(".ant-page-header-heading-title").closest(".ant-page-header-heading").classList.remove("focus")},onFocus:()=>{document.querySelector(".ant-page-header-heading-title").closest(".ant-page-header-heading").classList.add("focus")},disabled:k.lockPreheaderAndTitle})}),k.aiAssistentEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Generate with AI"),children:(0,a.jsx)(r.EmIcons,{icon:"AI",component:_.icons$AI,size:12,strokeWidth:k.iconStrokeWidth,onClick:T})})]}):(0,a.jsx)(_.ui_kit$Skeleton.Input,{active:!0,size:16,style:{width:"40%",marginTop:3}})]})}),k.headerPreheaderVisible&&(0,a.jsx)("div",{children:(0,a.jsxs)(_.ui_kit$Space,{style:{width:"100%"},align:"baseline",size:12,children:[(0,a.jsx)("div",{className:"subject_preheader_form__title",children:o("Preheader")}),se?(0,a.jsxs)("div",{className:"ant-page-header-heading ant-page-header-heading_preheader",children:[(0,a.jsx)(_.ui_kit$Form.Item,{name:"preheader",noStyle:!0,children:(0,a.jsx)(_.ui_kit$Input,{className:"ant-page-header-heading-preheader",ref:P,placeholder:o("Enter preheader here"),variant:"borderless",autoComplete:"off","data-lpignore":"true","data-1p-ignore":"","data-bwignore":"true","data-form-type":"other",onChange:Te,onPressEnter:Re,onBlur:I=>{Re(I),document.querySelector(".ant-page-header-heading-preheader").closest(".ant-page-header-heading").classList.remove("focus")},onFocus:()=>{document.querySelector(".ant-page-header-heading-preheader").closest(".ant-page-header-heading").classList.add("focus")},disabled:k.lockPreheaderAndTitle})}),k.aiAssistentEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Generate with AI"),children:(0,a.jsx)(r.EmIcons,{icon:"AI",component:_.icons$AI,size:12,strokeWidth:k.iconStrokeWidth,onClick:T})})]}):(0,a.jsx)(_.ui_kit$Skeleton.Input,{active:!0,size:16,style:{width:"80%",marginTop:2}})]})})]})})]})}),D=(0,a.jsxs)(a.Fragment,{children:[k.emailIdShow&&!!e.id&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"email-page-header__email-id",children:"ID"+e.id}),(0,a.jsx)(_.ui_kit$Divider,{orientation:"vertical"})]}),(0,a.jsx)(ps,{emailElement:e,isCollaborationEditor:t}),k.commandButtonsEnabled&&(0,a.jsxs)(a.Fragment,{children:[e.lock?(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:18,strokeWidth:k.iconStrokeWidth,className:(0,rt.default)("lock-icon",{"lock-icon__disabled":!(y||m||p.id?.toString()===e.author?.toString())}),style:{color:E.colorPrimary,verticalAlign:"sub"}},"Lock"):null,(0,a.jsx)(of,{email:e,isHeaderCodeMenuOpen:de},"Buttons")]})]});return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(lf,{className:"email-pane__header",leftBlock:u?R:null,rightBlock:u?D:null,isHeaderCodeMenuOpen:de}),(0,a.jsx)(r.PlanUpgradePrompt,{open:H,onCancel:()=>Z(!1),initialSlide:9}),Y&&fe.exceeded?(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(oo,{open:De,onClose:et,title:o(Y.titleKey),subtitle:o(Y.subtitleKey),usageResource:Y.usageResource,previousDisplay:r.presetLimitDisplay(fe.exceeded.previousLimit),nextDisplay:r.presetLimitDisplay(fe.exceeded.nextLimit),onChangePlan:be})}):null]})};Is.propTypes={};function uf(e){const t=r.parseEmBlockVersion(e);if(!t)return e;const n=o=>String(o).padStart(2,"0");return`${n(t.getDate())}.${n(t.getMonth()+1)}.${t.getFullYear()} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}var pf=({open:e,blocks:t,projectId:n,onClose:o})=>{const{__:i,_n:s}=r.useI18n(),c=r.useSendPostMessage(),d=r.useNotification(),[u,p]=(0,l.useState)({});(0,l.useEffect)(()=>{e&&p(Object.fromEntries(t.map(m=>[m.emBlockId,!0])))},[e,t]);const f=(0,l.useMemo)(()=>Object.values(u).filter(Boolean).length,[u]),g=(m,E)=>{p(k=>({...k,[m]:E}))},y=()=>{const m=t.filter(E=>u[E.emBlockId]);m.length&&(m.forEach(E=>{c({operation:r.EVENT_TYPES.SANDBOX_GLOBAL_BLOCK_REPLACE,settings:{emBlockId:E.emBlockId,blockHTML:E.savedHtml,type:"project",...n?{project:String(n)}:{}}})}),d.success({message:i("Updated")+" "+m.length+" "+s("block","blocks",m.length),placement:"bottomRight"}),o())};return(0,a.jsxs)(_.ui_kit$Modal,{title:(0,a.jsx)("div",{className:"ant-modal-title",children:i("Update global blocks")}),open:e,onOk:y,onCancel:o,footer:(0,a.jsxs)("div",{className:"update-global-blocks-modal__footer",children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",onClick:o,children:i("Cancel")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",disabled:f===0,onClick:y,children:i("Update")})]}),children:[(0,a.jsx)("div",{className:"update-global-blocks-modal__hint",children:i("These global blocks have a newer saved version. Select the ones to update in the template.")}),(0,a.jsx)("div",{className:"update-global-blocks-modal__list",children:t.map(m=>(0,a.jsxs)("div",{className:"update-global-blocks-modal__row",children:[(0,a.jsx)(_.ui_kit$Switch,{checked:!!u[m.emBlockId],onChange:E=>g(m.emBlockId,E)}),(0,a.jsxs)("span",{className:"update-global-blocks-modal__title",title:m.title,children:[m.title,(0,a.jsxs)("span",{className:"update-global-blocks-modal__version",children:[i("Version of")," ",uf(m.savedVersion)]})]}),m.instances>1&&(0,a.jsxs)("span",{className:"update-global-blocks-modal__count",children:[m.instances," ",s("instance","instances",m.instances)]})]},m.emBlockId))})]})};function mf(e){const t=new Map;return e?.trim()&&new DOMParser().parseFromString(e,"text/html").querySelectorAll('[em="block"][em-block-id]').forEach(n=>{const o=n.getAttribute("em-block-id");if(!o)return;const i=n.getAttribute("em-block-version")??void 0,s=t.get(o);s?(s.versions.add(i),s.count+=1):t.set(o,{versions:new Set([i]),count:1})}),t}function ff(e,t){const n=mf(e);if(!n.size||!t?.length)return[];const o=[];for(const i of t){if(!i.global_block||!i.id||!i.html)continue;const s=String(i.id),c=n.get(s);if(!c)continue;const d=r.readRootEmBlockAttrs(i.html).emBlockVersion;d&&[...c.versions].some(u=>u!==d)&&o.push({emBlockId:s,title:i.title?.trim()||s,savedHtml:i.html,savedVersion:d,templateVersion:[...c.versions][0],instances:c.count})}return o}var As="em-block-id";function gf({projectId:e,document:t}){const n=r.useEvent(h.events.ON_EMAIL_INIT_ID),o=r.useHeadless(),[i,s]=(0,l.useState)([]),[c,d]=(0,l.useState)(!1),[u,p]=(0,l.useState)(null),f=(0,l.useCallback)(E=>t?.subscribe(E)??(()=>{}),[t]),g=(0,l.useSyncExternalStore)(f,()=>!!t?.getContent().includes(As)),{data:y}=r.blocksApi.endpoints.getBlocks.useQuery(r.projectBlocksArgs(e),{skip:!e||!g}),m=(0,l.useRef)(!1);return(0,l.useEffect)(()=>{g&&m.current&&t&&(m.current=!1,p(t.getContent()))},[g,t]),(0,l.useEffect)(()=>{const E=new h.Disposable;return E.addDisposable(n(k=>{if(k?.reset)return;const w=k?.html??"",v=w.includes(As);m.current=!v,p(v?w:null)})),()=>E.dispose()},[n]),(0,l.useEffect)(()=>{if(u==null||!y)return;if(o){p(null);return}const E=ff(u,y);E.length&&(s(E),d(!0)),p(null)},[u,y,o]),{outdatedBlocks:i,isOpen:c,close:(0,l.useCallback)(()=>d(!1),[])}}var hf=({open:e,html:t,emBlockId:n,onSaveAsNew:o,onClose:i})=>{const{__:s}=r.useI18n(),c=r.useSendPostMessage(),d=r.useNotification(),[u]=r.useEditBlockMutation(),[p,f]=(0,l.useState)(!1),g=async()=>{if(!n||!t){i();return}f(!0);const y=new Date,m=r.formatEmBlockVersion(y),E=r.injectEmBlockIdIntoBlockHtml(t,String(n),y),k=await u({blockId:String(n),html:E});if(f(!1),"error"in k&&k.error){d.error({message:s("Failed to update the global block."),placement:"bottomRight"});return}c({operation:r.EVENT_TYPES.SANDBOX_EBLOCK_SET_EM_BLOCK_ID,settings:{emBlockId:String(n),emBlockVersion:m}}),d.success({message:s("The global block was updated."),placement:"bottomRight"}),i()};return(0,a.jsx)(_.ui_kit$Modal,{title:(0,a.jsx)("div",{className:"ant-modal-title",children:s("Saving changes in the block")}),open:e,onCancel:i,footer:(0,a.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",disabled:p,onClick:o,children:s("Create new block")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",loading:p,onClick:g,children:s("Update current block")})]}),children:(0,a.jsx)("div",{children:s("This is a global block. You can create a new one to apply changes only in this email, or update the current one — then the changes will be applied everywhere this block is used.")})})},_f=(function(){var e=window.__useblocks__;if(e&&e.assetUrl)return e.assetUrl("converter-intro.bf4ee74d750b35ae2c10.png");if(e&&e.publicPath)try{return new URL("static/media/converter-intro.bf4ee74d750b35ae2c10.png",e.publicPath).href}catch{}try{return new URL("/static/media/converter-intro.bf4ee74d750b35ae2c10.png",typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?window.location.href:"").href}catch{return"/static/media/converter-intro.bf4ee74d750b35ae2c10.png"}})(),yf={closable:!1},vf=_f,bf=({open:e,onConfirm:t,onCancel:n,neverSuggestAgain:o,onNeverSuggestAgainChange:i})=>{const{__:s}=r.useI18n();return(0,a.jsx)(_.ui_kit$Modal,{className:"convert-layout-modal",title:(0,a.jsx)("div",{className:"convert-layout-modal__title",children:s("Template conversion")}),open:e,onOk:t,onCancel:n,mask:yf,width:480,footer:(0,a.jsxs)("div",{className:"convert-layout-modal__footer",style:{display:"flex",flexDirection:"column",gap:16},children:[(0,a.jsx)(_.ui_kit$Switch,{size:"small",checked:o,onChange:i,label:s("Don't suggest again"),labelSize:"small"}),(0,a.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",onClick:n,children:s("Cancel")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",onClick:t,children:s("Convert")})]})]}),children:(0,a.jsxs)("div",{className:"convert-layout-modal__content",style:{display:"flex",flexDirection:"column",alignItems:"center",gap:24,padding:"0 8px",overflow:"hidden"},children:[(0,a.jsx)("div",{className:"convert-layout-modal__text convert-layout-modal__intro-text",style:{textAlign:"center"},children:s("This layout was not created in our editor. Convert it to unlock full editing capabilities: easily change texts, replace images, and manage blocks.")}),(0,a.jsx)("img",{src:vf,alt:"Converter Intro",className:"convert-layout-modal__image",style:{display:"block",width:"100%",maxWidth:"100%",height:"auto",borderRadius:8}})]})})},Ef={closable:!1},Sf=({open:e,message:t,onRetry:n,onCancel:o})=>{const{__:i}=r.useI18n();return(0,a.jsx)(_.ui_kit$Modal,{title:(0,a.jsx)("div",{className:"ant-modal-title",children:i("Conversion failed")}),open:e,onOk:n,onCancel:o,mask:Ef,footer:(0,a.jsxs)("div",{className:"convert-layout-modal__footer",children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",onClick:o,children:i("Cancel")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",onClick:n,children:i("Try again")})]}),children:(0,a.jsxs)("div",{className:"convert-layout-modal__text",children:[i("Something went wrong during layout conversion. You can try running the conversion again."),t?(0,a.jsx)("div",{className:"convert-layout-modal__error-details",children:t}):null]})})},wf=({open:e,progress:t})=>{const{__:n}=r.useI18n();return e?(0,a.jsx)("div",{className:"conversion-overlay",children:(0,a.jsxs)("div",{className:"conversion-overlay__content",children:[(0,a.jsx)(_.ui_kit$Spin,{size:"large"}),(0,a.jsx)("div",{className:"conversion-overlay__title",children:n("Converting layout…")}),(0,a.jsx)("div",{className:"conversion-overlay__hint",children:n("This may take several minutes. Please keep this tab open.")}),(0,a.jsx)(_.ui_kit$Progress,{className:"conversion-overlay__progress",percent:Math.round(t),status:"active",strokeColor:r.emCssVar("colorPrimary")})]})}):null},yr=r.createApi({reducerPath:"layoutConverterApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({createConvertJob:e.mutation({query:({html:t})=>({url:"/ai/converter/jobs",method:"POST",body:{html:t}})}),getConvertJobStatus:e.query({query:t=>({url:`/ai/converter/jobs/${t}`,method:"GET"})})})}),{useCreateConvertJobMutation:kf,useLazyGetConvertJobStatusQuery:Cf}=yr;function Tf(){try{return window.localStorage.getItem(r.LOCAL_STORAGE_ITEMS.em_layout_convert_never_suggest)==="true"}catch{return!1}}function If(e){try{e?window.localStorage.setItem(r.LOCAL_STORAGE_ITEMS.em_layout_convert_never_suggest,"true"):window.localStorage.removeItem(r.LOCAL_STORAGE_ITEMS.em_layout_convert_never_suggest)}catch{}}function xs(e){return e==="beefree"?(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/79749848.js")).then(t=>t.convertBeeFreeToEmailMaker),void 0,{}.url):(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/e0d71533.js")).then(t=>t.convertStripoToEmailMaker),void 0,{}.url)}var Af=5,Ps=95,xf=35e3,Pf=1e3,Rf=e=>new Promise(t=>setTimeout(t,e));function jf(e,t){if(e&&typeof e=="object"){const n=e,o=n.data;if(o&&typeof o=="object"){const i=o.error;if(typeof i=="object"&&i?.message)return i.message;if(typeof i=="string"&&i)return i;if(o.message)return o.message}if(typeof o=="string"&&o)return o;if(n.error)return n.error;if(n.message)return n.message}return t}function Of(){const{__:e}=r.useI18n(),t=r.useContentReplacer(),n=r.useNotification(),o=vs(),{aiLayoutConverterEnabled:i,anyConverterEnabled:s}=o,c=r.useHeadless(),d=r.useEvent(h.events.ON_EMAIL_INIT_ID),u=r.useEvent(h.events.ON_LAYOUT_CONVERT_REQUEST_ID),[p]=kf(),[f]=Cf(),[g,y]=(0,l.useState)(Tf),m=(0,l.useRef)(g),E=(0,l.useCallback)(ie=>{m.current=ie,y(ie),If(ie)},[]),[k,w]=(0,l.useState)(!1),[v,x]=(0,l.useState)(!1),[P,K]=(0,l.useState)(0),[J,N]=(0,l.useState)(!1),[L,A]=(0,l.useState)(""),O=(0,l.useRef)(""),z=(0,l.useRef)(null),B=(0,l.useRef)(null),U=(0,l.useRef)(!1),de=(0,l.useRef)({cancelled:!0}),me=(0,l.useRef)(null);(0,l.useEffect)(()=>{U.current=v},[v]);const H=(0,l.useCallback)(()=>{me.current!==null&&(clearInterval(me.current),me.current=null)},[]),Z=(0,l.useCallback)(()=>{H();const ie=Date.now();me.current=setInterval(()=>{const se=Date.now()-ie,Ae=Ps*(1-Math.exp(-se/xf));K(Te=>Math.max(Te,Math.min(Ps,Ae)))},Pf)},[H]),De=(0,l.useCallback)(ie=>{ie&&(t(ie,{undoable:!0}),B.current=ie)},[t]),ve=(0,l.useCallback)(async ie=>{const se={cancelled:!1};de.current=se,N(!1);const Ae=z.current;if(Ae==="beefree"||Ae==="stripo"){try{const Te=await xs(Ae),Fe=se.cancelled?"":Te(ie);if(Fe&&!se.cancelled){De(Fe),n.success({message:r.isUseBlocksBuild()?e("Layout converted to Blocks format"):e("Layout converted to EmailMaker format"),placement:"bottomRight"});return}}catch{}if(!i){se.cancelled||(A(e("Layout conversion failed")),N(!0));return}}if(i){x(!0),K(0),Z();try{const Te=await p({html:ie}).unwrap();if(se.cancelled)return;let Fe=Te.retry_after>0?Te.retry_after:Af;for(;!se.cancelled;){if(await Rf(Fe*1e3),se.cancelled)return;const X=await f(Te.job_id).unwrap();if(se.cancelled)return;if(X.retry_after&&X.retry_after>0&&(Fe=X.retry_after),X.status==="completed"){H(),K(100),De(X.html??""),n.success({message:r.isUseBlocksBuild()?e("Layout converted to Blocks format"):e("Layout converted to EmailMaker format"),placement:"bottomRight"}),setTimeout(()=>{se.cancelled||(x(!1),K(0))},400);return}if(X.status==="failed")throw new Error(X.error?.message||e("Layout conversion failed"))}}catch(Te){if(se.cancelled)return;H(),x(!1),K(0),A(jf(Te,e("Layout conversion failed"))),N(!0)}}},[e,i,De,p,n,f,Z,H]),et=(0,l.useCallback)(()=>{w(!1);const ie=O.current;ie&&ve(ie)},[ve]),be=(0,l.useCallback)(()=>{w(!1),B.current=O.current},[]),fe=(0,l.useCallback)(()=>{N(!1);const ie=O.current;ie&&ve(ie)},[ve]),Y=(0,l.useCallback)(()=>{N(!1),B.current=O.current},[]),pe=(0,l.useCallback)((ie,se=!1)=>{const Ae=bs(ie,o);if(s&&!c&&Ae&&!U.current){if(se)B.current=null;else{if(m.current)return;if(B.current===ie)return}O.current=ie,z.current=Ae,Ae!=="ai"&&xs(Ae).catch(()=>{}),w(!0)}},[s,o,c]);return(0,l.useEffect)(()=>{if(!s)return;const ie=new h.Disposable;return ie.addDisposable(d(se=>{se?.reset||pe(se?.html??"")})),()=>ie.dispose()},[s,d,pe]),(0,l.useEffect)(()=>{if(!s)return;const ie=new h.Disposable;return ie.addDisposable(u(se=>{pe(se?.html??"",!0)})),()=>ie.dispose()},[s,u,pe]),(0,l.useEffect)(()=>()=>{de.current.cancelled=!0,H()},[H]),{isPromptOpen:k,isConverting:v,progress:P,isErrorOpen:J,errorMessage:L,confirmConversion:et,cancelPrompt:be,retryConversion:fe,closeError:Y,neverSuggestAgain:g,setNeverSuggestAgain:E}}var Lf=6e4,Rs=new Map;function Mf(e){const t=e?String(e):"",n=Rs.get(t);if(n&&(Rs.delete(t),!(Date.now()-n.at>Lf)))return n.promise}var ho={data:void 0,isSuccess:!1,isError:!1,error:void 0,isLoading:!1};function Nf(e){const t=r.useStore(),n=(0,l.useRef)(t);n.current=t;const[o,i]=(0,l.useState)(ho),s=e?String(e):void 0;return(0,l.useEffect)(()=>{if(!s){i(ho);return}let c=!1;return i({...ho,isLoading:!0}),(Mf(s)??r.resolveEmailPort(h.getContainer(n.current)).readEmail(s)).then(d=>{c||i({data:d??void 0,isSuccess:!0,isError:!1,error:void 0,isLoading:!1})}).catch(d=>{c||i({data:void 0,isSuccess:!1,isError:!0,error:d,isLoading:!1})}),()=>{c=!0}},[s]),o}var ob=2;function Df(){const e=r.useProjectData()?.id,t=!0,{data:n,isError:o,isFetching:i,refetch:s}=r.useGetProjectPlanQuery(e,{skip:t}),[c,d]=(0,l.useState)(0),u=(0,l.useRef)(!1),p=!!o,f=c>=2,g=(0,l.useCallback)(()=>{u.current=!1,d(0),s()},[s]);(0,l.useEffect)(()=>{},[p,i,s,c,t]),(0,l.useEffect)(()=>{},[p,e,f,t]);const y="ready";return(0,l.useMemo)(()=>({status:y,retry:g}),[y,g])}var ib=300,Ff=h.createIdentifier$1("prewarm.queue");function Bf(e){const t=[];let n=!1,o=!1,i;const s=()=>{i&&(i.unwatch(),e.clearTimer(i.timer),i=void 0)},c=()=>{const p=t.shift();if(!p)return;o=!0;const f=()=>{o=!1,u()};p.start().then(f,f)},d=()=>{s(),e.idle(()=>{if(!(o||t.length===0)){if(e.activity.inFlight()>0){u();return}c()}})};function u(){if(!n||o||i||t.length===0)return;const p=()=>e.setTimer(d,300),f={timer:e.activity.inFlight()===0?p():void 0,unwatch:e.activity.watch(()=>{e.clearTimer(f.timer),f.timer=e.activity.inFlight()===0?p():void 0})};i=f}return e.whenVisible(()=>{n=!0,u()}),{add(p){t.some(f=>f.name===p.name)||(t.push(p),u())},remove(p){const f=t.findIndex(g=>g.name===p);f>=0&&t.splice(f,1),t.length===0&&s()}}}function $f(e){return e.getOrCreateInstance(Ff,()=>Bf({activity:h.getNetworkActivity(e),whenVisible:t=>Ht(e).whenVisible(t),idle:Xt,setTimer:(t,n)=>window.setTimeout(t,n),clearTimer:t=>window.clearTimeout(t)}))}function Uf({projectId:e,project:t,emailProjectId:n,parentEmailId:o}){const i=r.useContainer(),s=r.useAppDispatch(),d=!!r.useCookieManager().get(r.APP_COOKIES.em_token);(0,l.useEffect)(()=>{const u=$f(i),p=[],f=[],g=(m,E)=>{f.push(m),u.add({name:m,start:()=>{const k=E();return p.push(k),Promise.resolve(k)}})},y=r.parentEmailSource(o);return y&&g("blocks.parentEmail",()=>s(r.blocksApi.endpoints.getParentEmailBlocks.initiate(r.parentEmailBlocksArgs(y)))),g("blocks.template",()=>s(r.blocksApi.endpoints.getTemplateBlocks.initiate(r.templateBlocksArgs()))),e&&g("blocks.list",()=>s(r.blocksApi.endpoints.getBlocks.initiate(r.projectBlocksArgs(e)))),g("blocks.schema",()=>s(r.blocksApi.endpoints.getBlocksSchema.initiate(void 0))),t?.id&&g("blocks.tags",()=>s(r.taxonomiesApi.endpoints.getTerms.initiate({project:t,kind:r.BLOCK_TAGS}))),()=>{f.forEach(m=>u.remove(m)),p.forEach(m=>m.unsubscribe())}},[i,s,e,t,n,o,d])}var _o="AUTOSAVE_RECOVERY";function zf(e,t,n=!1,o){const i=t?.get().serverId??void 0,{__:s}=r.useI18n(),c=r.useNotification(),d=r.useAppConfig(),u=r.useSelector(r.selectMonacoFocusing),p=r.useContainer(),f=p?.getInstance(Ts),g=(0,l.useRef)(0),y=r.useSelector(r.selectIsPanelHistoryCollapsed),m=r.useSelector(r.selectActiveSettingsTab),E=r.useDispatch(),k=(0,l.useSyncExternalStore)((0,l.useCallback)(L=>o?.subscribe(L)??(()=>{}),[o]),()=>o?.recoveryFacts()),w=d?.revisionService===!0,v=k?.isRecovering===!0,x=k?.applied,P=(0,l.useCallback)(()=>{E(r.markAppearanceNeedsUpdate());const L=e?.renderGuid,A=e?.preheader,O=e?.subject;L&&(A||O)&&f?.reassert({...A?{preheader:A}:{},...O?{subject:O}:{}})},[E,f,e?.preheader,e?.subject,e?.title,e?.common_styles,e?.renderGuid,t,o]);(0,l.useEffect)(()=>()=>{clearTimeout(g.current),o?.endForcedHeaders()},[i,o]),(0,l.useEffect)(()=>{w&&v&&c.info({key:_o,title:s("Loading latest changes..."),duration:0})},[w,v,c,s]);const K=(0,l.useRef)({emailId:void 0,seq:0});(0,l.useEffect)(()=>{if(!x||k?.emailId!==i||(K.current.emailId!==i&&(K.current={emailId:i,seq:0}),x.seq<=K.current.seq))return;K.current={emailId:i,seq:x.seq},P();const{phase:L}=x;!w||L==="normal"||(L==="found"?c.success({key:_o,title:s("Changes loaded"),duration:3}):L==="timeout"?c.warning({key:_o,title:s("Locally saved version applied"),description:s("Syncing with the server in the background..."),duration:5}):L==="bg"&&c.info({key:"AUTOSAVE_BG_SYNCED",title:s("Email synced with the server"),duration:3}))},[w,x,k?.emailId,i,P,c,s]),(0,l.useEffect)(()=>{if(!n)return;const L=A=>{A.preventDefault()};return window.addEventListener("beforeunload",L),()=>window.removeEventListener("beforeunload",L)},[n]);const J=!y||u||m==="Discuss",N=p?r.provideAutosaveUiFacts(p):void 0;(0,l.useEffect)(()=>{N?.set({...N.get()??{isUserBusy:!1,saveContext:{}},isUserBusy:J})},[N,J])}var Gf=class extends Error{label;timeoutMs;constructor(e,t){super(`[${e}] timed out after ${t}ms`),this.name="OperationTimeoutError",this.label=e,this.timeoutMs=t}};function Wf(e,t,n){return t<=0?e:new Promise((o,i)=>{let s=!1,c;const d=u=>{s||(s=!0,c!==void 0&&(clearTimeout(c),c=void 0),u())};c=setTimeout(()=>{d(()=>i(new Gf(n,t)))},t),e.then(u=>{d(()=>o(u))},u=>{d(()=>i(u))})})}var Hf=2,vr=Symbol("sandbox:frame-replaced");function an(e,t,n,o,i,s,c){const d=`sandbox:${t}`,u=s?.getSandboxTimeoutMs(t)??r.DEFAULT_SANDBOX_OP_TIMEOUT_MS[t],p=()=>{let E=Wf(e.sendAsync(n,o),u,d);return E=h.raceWithAbortSignal(E,s?.signal),r.logShowPipelineWait(d,E,i)};if(t==="INIT_START"&&Ki(e)){const E=s?.getSandboxReadyTimeoutMs()??2e4,k=e,w=v=>{const x=Yi(k,E,s?.signal);return r.logShowPipelineWait("sandbox:INIT_START:ready-wait",x,i).then(()=>{if(!c||v<=0)return p();const P=c.getGeneration();let K;const J=new Promise((L,A)=>{K=c.onChange(()=>{c.getGeneration()!==P&&A(vr)})}),N=p();return N.catch(()=>{}),Promise.race([N,J]).finally(()=>K?.()).catch(L=>{if(L!==vr)throw L;return{...i},w(v-1)})})};return w(Hf)}if(!c)return p();const f=c.getGeneration();let g;const y=new Promise((E,k)=>{g=c.onChange(()=>{c.getGeneration()!==f&&k(vr)})}),m=p();return m.catch(()=>{}),Promise.race([m,y]).finally(()=>g?.()).catch(E=>{throw E===vr&&{...i},E})}function js(e,t,n,o){return{html:e,guid:t,...Object.keys(n).length>0?{templateDirectivesPolicy:n}:{},...o!==void 0?{rev:o}:{}}}var Os="self-init:";function qf(e){return e.startsWith(Os)}function Ls(e,t){const n=e.getActiveShowRequest();return qf(t)?n===null:n?.showId===t&&e.hasPendingShow(t)}function Vf(e){const t=()=>e.initPipeline(),n=e.messageService,o=()=>e.waitScope?.()??t();let i="";const s=()=>e.readDocument()?r.readDocumentContent(e.readDocument()):i,c=()=>on(e.container).editorPolicy,d=()=>e.readEmail(),u=()=>{const p=d();return{...p,id:e.isTemplate()||p.isNew?void 0:p.id,html:s()}};return{readContent:s,publicEmail:u,sendInitStart:()=>an(n,"INIT_START",r.EVENT_TYPES.SANDBOX_INIT_START,{guid:d().renderGuid},void 0,o()),sendInited:()=>an(n,"INITED",r.EVENT_TYPES.SANDBOX_INITED,{guid:d().renderGuid},void 0,o()),async sendContent(){const p=d(),{html:f,hasBrowserExtensionArtifacts:g}=r.prepareEmailHtmlForEditor(p?.html||"");g&&e.events.browserExtensionDetected(),r.loadDocumentContent(e.readDocument(),f),i=f,await an(n,"SET_ENTITY",r.EVENT_TYPES.SANDBOX_SET_ENTITY,js(s(),p.renderGuid,c(),e.readDocument()?.get().version),{guid:p.renderGuid,emailId:p.id??null},o())},refreshContent:()=>an(n,"SET_ENTITY",r.EVENT_TYPES.SANDBOX_SET_ENTITY,js(s(),d().renderGuid,c(),e.readDocument()?.get().version),void 0,o()),sendPreheader:async()=>{const p=d();if(p.preheader!==void 0)return an(n,"PREHEADER",r.EVENT_TYPES.SANDBOX_PREHEADER_UPDATE,{value:p.preheader,guid:p.renderGuid,force:!0},void 0,o())},sendSubject:async()=>{const p=d();if(p.subject!==void 0)return an(n,"SUBJECT",r.EVENT_TYPES.SANDBOX_SUBJECT_UPDATE,{value:p.subject,guid:p.renderGuid,force:!0},void 0,o())},revealFilled:()=>e.revealFilled?.()??Promise.resolve(),showFilled:p=>e.showFilled?.(p),readTarget:()=>e.readTarget?.(),fireWillInit:()=>e.events.willInit(u()),fireInit(p,f){if(!Ls(t(),p)){t().getActiveShowRequest()?.showId;return}const g=d();g.id,g.renderGuid,t().completeShow(p),r.writeEmailAttributes(e.readDocument(),{is_inited:!0},{source:"system"});const y=u();return f&&(y.reset=!0),e.events.inited(y)},fireEmailChanged(){e.events.emailChanged(u())},fireContentChanged(){e.events.contentChanged(s())}}}function Kf(e){const t=()=>e.initPipeline();let n=!1,o,i,s,c=0,d;const u=Vf({...e,waitScope:()=>({getSandboxTimeoutMs:w=>t().getSandboxTimeoutMs(w),getSandboxReadyTimeoutMs:()=>t().getSandboxReadyTimeoutMs(),signal:d?.signal??t().signal})});let p;const f=(w,v)=>{if(p===w)return;p=w;const x=c;setTimeout(()=>{c!==x||t().signal.aborted||E(w,v).catch(()=>{})},0)},g=()=>{d?.abort(),d=void 0};let y;const m=()=>{const w=t().signal;w!==y&&(y?.removeEventListener("abort",g),y=w,w.addEventListener("abort",g))};async function E(w,v){const x=++c;g(),d=new AbortController,m();const P=()=>c!==x,K=u.readTarget(),J=t().generation,N=()=>J===t().generation&&!t().signal.aborted,L=v?"init:reset-":"init:";if(!v){const z=u.publicEmail();z?.id,z?.renderGuid,z?.preheader}let A=!1,O=!1;try{n=!0,await u.sendInitStart(),u.fireWillInit(),await(v?u.refreshContent():u.sendContent()),A=!0,v||u.publicEmail()?.id;try{await u.sendPreheader()}catch(z){r.logShowPipelineError(`${L}preheader-failed`,{showId:w,error:String(z)})}try{await u.sendSubject()}catch(z){r.logShowPipelineError(`${L}subject-failed`,{showId:w,error:String(z)})}if(P()||u.showFilled(K),await u.sendInited(),O=!0,i===w){const z=e.readSandboxGeneration?.()??s;z!==void 0&&(o=z)}await u.revealFilled()}catch(z){throw P()||r.logShowPipelineError(`${L}failed`,{showId:w,contentApplied:A,sandboxInitedAcked:O,superseded:!1,...e.describeSurface?.(),error:String(z)}),!P()&&Ls(t(),w)&&t().failShow(w,z),z}finally{k(w,v,L,{superseded:P(),sessionGeneration:J,contentApplied:A,sandboxInitedAcked:O,commit:N()})}}function k(w,v,x,P){const{superseded:K,contentApplied:J,sandboxInitedAcked:N}=P;if(K){`${x}`;return}N&&P.commit?u.fireInit(w,v||void 0):N?r.logShowPipelineError(`${x}aborted (stale session or signal)`,{showId:w,sessionGeneration:P.sessionGeneration,currentGeneration:t().generation,aborted:t().signal.aborted}):J?r.logShowPipelineError(`${x}aborted (sandbox INITED ack missing)`,{showId:w}):r.logShowPipelineError(`${x}aborted (content not applied)`,{showId:w}),n=!1,d=void 0,!N&&i===w&&(i=void 0,o===s&&(o=void 0)),!N&&J&&f(w,v)}return{channel:u,isEventsLocked:()=>n,filledGeneration:()=>o,markFilled:w=>{o=w},lastCorrelation:()=>i,markCorrelation:w=>{i=w},bumpRunSeq:()=>{c+=1},noteSandboxGeneration:w=>{s=w},fill:w=>E(w,!1),refill:w=>E(w,!0),stop:()=>{c+=1,g(),n=!1,y?.removeEventListener("abort",g),y=void 0}}}function Yf(e,t,n){if(!e?.renderGuid||!e.showId||e.showId!==t.showId)return!1;if(t.isNew)return e.id==null;const o=t.emailId??t.navId;return o!=null&&String(e.id??"")!==String(o)?!1:Ms(e,n)}function Ms(e,t){return t?e?.id==null?!1:String(e.id)===String(t):!0}function Qf(e){const{pipeline:t,readEmail:n,readDocument:o,readRouteEmailId:i,readSandboxGeneration:s}=e,c=f=>{const g=n(),y=i();if(!Yf(g,f,y)){f.showId,f.navId,f.emailId,g?.id,g?.showId,g?.renderGuid;return}f.showId,g?.id,g?.renderGuid,t.markFilled(s()),t.markCorrelation(f.showId),t.fill(f.showId).catch(()=>{})};return{showRequested:f=>{c(f)},showRequestIdentityChanged:()=>{const f=e.initPipeline().getActiveShowRequest();f&&c(f)},selfInitChanged:()=>{if(e.initPipeline().getActiveShowRequest())return;const f=s();if(t.filledGeneration()===f)return;const g=n(),y=i();if(!g?.renderGuid||!Ms(g,y))return;const m=`${Os}${g.renderGuid}`;t.markFilled(f),t.markCorrelation(m);const E=o()?.isReady()===!0;g.id,g.renderGuid,(E?k=>t.refill(k):k=>t.fill(k))(m).catch(()=>{t.lastCorrelation()===m&&t.markFilled(void 0)})},saasChanged:()=>{const f=n();f?.renderGuid,f?.showToken,f?.id}}}var Ns=h.createIdentifier$1("canvas.sandboxFill"),Xf=class extends Error{showId;constructor(e,t){super(`[useblocks] show() timed out after ${t}ms waiting for editor init (showId=${e}). Check earlier console errors: wrong host-plugin publicPath (chunks return HTML), mount element removed without destroy(), or sandbox init never completed. Search for [show-pipeline] and [AMD] messages.`),this.name="ShowPipelineTimeoutError",this.showId=e}},Jf=class{_activeRequest=null;_pending=new Map;_listeners=new Set;getActiveShowRequest(){return this._activeRequest}onShowRequested(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}requestShow(e,t,n){return this._rejectPending(h.createAbortError("Superseded by newer show()")),n.aborted?Promise.reject(h.createAbortError(n.reason)):(this._activeRequest=e,new Promise((o,i)=>{const s=setTimeout(()=>{this._settle(e.showId,()=>{i(new Xf(e.showId,t))})},t);s.unref?.();const c=()=>{this._settle(e.showId,()=>{i(h.createAbortError(n.reason))})};n.addEventListener("abort",c,{once:!0});const d=()=>{clearTimeout(s),n.removeEventListener("abort",c)};this._pending.set(e.showId,{request:e,resolve:o,reject:i,timeoutId:s,dispose:d});for(const u of this._listeners)u(e)}))}completeShow(e){this._settle(e,t=>{t.resolve()})}hasPendingShow(e){return this._pending.has(e)}failShow(e,t){this._settle(e,n=>{n.reject(t)})}rejectAll(e){this._rejectPending(e),this._activeRequest=null}_settle(e,t){const n=this._pending.get(e);n&&(n.dispose(),this._pending.delete(e),this._activeRequest?.showId===e&&(this._activeRequest=null),t(n))}_rejectPending(e){for(const[,t]of this._pending)t.dispose(),t.reject(e);this._pending.clear()}};function Zf(e,t){return{contentReady:t.contentReady??e?.contentReady,sandboxReady:t.sandboxReady??e?.sandboxReady,sandbox:t.sandbox?{...e?.sandbox,...t.sandbox}:e?.sandbox}}function eg(e){if(!e||!(e.contentReady!==void 0||e.sandboxReady!==void 0||e.sandbox!==void 0))return;const t=r.resolveContentReadyTimeoutMs(e),n=r.resolveSandboxReadyTimeoutMs(e),o=r.resolveSequentialSandboxOpBudgetMs(e.sandbox);t<n+o}var tg=class{_controller=new AbortController;_externalSignalDisposable=new h.Disposable;_sessionChangeListeners=new Set;_showRegistry=new Jf;_timeouts;_generation=0;_sessionStarted=!1;get signal(){return this._controller.signal}get generation(){return this._generation}get contentReadyTimeoutMs(){return r.resolveContentReadyTimeoutMs(this._timeouts)}getSandboxTimeoutMs(e){return r.resolveSandboxOpTimeoutMs(e,this._timeouts?.sandbox)}getSandboxReadyTimeoutMs(){return r.resolveSandboxReadyTimeoutMs(this._timeouts)}bumpGeneration(){this._generation+=1}getActiveShowRequest(){return this._showRegistry.getActiveShowRequest()}onShowRequested(e){return this._showRegistry.onShowRequested(e)}requestShow(e){return this._showRegistry.requestShow(e,this.contentReadyTimeoutMs,this._controller.signal)}completeShow(e){this._showRegistry.completeShow(e)}hasPendingShow(e){return this._showRegistry.hasPendingShow(e)}failShow(e,t){this._showRegistry.failShow(e,t)}rejectAllPendingShows(e){this._showRegistry.rejectAll(e)}onSessionReplaced(e){return this._sessionChangeListeners.add(e),()=>{this._sessionChangeListeners.delete(e)}}configure(e){e.timeouts!==void 0&&(this._timeouts=Zf(this._timeouts,e.timeouts),eg(this._timeouts));const t=e.replaceSession===!0||!this._sessionStarted||e.timeouts!==void 0||e.signal!==void 0;this._sessionStarted=!0,t&&(this._replaceSessionController(),this.bumpGeneration()),(e.signal!==void 0||t)&&this._linkExternalSignal(e.signal)}abort(e){const t=e??h.createAbortError("Editor instance destroyed");this._showRegistry.rejectAll(t),this._controller.signal.aborted||(this._controller.abort(t),this.bumpGeneration()),this._externalSignalDisposable.dispose(),this._externalSignalDisposable=new h.Disposable}_replaceSessionController(){this._externalSignalDisposable.dispose(),this._externalSignalDisposable=new h.Disposable,this._showRegistry.rejectAll(h.createAbortError("Init session replaced")),this._controller.signal.aborted||this._controller.abort(h.createAbortError("Init session replaced")),this._controller=new AbortController,this._emitSessionReplaced()}_emitSessionReplaced(){for(const e of this._sessionChangeListeners)e()}_linkExternalSignal(e){if(!e)return;if(e.aborted){this._controller.signal.aborted||(this._controller.abort(e.reason??h.createAbortError()),this.bumpGeneration());return}const t=()=>{this._controller.signal.aborted||(this._controller.abort(e.reason??h.createAbortError()),this.bumpGeneration())};e.addEventListener("abort",t),this._externalSignalDisposable.addDispose(()=>{e.removeEventListener("abort",t)})}},ng=(()=>{const e=new tg;return e.configure({}),e})();function yo(){const e=r.useStore();return(0,l.useMemo)(()=>h.getContainer(e)?.getInstance(h.INIT_PIPELINE_ID)??ng,[e])}function rg(e){const t=yo(),n=(0,l.useRef)(e);n.current=e,(0,l.useEffect)(()=>{let o;const i=()=>{o?.();const c=t.signal;if(c.aborted){n.current();return}const d=()=>n.current();c.addEventListener("abort",d),o=()=>c.removeEventListener("abort",d)};i();const s=t.onSessionReplaced(i);return()=>{s(),o?.()}},[t])}function og(e){const t=yo(),n=(0,l.useRef)(e);n.current=e,(0,l.useEffect)(()=>t.onShowRequested(o=>n.current(o)),[t])}var ig=(e,t,n,o,i)=>{const s=r.useStore(),c=r.useMessageService(),d=yo(),u=(0,l.useRef)(d);u.current=d;const p=r.useEventEmitter(h.events.WILL_EMAIL_INIT_ID),f=r.useEventEmitter(h.events.ON_EMAIL_INIT_ID),g=r.useEventEmitter(h.events.ON_CONTENT_CHANGED_ID),y=r.useEventEmitter(h.events.ON_EMAIL_CHANGED_ID),m=r.useEventEmitter(h.events.ON_BROWSER_EXTENSION_DETECTED_ID),E=e?.id!==void 0,k=e?.showToken??0,w=k,v=(0,l.useRef)(w);v.current=w;const x=(0,l.useRef)(void 0);x.current=e;const[P,K]=(0,l.useState)(()=>r.getSandboxGeneration(c)),J=(0,l.useRef)(P);J.current=P,(0,l.useEffect)(()=>(K(r.getSandboxGeneration(c)),r.onSandboxGenerationChange(c,()=>{K(r.getSandboxGeneration(c))})),[c]);const N=(0,l.useRef)(o);N.current=o;const L=(0,l.useRef)(t);L.current=t;const A=i?.standalone?void 0:h.getContainer(s)?.getInstance(Ns),O=!A,z=(0,l.useRef)(A?.pipeline);z.current||(z.current=Kf({container:h.getContainer(s),messageService:c,initPipeline:()=>u.current,readDocument:()=>N.current,readEmail:()=>x.current,isTemplate:()=>!!L.current,readSandboxGeneration:()=>J.current,events:{willInit:H=>p.fire(H),inited:H=>f.fire(H),contentChanged:H=>g.fire(H),emailChanged:H=>y.fire(H),browserExtensionDetected:()=>m.fire()}}));const B=z.current,U=(0,l.useRef)(n);U.current=n;const de=(0,l.useRef)(void 0);O&&!de.current&&(de.current=Qf({pipeline:B,initPipeline:()=>u.current,readEmail:()=>x.current,readDocument:()=>N.current,readRouteEmailId:()=>U.current,readSandboxGeneration:()=>J.current}));const me=de.current;B.noteSandboxGeneration(J.current),(0,l.useEffect)(()=>{if(O)return()=>z.current?.stop()},[O]),(0,l.useEffect)(()=>{A?.setRoute({emailId:n,isTemplate:t})},[A,n,t]),(0,l.useEffect)(()=>{const H=x.current;if(O&&!B.isEventsLocked()&&e?.renderGuid===H?.renderGuid&&H?.is_inited&&H){const Z=B.channel.readContent();y.fire({...H,id:t||H.isNew?void 0:H.id,html:Z})}},[B,e?.renderGuid,e?.preheader,e?.common_styles,e?.meta,e?.subject,e?.utm_parameters?.utm_campaign||"",e?.utm_parameters?.utm_content||"",e?.utm_parameters?.utm_medium||"",e?.utm_parameters?.utm_source||"",e?.utm_parameters?.utm_term||"",y,t,O]),(0,l.useEffect)(()=>{if(O){const H=r.subscribeToContent(o,()=>{const Z=x.current;if(!B.isEventsLocked()&&e?.renderGuid===Z?.renderGuid&&Z){const De=B.channel.readContent();g.fire(De),y.fire({...Z,id:t||Z.isNew?void 0:Z.id,html:De})}});return()=>H.dispose()}},[o,B,g,y,e,t,O]),rg(()=>{O&&B.stop()}),og(H=>{me?.showRequested(H)}),(0,l.useEffect)(()=>{me?.showRequestIdentityChanged()},[me,d,e?.renderGuid,e?.showId,e?.id,n]),(0,l.useEffect)(()=>{me?.selfInitChanged()},[me,d,e?.renderGuid,e?.showId,e?.id,n,o,P]),r.usePrevious(()=>{me?.saasChanged()},[e?.renderGuid,k,E,me]),Zr(async()=>{if(!O)return;const H=d.getActiveShowRequest()?.showId;H&&(B.markFilled(J.current),await B.refill(H))},{async:!0})};function sg(e){const t=r.useEvent(h.events.ON_EMAIL_INIT_ID);(0,l.useEffect)(()=>{if(!e)return;const n=t(()=>e.clear());return()=>n.dispose()},[e,t])}function ag(e,t){const n=r.useEventEmitter(h.events.ON_DOCUMENT_SESSION_CHANGE);(0,l.useEffect)(()=>{n.fire({document:e,history:t})},[e,t,n])}function lg({templateEmailId:e,templateEmail:t,newEmail:n}){return e?t:n}function cg({routeEmailId:e,draft:t}){const n=r.useStore();(0,l.useRef)(0),(0,l.useEffect)(()=>{},[n,e,t])}function dg(e,t){return t}function ug(e){return!1}function pg({documents:e,push:t,projectId:n,subscription:o}){(0,l.useEffect)(()=>e.onSaved(i=>{i.intent==="publish"&&t({event:"save",action:"save_email",email_id:i.serverId??void 0,project_id:n,subscription:o})}),[e,t,n,o])}function mg(e){const t=r.useStore();(0,l.useEffect)(()=>{},[t,e])}function fg(e,t,n){const o=r.useAppNavigate(),i=r.useContainer();(0,l.useEffect)(()=>{},[o,e,t,n,i])}function gg(e){if(!e)return{status:"unknown"};if("status"in e){const t=e.data,n=t&&typeof t=="object"?t.message:void 0,o=typeof n=="string"?n:typeof t=="string"?t:void 0;return{status:String(e.status),message:o}}return{status:e.name??"unknown",message:e.message}}function Ds(e,t,n){const{status:o,message:i}=gg(n);r.reportMessage(`Failed to load ${e} ${t??"?"}: ${o}`,{origin:"entity-load-error",tags:{mechanism:"entity-load-error",entity_type:e,http_status:o},level:"error",contexts:{entity_load_error:{entityType:e,entityId:t,status:o,message:i,url:window.location.href}}})}var{Content:hg}=_.ui_kit$Layout,_g={paddingTop:"40px"},yg=()=>{const{__:e}=r.useI18n(),{owner:t,admin:n}=Qn(),o=r.useDispatch(),i=Vr(),s=r.useAppNavigate(),{modal:c}=_.ui_kit$App.useApp(),d=r.useAppConfig(),u=r.useRootElement(),p=r.useCookieManager(),f=r.useMessageService(),{emailId:g,preview:y}=r.useRouteParams(),m=r.useEditorProjectId(),E=r.useAppSearchParams(),k=r.useSelector(r.selectIsCodeMode),w=r.useSelector(r.selectActiveModal),v=r.useCurrentUser(),x=r.useProjectData(),P=(0,l.useMemo)(()=>r.createNewEmailDraft(x?{id:Number(x.id),title:x.name}:void 0),[x]),K=r.useSelector(r.selectIsGlobalLoading),[J]=r.useLazyGetMeQuery(),{isSuccess:N,data:L}=r.useGetSubscriptionsQuery(),A=Df(),[O,z]=(0,l.useState)(!1),[B,U]=(0,l.useState)(!1),[de,me]=(0,l.useState)(),[H,Z]=(0,l.useState)(null),[De,ve]=(0,l.useState)(!1),[et,be]=(0,l.useState)(!1),[fe,Y]=(0,l.useState)(!1),[pe,ie]=(0,l.useState)(!1),[se,Ae]=(0,l.useState)(!1),Te=(0,l.useRef)(),{confirm:Fe}=c,{counters:X,subscription:Ee}=v,Ie=X?.emails_counter;p.get(r.APP_COOKIES.em_template_email);const ge=E.get("template")||!B&&!g&&p.get(r.APP_COOKIES.em_new_email),{isSuccess:Re,isLoading:Ue,isError:C,error:T,data:R}=Nf(g?void 0:ge),D=lg({templateEmailId:ge,templateEmail:R,newEmail:P});cg({routeEmailId:g,draft:D});const{document:I,email:S,error:ae}=r.useOpenEmail(),we=S?.id!=null?String(S.id):void 0,Ye=dg(g,we);(0,l.useEffect)(()=>{},[g,we,I,ge]),fg(g,S?.id,m);const Qe=r.useStore(),ze=r.getEmailDocuments(h.getContainer(Qe)),Ze=(0,l.useCallback)((ce,ke)=>ze.save(ce,ke),[ze]),pt=(0,l.useCallback)(()=>ze.saveState(),[ze]),bt=r.usePushToDataLayer();pg({documents:ze,push:bt,projectId:m,subscription:Ee?.post_title}),(0,l.useEffect)(()=>{!B&&S?.id&&U(!0)},[U,B,S?.id]);const ft=ze.history();ag(I,ft),sg(ft),ig(S,ug(g),Ye,I);const lt=Jr({document:I,history:ft});zf(S,I,ze.saveState().saving,ze),mg(m),(0,l.useEffect)(()=>{r.injectEmailRightsResolver(h.getContainer(Qe),ce=>!!(t||n||v.id?.toString()===ce?.author?.toString()))},[Qe,t,n,v.id]);const G=Kp({email:S,save:Ze,saveState:pt,documentSession:I}),{outdatedBlocks:V,isOpen:te,close:ue}=gf({projectId:m,document:I});Uf({projectId:m,project:x,emailProjectId:S?.project,parentEmailId:S?.parent_email});const he=w===r.MODALS.ADD_NEW_EBLOCK_MODAL,Ge=kn(he),qe=kn(fe),{isPromptOpen:st,isConverting:Bt,progress:Le,isErrorOpen:Xe,errorMessage:oe,confirmConversion:ee,cancelPrompt:$,retryConversion:le,closeError:xe,neverSuggestAgain:Se,setNeverSuggestAgain:Me}=Of(),We=ae??(ge?T:void 0),Be=!!We,ot=!S&&!Be,fn=!!S;(0,l.useEffect)(()=>{Be&&We&&Ds("email",g||ge,We)},[Be,We,g,ge]),(0,l.useEffect)(()=>{ge&&Re&&(U(!0),E.set({}))},[ge,Re,E]),(0,l.useEffect)(()=>(o(r.switchIsPanelHistoryCollapsed(!0)),()=>o(r.switchIsPanelHistoryCollapsed(!0))),[o]);const Ot=(0,l.useCallback)(()=>{i.toggle(),o(r.resetPanes())},[o,i]);(0,l.useEffect)(()=>{y&&!k&&Ot()},[k,y,Ot]),(0,l.useEffect)(()=>{document.body.classList.add("editor"),o(r.setActiveSettingsTab(r.BUILD))},[o]),(0,l.useEffect)(()=>{!O&&Ie<3&&(J(),z(!0))},[J,Ie,O]);const ct=(0,l.useCallback)(()=>{lt.undo()},[lt]),Et=(0,l.useCallback)(()=>{lt.redo()},[lt]);(0,l.useEffect)(()=>{Te.current!==S?.id&&(lt.clear(),Te.current=S?.id)},[S,lt]);const Lt=(0,l.useCallback)(ce=>{(window.navigator.appVersion.indexOf("Mac")&&ce.metaKey||ce.ctrlKey)&&ce.code==="KeyZ"&&(ce.preventDefault(),ce.shiftKey?Et():ct())},[ct,Et]);(0,l.useEffect)(()=>()=>{o(r.resetPanes()),o(r.closeModal()),o(r.closeModal$1()),o(r.resetElementHistorySlice())},[o]);const jn=(0,l.useCallback)(ce=>{const ke=()=>{o(r.openModal(r.MODALS.ADD_NEW_EBLOCK_MODAL))},Ne=ce.data.operation,nt=ce.data,je=ce.data.action,Yt=u.querySelector("#iframe-scroll-top"),$t=u.querySelector("#iframe-scroll-bottom");if(Ne===r.EVENT_TYPES.APPLICATION_EBLOCK_ADD){const dt=nt.settings?.emBlockId;dt?Z({html:nt.data,emBlockId:String(dt)}):(me(nt.data),ke())}if(Ne===r.EVENT_TYPES.APPLICATION_ACTION&&(je==="undo"?ct():je==="redo"&&Et()),Ne===r.EVENT_TYPES.APPLICATION_SCROLL_BLOCK_SHOW){const dt=u.querySelector("#email_iframe_slot"),Nn=document.body.getBoundingClientRect().height,Ut=dt.getClientRects()[0];Ut.top<0&&(Yt.style.display="block"),Ut.top+Ut.height>Nn&&($t.style.display="block")}Ne===r.EVENT_TYPES.APPLICATION_SCROLL_BLOCK_HIDE&&(Yt.style.display="none",$t.style.display="none")},[o,ct,Et,u]);r.useListenPostMessage(jn);const On=ce=>{if(ce.target?.closest?.(".file-manager, .ant-modal.file-manager"))return;const ke=ce.dataTransfer,Ne=(ke?Array.from(ke.types||[]):[]).includes(r.DND_SOCIAL_LIST_REORDER_MIME),nt=typeof ce.composedPath=="function"?ce.composedPath():[];ce.target?.closest?.(".selected-social-form")||nt.some(je=>je&&je.nodeType===1&&typeof je.classList?.contains=="function"&&je.classList.contains("selected-social-form"))||Ne||(ce.preventDefault(),ce.target&&f.send({operation:r.EVENT_TYPES.SANDBOX_DRAG_CANCEL}),u.querySelectorAll(".em-dragging-element").forEach(je=>{je.classList.remove("em-dragging-element")}))},gn=(0,l.useRef)({});(0,l.useEffect)(()=>{const ce=new h.Disposable,ke=Ne=>nt=>gn.current[Ne]?.(nt);return ce.addDisposable(r.addWindowListenerFromShadow(u,"drop",ke("drop"))),ce.addDisposable(r.addWindowListenerFromShadow(u,"dragover",ke("dragover"))),ce.addDisposable(r.addWindowListenerFromShadow(u,"dragstart",ke("dragstart"))),ce.addDisposable(r.addWindowListenerFromShadow(u,"dragend",ke("dragend"))),()=>{ce.dispose()}},[u]),(0,l.useEffect)(()=>(window.addEventListener("keydown",Lt),()=>{window.removeEventListener("keydown",Lt)}),[Lt]);const Ln=ce=>{if(ce.preventDefault(),ce.target?.closest?.(".file-manager, .ant-modal.file-manager"))return;const ke=u.querySelector("#iframe-scroll-top"),Ne=u.querySelector("#iframe-scroll-bottom"),nt=d.sidePanelFloating?u.querySelector("#pane-content-wrapper"):u.querySelector(".email-pane__col_preview"),je=u.querySelector(".blocks-app").getBoundingClientRect().top,{height:Yt,top:$t}=u.querySelector("#email_iframe_slot").getBoundingClientRect(),dt=nt.getBoundingClientRect().height;$t>96?ke.style.display==="block"&&(ke.style.display="none"):(ke.style.display==="none"||ke.style.display==="")&&(ke.style.display="block"),Yt-dt+$t-je<44?Ne.style.display==="block"&&(Ne.style.display="none"):Ne.style.display==="none"&&(Ne.style.display="block"),ce.target===ke&&nt.scrollBy(0,-15),ce.target===Ne&&nt.scrollBy(0,15)},Mn=()=>{const ce=u.querySelector("#iframe-scroll-top"),ke=u.querySelector("#iframe-scroll-bottom");ce&&ke&&(ce.style.display="none",ke.style.display="none"),u.querySelectorAll(".em-dragging-element").forEach(Ne=>{Ne.classList.remove("em-dragging-element")})},gt=ce=>{const ke=ce.target,Ne=ke instanceof Element?ke:ke.parentElement;if(!(Ne instanceof Element)||Ne.closest(".selected-social-form"))return;Ne.parentElement?.classList.add("em-dragging-element");const nt=!!Ne.closest(".blocks-search__result-wrapper");var je=nt?r.cloneBlockPreviewForDrag(Ne.querySelector(".blocks-search__result-html")):Ne.cloneNode(!0);je.classList.add("em-ghost-element"),je.style.height=nt?"auto":"70px",je.style.width=nt?"600px":"109px",je.style.position="absolute",je.style.top="0",je.style.left="0",je.style.zIndex="-1",Ne.appendChild(je),ce.dataTransfer.setDragImage(je,0,0),window.setTimeout(function(){je.parentNode.removeChild(je)},1e3)};gn.current={drop:On,dragover:Ln,dragstart:gt,dragend:Mn};const St=(0,l.useCallback)(()=>{Fe({title:e("You reached the plan limit"),icon:(0,a.jsx)(r.EmIcons,{icon:"ExclamationCircleOutlined",component:_.icons$ExclamationCircleOutlined}),content:(0,a.jsx)("div",{style:{maxWidth:"330px"},children:e("Switch to a different plan to save more emails.")}),centered:!0,okText:e("Choose a plan"),cancelText:e("Continue without saving"),width:"unset",onOk(){s("/billing")},onCancel(){}})},[s,e,Fe]);return(0,l.useEffect)(()=>{if(N&&L){const ce=L?.find(ke=>ke.id?.toString()===Ee?.ID?.toString())?.limits?.emails_limit;ce&&Ie>=ce&&!De&&!g&&t&&(St(),ve(!0))}},[L,N,Ee,Ie,De,St,g,t]),(0,l.useEffect)(()=>{const ce=f.onInit(()=>{f.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:!1})});return()=>ce.dispose()},[f]),(0,a.jsx)(r.DocumentSessionProvider,{document:I,history:ft,children:(0,a.jsx)(hs.Provider,{value:G,children:(0,a.jsxs)(_.ui_kit$Layout,{className:"email-page",children:[ot&&(0,a.jsx)(_.ui_kit$PageLoader,{}),!ot&&A.status==="pending"&&(0,a.jsx)(_.ui_kit$PageLoader,{}),A.status==="error"&&(0,a.jsx)(hg,{style:_g,children:(0,a.jsx)("div",{className:"container",children:(0,a.jsx)(_.ui_kit$Result,{status:"warning",title:e("Failed to load plan data"),subTitle:e("Editor features depend on your plan. Check your connection and try again."),extra:(0,a.jsx)(_.ui_kit$Button,{type:"primary",onClick:A.retry,children:e("Try again")})})})}),Be&&We&&!1,S&&!ot&&A.status==="ready"&&(0,a.jsxs)(_.ui_kit$Layout,{className:"email-pane",children:[K&&(0,a.jsx)("div",{className:"email-pane__loader",children:(0,a.jsx)(_.ui_kit$PageLoader,{small:!0})}),(0,a.jsx)(Is,{email:S,isCollaborationEditor:et}),(0,a.jsx)(Np,{emailElement:S,isSuccess:fn,setIsCollaborationEditor:be,setIsShowAddAllBlocksModal:Y,triggerOpenSavedBlocksTab:pe})]}),Ge&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Cu,{isModalVisible:he,htmlContent:de,projectId:m,setIsShowAddAllBlocksModal:Y,setIsShowAddAllBlocksModalForNewEmail:Ae,currentEmail:S})}),(0,a.jsx)(pf,{open:te,blocks:V,projectId:m,onClose:ue}),(0,a.jsx)(hf,{open:!!H,html:H?.html,emBlockId:H?.emBlockId,onSaveAsNew:()=>{me(H?.html),Z(null),o(r.openModal(r.MODALS.ADD_NEW_EBLOCK_MODAL))},onClose:()=>Z(null)}),qe&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Tu,{isModalVisible:fe,currentEmail:S,setIsShowAddAllBlocksModal:Y,setTriggerOpenSavedBlocksTab:ie,autoStart:!se,projectId:m})}),(0,a.jsx)(bf,{open:st,onConfirm:ee,onCancel:$,neverSuggestAgain:Se,onNeverSuggestAgainChange:Me}),(0,a.jsx)(wf,{open:Bt,progress:Le}),(0,a.jsx)(Sf,{open:Xe,message:oe,onRetry:le,onCancel:xe})]})})})};function vg(){const e=r.useStore(),t=r.getEmailDocuments(h.getContainer(e)),n=(0,l.useCallback)(o=>t.subscribe(o),[t]);return(0,l.useSyncExternalStore)(n,()=>!!t.current())}function bg(e,t){const n=r.useStore(),o=r.useAppConfig(),i=r.useStorageProvider();(0,l.useRef)(new Set),(0,l.useEffect)(()=>{},[e,t,o,n,i])}var Eg=30;function Sg(e){const t=r.useContainer(),n=r.useGetProjectQuery(+e,{skip:!e,refetchOnMountOrArgChange:Eg}),{isSuccess:o,isError:i,error:s,data:c,isFetching:d}=n;bg(e,o),(0,l.useEffect)(()=>{t&&r.setCurrentProjectRefreshing(t,d)},[t,d]),(0,l.useEffect)(()=>{t&&o&&c&&String(c.id)===String(e)&&r.setCurrentProjectCard(t,c)},[o,c,t,e]),(0,l.useEffect)(()=>{i&&s&&Ds("project",e,s)},[i,s,e]);const u=r.useProjectData(),p=!!u&&String(u.id)===String(e);return{...n,projectReady:p}}var An=r.createApi({reducerPath:"promoApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.emailmaker.ru/api/wp-json/promo/v1/"}),endpoints:e=>({checkPromo:e.mutation({queryFn:({code:t,type:n},o)=>r.clientFromApi(o).promo.set_code_create({code:t,type:n})}),getPromoInfo:e.query({queryFn({code:t},n){return r.clientFromApi(n).promo.get_code_info_list({code:t})}})})}),{useCheckPromoMutation:sb,useGetPromoInfoQuery:ab}=An;function wg(){const e=r.useContainer(),[t,n]=(0,l.useState)();return(0,l.useEffect)(()=>{if(!e)return;let o=!0;return r.getAppProject(e).then(i=>{o&&i!=null&&n(String(i))},()=>{}),()=>{o=!1}},[e]),t}var kg=()=>{const e=r.useDispatch(),t=r.useCookieManager(),n=r.useCurrentUser(),o=r.useContainer();(0,l.useEffect)(()=>{const s=n?.code_editor;s&&o&&r.applyEditorOptions(o,s)},[n,o]),(0,l.useEffect)(()=>{const s=t.get(r.APP_COOKIES.em_token),c=t.get(r.APP_COOKIES.promocode);s&&c&&(e(An.endpoints.checkPromo.initiate({code:c,type:"by_link"})),t.remove(r.APP_COOKIES.promocode))},[e,t]),r.useNotifyCommand();const i=vg();return Sg(wg()),i?(0,a.jsx)(Ql,{hasEmail:!0,children:(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$PageLoader,{}),children:(0,a.jsx)(yg,{})})}):null};function Cg(e,t){const n=(0,l.useRef)(!1);(0,l.useEffect)(()=>{!e||n.current||(n.current=!0,r.mark(r.PHASES.appVisible),t&&Ht(t).noteShellVisible())},[e,t])}var xn=new WeakMap,Tg="data-useblocks-config-styles";function Ig(e){return typeof e=="string"?e.trim():""}function Fs(e,t){if(e.firstChild){e.insertBefore(t,e.firstChild);return}e.appendChild(t)}function Ag(e,t,n){if(!e||typeof document>"u")return null;const o=Ig(t),i=xn.get(e),s=n||e;if(!o)return i&&(i.remove(),xn.delete(e)),null;if(i)return i.textContent!==o&&(i.textContent=o),(i.parentNode!==s||i!==s.firstChild)&&Fs(s,i),i;const c=document.createElement("style");return c.setAttribute(Tg,"true"),c.textContent=o,Fs(s,c),xn.set(e,c),c}function vo(e){if(!e)return;const t=xn.get(e);t&&(t.remove(),xn.delete(e))}var xg={height:"100%",display:"flex",justifyContent:"center",alignItems:"center"},Pg=({children:e,handleBeforeRender:t})=>{const[n,o]=(0,l.useState)(),i=r.useIsLocaleInited();Cg(i,r.useContainer());const s=r.useAppConfig().styles,c=(0,l.useRef)(null),d=(0,l.useRef)(!1),u=(0,l.useRef)(void 0),p=r.useRootElement();return(0,l.useLayoutEffect)(()=>{d.current||(d.current=!0,t&&t())},[]),(0,l.useLayoutEffect)(()=>{if(!p){u.current&&(vo(u.current),u.current=void 0);return}u.current&&u.current!==p&&vo(u.current),Ag(p,s,c.current||void 0),u.current=p},[p,s]),(0,l.useLayoutEffect)(()=>()=>{u.current&&(vo(u.current),u.current=void 0)},[]),(0,a.jsxs)(_.ui_kit$StyleProvider,{container:r.findShadowRoot(p)||document.head,children:[(0,a.jsxs)("div",{ref:c,className:"App blocks-app blocks-plugin",style:i?{}:{visibility:"hidden"},children:[(0,a.jsx)(r.ModalRootContext.Provider,{value:n,children:e}),(0,a.jsx)("div",{ref:o,className:"blocks-modal-container"})]}),!i&&(0,a.jsx)(_.ui_kit$Space,{size:"large",style:xg,children:(0,a.jsx)(_.ui_kit$Spin,{size:"large"})})]})};async function Rg({container:e,renderTarget:t,mapKey:n,disposable:o,chunkLoadedFire:i}){const s=await e.getInstanceAsync(h.STORE_ID);return new Promise(c=>{if(o.isDisposed()){c();return}const d=(0,nl.createRoot)(t),u=(0,a.jsx)(r.Provider,{store:s,children:(0,a.jsx)(Wl,{onLoad:c,children:(0,a.jsx)(r.RootContext.Provider,{value:{element:n},children:(0,a.jsx)(_.ui_kit$StyleProvider,{container:r.isDocumentFragment(n)?document.head:n,children:(0,a.jsx)(r.LocaleProvider,{children:(0,a.jsx)(Pg,{handleBeforeRender:i,children:(0,a.jsx)(pl,{children:(0,a.jsx)(Gl,{children:(0,a.jsx)(kg,{})})})})})})})})});d.render(u),o.addDispose(c),o.addDispose(()=>{try{d.unmount()}catch(p){if(p instanceof DOMException&&p.name==="NotFoundError"||p instanceof Error&&p.name==="NotFoundError"&&/removeChild/i.test(p.message)){r.logShowPipelineError("mount:unmount-dom-mismatch (host container was already removed)",{hint:"Usually harmless during host React StrictMode teardown. Ensure instance.destroy() runs before the host removes the mount container."});return}throw p}}),o.addDispose(()=>{h.ELEMENT_MAP.delete(n)})})}var lb="multiple init call on single HTMLELEMENT",jg=zn(async e=>{let t=null,n=!1;const o=h.getEmitter(e,h.events.ON_CHUNKS_LOADED),i=e.getInstance(h.DISPOSABLE_ID);let s,c=!1;const d=()=>{c||(c=!0,r.mark(r.PHASES.chunksLoaded),o.fire())},u=(p,f)=>Rg({container:e,renderTarget:p,mapKey:f,disposable:s,chunkLoadedFire:d});return{instance:{getElement(){return t}},async setOptions(p){const f=e.getInstance(h.INIT_PIPELINE_ID),g=await h.waitForElement(p.element,i,f.signal),y=e.getInstance(h.INSTANCE_ID),m=!!p.hidden&&!!g;if(t===g&&n===m)return;const E=t===g&&n&&!m;n=m,i.addDisposable(o.event(()=>{p.handleChunkLoaded&&p.handleChunkLoaded()})),t&&h.ELEMENT_MAP.delete(t),g&&h.ELEMENT_MAP.has(g),s&&s.dispose(),s=i.addDisposable(new h.Disposable);const k=p.element!==void 0;if(r.setHeadlessMode(e,!g||m),r.setHiddenMount(e,m),!g){r.mark(r.MOUNT_HEADLESS_MARK);const v=document.createElement("div");v.style.position="absolute",v.style.left="-10000px",v.style.top="-10000px",v.style.width="1600px",v.style.height="1000px",document.body.appendChild(v),t=v,d(),s.addDispose(()=>{v.parentNode===document.body&&v.remove()});return}const w=r.findShadowRoot(g);if(w&&s.addDisposable(new ul({shadowRoot:w})),k&&g instanceof Element){const v=g;il(v,()=>{i.isDisposed()||s?.isDisposed()||(r.logShowPipelineError("mount:detached (host removed element without destroy)",{elementId:v.id||null}),f.abort(ol()))},s)}if(m){r.mark(r.MOUNT_HEADLESS_MARK),t=g,d();return}if(k&&g instanceof Element){const v=g,x=cl(v);t=v;const P=u(x,v);return dl(v,x,s),P}return t=g,u(g,g)},dispose(){s&&!s.isDisposed()&&s.dispose()}}});function bo(e){return zn(async t=>(await t.getInstanceAsync(h.STORE_ID),await e(t)))}function Og({html:e,renderGuid:t,...n},o){const{requested:i}=r.getCurrentProject(o);return r.filterUndefined({...n,code:on(o).toOutputForm(e),project:i===void 0?n.project:i,guid:void 0,link:void 0,status:void 0,slug:void 0,password:void 0,comment_status:void 0,template:void 0,blocktags:void 0,project_title:void 0,ping_status:void 0,lock:void 0,tag:void 0,is_template:void 0})}function Lg(e,t){return r.filterUndefined({...e,link:void 0,comment_status:void 0})}function Mg({html:e,...t},n){return r.filterUndefined({...t,code:e,guid:void 0,compiled:r.filterUndefined({html:e,ampHtml:e&&""})})}var Bs=e=>{const t={current:Promise.resolve(),state:e,decorate:(n,o)=>(o&&(n=n.bind(o)),function(...i){const s=t.current.then(()=>n(...i));return t.current=s.then(c=>{t.state=c},c=>{}),s})};return t},Ng=h.createIdentifier$1("emailTemplate.reads");async function Dg(e,t){try{return await r.getRestEmailPortFactories(e).email(e).readEmail(t)??void 0}catch(n){r.logShowPipelineError("show:template-read-failed",{templateId:t,error:n instanceof Error?n.message:"неизвестная ошибка"});return}}function Fg(e,t){const n=e.getOrCreateInstance(Ng,()=>new Map),o=n.get(t);if(o!==void 0)return o;const i=Dg(e,t).then(s=>(s===void 0&&n.delete(t),s));return n.set(t,i),i}var kt=class extends h.Disposable{_event;_listener;_disposeEvent;constructor(e){super(),this._event=e}setListener(e){this._listener!==e&&(this._listener=e,this._disposeEvent&&this._disposeEvent(),e?this._disposeEvent=this._event(e):this._disposeEvent=void 0)}dispose(){this._disposeEvent&&this._disposeEvent(),super.dispose()}};function Ct(e,t,n){const o=h.snapshot(e);return(i,s,c)=>{const d=o(async u=>{const p=t?t(u):u;c&&i.bind(c);const f=await i(p);return n?n(f):f},s,c);return()=>d.dispose()}}var cb=h.createIdentifier("application_block_inserted"),db=h.createIdentifier$1("DataController"),ub=h.createIdentifier$1("DataEvents"),Bg=h.createIdentifier$1("plugin.startupShow");function $g(e){return e.getInstance(Bg)?.current??Promise.resolve()}var $s=bo(async()=>({instance:{}})),Us=bo(async e=>({instance:{},async setOptions(){await $g(e)}})),pb=h.combineMixins([$s,Us]),zs=()=>({title:"",description:"",website:"",company_size:"",industry:"",email:"",phone:"",logo_url:""}),Ug={title:"title",description:"description",website:"website",company_size:"company_size",industry:"industry",email:"email",phone:"phone",logo_url:"logo"},Gs=e=>({...zs(),title:e?.title??"",description:e?.description??"",website:e?.website??"",company_size:e?.company_size??"",industry:e?.industry??"",email:e?.email??"",phone:e?.phone??"",logo_url:e?.logo??""}),Ws=e=>(e??[]).filter(t=>!!t?.code).map(({code:t,label:n})=>({value:t,label:n??t})),zg=e=>({company_sizes:Ws(e?.company_sizes),industries:Ws(e?.industries)}),mb=Object.keys(zs()),Hs="ProjectProfile",Pn=r.createApi({reducerPath:"projectSettingsProfileApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),tagTypes:[Hs],endpoints:e=>({getProjectProfile:e.query({async queryFn(t,n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.profileList({id:String(t)}));return"error"in o?{error:o.error}:{data:Gs(o.data)}},providesTags:(t,n,o)=>[{type:Hs,id:String(o)}]}),getProjectProfileOptions:e.query({async queryFn(t,n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.profileOptionsList());return"error"in o?{error:o.error}:{data:zg(o.data)}}}),updateProjectProfileField:e.mutation({async queryFn({projectId:t,field:n,value:o},i){const s={[Ug[n]]:o},c=r.v2ResultOf(await r.getClientV2(h.getContainer(i)).projects.profilePartialUpdate({id:String(t)},s));return"error"in c?{error:c.error}:{data:Gs(c.data)}},async onQueryStarted({projectId:t},{dispatch:n,queryFulfilled:o}){try{const{data:i}=await o;n(Pn.util.updateQueryData("getProjectProfile",t,()=>i))}catch{}}})})}),{useGetProjectProfileQuery:fb,useGetProjectProfileOptionsQuery:gb,useUpdateProjectProfileFieldMutation:hb}=Pn,qs="ProjectStorage",Rn=r.createApi({reducerPath:"projectSettingsStorageApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),tagTypes:[qs],endpoints:e=>({getProjectStorage:e.query({async queryFn(t,n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.storageList({id:String(t)}));return"error"in o?{error:o.error}:{data:o.data}},providesTags:(t,n,o)=>[{type:qs,id:String(o)}]}),updateProjectStorage:e.mutation({async queryFn({projectId:t,body:n},o){const i=r.v2ResultOf(await r.getClientV2(h.getContainer(o)).projects.storageUpdate({id:String(t)},n));return"error"in i?{error:i.error}:{data:i.data}},async onQueryStarted({projectId:t},{dispatch:n,queryFulfilled:o}){const{data:i}=await o;n(Rn.util.upsertQueryData("getProjectStorage",t,i))}}),testProjectStorageConnection:e.mutation({async queryFn({projectId:t,body:n},o){const i=r.v2ResultOf(await r.getClientV2(h.getContainer(o)).projects.storageTestCreate({id:String(t)},n));return"error"in i?{error:i.error}:{data:i.data}}})})}),{useGetProjectStorageQuery:_b,useUpdateProjectStorageMutation:yb,useTestProjectStorageConnectionMutation:vb}=Rn,Gg=class{http;constructor(e){this.http=e}settings_summary_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/settings-summary/${e}`,method:"GET",...n})},Vs=class{http;constructor(e){this.http=e}developer_credentials_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}`,method:"GET",...n});developer_credentials_partial_update=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}`,method:"PATCH",...n});developer_credentials_rotate_secret_create=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}/rotate-secret`,method:"POST",...n});developer_credentials_verify_secret_create=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}/verify-secret`,method:"POST",...n})},Wg=class{http;constructor(e){this.http=e}developer_kit_postman_collection_list=(e={})=>this.http.request({path:"/projects/v1/developer-kit/postman-collection",method:"GET",...e})},Hg=class{http;constructor(e){this.http=e}billing_context_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/billing-context/${e}`,method:"GET",...n});billing_context_payments_list=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/billing-context/${e}/payments`,method:"GET",query:t,...n})},qg=class{http;constructor(e){this.http=e}usage_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/usage/${e}`,method:"GET",...n});usage_timeseries_list=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/usage/${e}/timeseries`,method:"GET",query:t,...n})},Ke={PLUGIN_INIT:"plugin_init",LINK_CHECK:"link_check",IMAGE_CHECK:"image_check",SPAM_ASSASSIN:"spam_assassin",AI_IMAGE:"ai_image",AI_WRITE:"ai_write",AI_REPHRASE:"ai_rephrase"},Zt={TODAY:"today",WEEK:"week",MONTH:"month",CUSTOM:"custom"},bb=[Ke.PLUGIN_INIT,Ke.LINK_CHECK,Ke.IMAGE_CHECK,Ke.SPAM_ASSASSIN,Ke.AI_IMAGE,Ke.AI_WRITE],ln={current:0,limit:null},Vg=()=>({pluginInit:{...ln},aiAssistant:{...ln},aiImage:{...ln},linkCheck:{...ln},imageCheck:{...ln},spamAssassin:{...ln}}),tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Je=(e,t,n="")=>{for(const o of t){const i=e[o];if(typeof i=="string")return i;if(typeof i=="number"&&Number.isFinite(i))return String(i)}return n},Ft=(e,t,n=0)=>{for(const o of t){const i=e[o];if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()&&Number.isFinite(Number(i)))return Number(i)}return n},Eo=(e,t,n=!1)=>{for(const o of t){const i=e[o];if(typeof i=="boolean")return i}return n},br=(e,t)=>{for(const n of t){const o=e[n];if(o===null)return null;if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()&&Number.isFinite(Number(o)))return Number(o)}return null},Kg=new Set(Object.values(Ke)),Yg=e=>Kg.has(e)?e:null,en=e=>tt(e)&&"data"in e&&(e.ok===!0||typeof e.success=="boolean"||e.success===void 0)?e.data:e,cn=(e,t)=>{for(const n of t){const o=e[n];if(tt(o))return o}return null},Qg=(e,t)=>{for(const n of t){const o=e[n];if(!Array.isArray(o))continue;const i=o.filter(s=>typeof s=="string");if(i.length>0)return i}},Xg=e=>tt(e)?{clientId:Je(e,["clientId","client_id"]),clientSecretConfigured:Eo(e,["clientSecretConfigured","client_secret_configured"]),rotatedAt:Je(e,["rotatedAt","rotated_at"])||void 0,scopesSuggested:Qg(e,["scopesSuggested","scopes_suggested"])}:{clientId:"",clientSecretConfigured:!1},Ks=(e,t)=>{for(const n of t){const o=e[n];if(typeof o=="boolean")return o}},Jg=e=>{const t=Ks(e,["pluginConnected","plugin_connected","connected","is_connected"]);if(t!==void 0)return t;for(const n of["plugin","developer_credentials","developerCredentials"]){const o=cn(e,[n]);if(!o)continue;const i=Ks(o,["connected","plugin_connected","is_connected"]);if(i!==void 0)return i;const s=Je(o,["clientId","client_id"]),c=Eo(o,["clientSecretConfigured","client_secret_configured"]);if(s)return c}},Zg=e=>{const t=en(e);if(!tt(t))return{};const n=cn(t,["members"]);return{myRole:Je(t,["myRole","my_role","role"])||(n?Je(n,["myRole","my_role","role"]):"")||void 0,pluginConnected:Jg(t)}},eh=e=>tt(e)?{clientId:Je(e,["clientId","client_id"]),secret:Je(e,["secret","clientSecret","client_secret"])}:{clientId:"",secret:""},th=e=>{if(!tt(e))return null;const t=Je(e,["event","type","key"]),n=Yg(t);if(!n)return null;const o=e.delta??e.change??e.trend,i=o==null?null:typeof o=="number"&&Number.isFinite(o)?o:Number.isFinite(Number(o))?Number(o):null;return{event:n,total:Ft(e,["total","count","value"],0),delta:i}},Ys=e=>{if(!tt(e))return null;const t=Je(e,["date","day","x"]);if(!t)return null;const n={date:t},o=e.event_counts??e.eventCounts;if(tt(o)){for(const[i,s]of Object.entries(o))typeof s=="number"&&Number.isFinite(s)&&(n[i]=s);return n}for(const[i,s]of Object.entries(e))i==="date"||i==="day"||i==="x"||i==="event_counts"||i==="eventCounts"||typeof s=="number"&&Number.isFinite(s)&&(n[i]=s);return n},nh=e=>{const t=en(e);return tt(t)?(Array.isArray(t.chart)?t.chart:Array.isArray(t.series)?t.series:Array.isArray(t.time_series)?t.time_series:Array.isArray(t.history)?t.history:[]).map(Ys).filter(n=>n!==null):[]},rh=e=>{if(!tt(e))return{current:0,limit:null};const t=Ft(e,["current","count","used","value","total"],0),n=br(e,["limit","max","quota","cap"]);return{current:t,limit:n===null?null:n}},dn=(e,t)=>{for(const n of t)if(n in e)return rh(e[n]);return{current:0,limit:null}},un={pluginInit:[Ke.PLUGIN_INIT,"plugin_init","pluginInit"],aiAssistant:["ai_assistant","aiAssistant","ai"],aiImage:[Ke.AI_IMAGE,"ai_image","ai_img","aiImg"],linkCheck:[Ke.LINK_CHECK,"link_check","linkCheck"],imageCheck:[Ke.IMAGE_CHECK,"image_check","imageCheck"],spamAssassin:[Ke.SPAM_ASSASSIN,"spam_assassin","spamAssassin","spam_check","spamCheck"]},So=e=>{const t=Vg(),n=en(e),o=tt(n)&&tt(n.usage)?n.usage:n;if(!tt(o))return t;const i=Ft(o,["operationsTotal","operations_total"],0),s=Ft(o,["operationsLast30d","operations_last_30d"],0),c=cn(o,["metrics","counters","limits","events","usage_by_event","usageByEvent"])??o;return{pluginInit:dn(c,un.pluginInit),aiAssistant:dn(c,un.aiAssistant),aiImage:dn(c,un.aiImage),linkCheck:dn(c,un.linkCheck),imageCheck:dn(c,un.imageCheck),spamAssassin:dn(c,un.spamAssassin),lastActivityAt:Je(o,["lastActivityAt","last_activity_at"])||void 0,operationsTotal:i>0?i:void 0,operationsLast30d:s>0?s:void 0}},Qs=(e,t)=>{const n=[{event:Ke.LINK_CHECK,total:e.linkCheck.current,delta:null},{event:Ke.IMAGE_CHECK,total:e.imageCheck.current,delta:null},{event:Ke.SPAM_ASSASSIN,total:e.spamAssassin.current,delta:null},{event:Ke.AI_IMAGE,total:e.aiImage.current,delta:null}],o=t?nh(t):[];return o.length>0?{cards:n,chart:o}:{cards:n,chart:[]}},oh=e=>{const t=en(e);if(!tt(t))return Qs(So(e),e);const n=Array.isArray(t.cards)?t.cards:Array.isArray(t.summary)?t.summary:[],o=Array.isArray(t.chart)?t.chart:Array.isArray(t.series)?t.series:[];return n.length>0||o.length>0?{cards:n.map(th).filter(i=>i!==null),chart:o.map(Ys).filter(i=>i!==null)}:Qs(So(t),t)},ih=e=>{if(!tt(e))return null;const t=Je(e,["id","payment_id"]);return t?{id:t,date:Je(e,["date","created_at","paid_at"]),amount:Ft(e,["amount","sum"],0),currency:Je(e,["currency"],"RUB"),status:Je(e,["status"],"unknown"),receiptUrl:Je(e,["receiptUrl","receipt_url","pdf_url"])||void 0}:null},sh=e=>{const t=en(e),n=tt(t)&&Array.isArray(t.payments)?t.payments:[];return{payments:n.map(ih).filter(o=>o!==null),page:tt(t)?Ft(t,["page"],1):1,perPage:tt(t)?Ft(t,["perPage","per_page"],20):20,total:tt(t)?Ft(t,["total"],n.length):n.length,totalPages:tt(t)?Ft(t,["totalPages","total_pages"],1):1}},ah=e=>{const t=en(e);if(!tt(t))return{viewerSeesBilling:!1};const n=cn(t,["endpoints"])??{},o=cn(t,["documentLinks","document_links"]),i=o?Object.fromEntries(Object.entries(o).filter(f=>typeof f[1]=="string")):void 0,s=br(t,["ownerUserId","owner_user_id"]),c=cn(t,["tariff","plan","subscription"]),d=Je(t,["planDescription","plan_description"])||(c?Je(c,["description","about","plan_description"]):"")||void 0,u=br(t,["planPrice","plan_price","price","amount"])??(c?br(c,["price","amount"]):null),p=Je(t,["planCurrency","plan_currency","currency"])||(c?Je(c,["currency"]):"")||void 0;return{viewerSeesBilling:Eo(t,["viewerSeesBilling","viewer_sees_billing"]),ownerUserId:s??void 0,planName:Je(t,["planName","plan_name"])||void 0,planDescription:d,planPrice:u??void 0,planCurrency:p||void 0,endpoints:{limitsStats:Je(n,["limitsStats","limits_stats"])||void 0,subscriptionMe:Je(n,["subscriptionMe","subscription_me"])||void 0,payments:Je(n,["payments"])||void 0},documentLinks:i&&Object.keys(i).length>0?i:void 0}},lh={myRole:"owner"},ch=()=>({...lh}),dh={clientId:"rust-awkward-bear",clientSecretConfigured:{}.REACT_APP_PLUGIN_SETTINGS_MOCK_CONNECTED!=="false"},Xs=()=>({...dh,clientSecretConfigured:{}.REACT_APP_PLUGIN_SETTINGS_MOCK_CONNECTED!=="false"}),Js=Object.values(Ke),uh={[Ke.PLUGIN_INIT]:42,[Ke.LINK_CHECK]:-15,[Ke.IMAGE_CHECK]:28,[Ke.SPAM_ASSASSIN]:9,[Ke.AI_IMAGE]:6,[Ke.AI_WRITE]:-11,[Ke.AI_REPHRASE]:4},ph=(e,t)=>{const n={date:e};return Js.forEach((o,i)=>{const s=Math.sin(t*.65+i*.9),c=t*(i%2===0?.35:.2),d=2+i;n[o]=Math.max(0,Math.round(d+s*4+c))}),n},mh=e=>Js.map(t=>({event:t,total:e.reduce((n,o)=>n+(typeof o[t]=="number"?o[t]:0),0),delta:uh[t]})),fh=({period:e,dateFrom:t,dateTo:n})=>{const o=(0,En.default)().startOf("day");if(e===Zt.WEEK)return{startDate:o.subtract(6,"day"),days:7};if(e===Zt.MONTH)return{startDate:o.subtract(29,"day"),days:30};if(e===Zt.CUSTOM&&t&&n){const i=(0,En.default)(t),s=(0,En.default)(n);return{startDate:i,days:Math.max(1,s.diff(i,"day")+1)}}return{startDate:o,days:1}},wo=(e={period:Zt.TODAY})=>{const{startDate:t,days:n}=fh(e),o=Array.from({length:n},(i,s)=>ph(t.add(s,"day").format("YYYY-MM-DD"),s));return{cards:mh(o),chart:o}},Eb=wo({period:Zt.WEEK}),gh={pluginInit:{current:0,limit:null},aiAssistant:{current:0,limit:null},aiImage:{current:42,limit:100},linkCheck:{current:128,limit:500},imageCheck:{current:64,limit:200},spamAssassin:{current:31,limit:150},lastActivityAt:"2026-05-02T12:00:00Z"},Zs={payments:[{id:"98765",date:"2026-05-12T10:15:00+00:00",amount:990,currency:"RUB",status:"success",receiptUrl:"https://receipts.example/98765.pdf"},{id:"98764",date:"2026-04-12T10:15:00+00:00",amount:990,currency:"RUB",status:"success"},{id:"98763",date:"2026-03-12T10:15:00+00:00",amount:990,currency:"RUB",status:"failed"}],page:1,perPage:20,total:3,totalPages:1},hh={viewerSeesBilling:!0,ownerUserId:1,planName:"Corporate",planDescription:"For fully addressing all necessary tasks in any field.",planPrice:3200,planCurrency:"RUB",endpoints:{limitsStats:"/wp-json/limits/v1/stats",subscriptionMe:"/wp-json/subscription/v2/me",payments:"/wp-json/projects/v1/billing-context/2581/payments"}},_h={info:{name:"EmailMaker Plugin Requests",schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:[]},yh=e=>e,vh=()=>!1,bh=()=>!1,Eh=e=>e,pn="ProjectPlugin",Sh=()=>({}).REACT_APP_PLUGIN_SETTINGS_USE_MOCK==="true",Vt=(e,t,n)=>e.error&&Sh()?{data:n(t)}:r.transformResponseFn(n)(e),wh=e=>yh(Xg(e)),kh=e=>Eh(ah(e)),Ch=({period:e,dateFrom:t,dateTo:n})=>{if(e===Zt.CUSTOM){const o={};return t&&(o.date_from=t),n&&(o.date_to=n),o}return{period:e??Zt.TODAY}},Er=r.createApi({reducerPath:"projectSettingsPluginApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api".replaceAll(/[\\/]$/g,"")}),tagTypes:[pn],endpoints:e=>({getPluginSummary:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Gg]).settings_summary_detail({projectId:t}).then(o=>Vt(o,ch(),Zg))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:o}]}),getPluginCredentials:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Vs]).developer_credentials_detail({projectId:t}).then(o=>Vt(o,Xs(),wh))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:`credentials-${o}`}]}),rotatePluginSecret:e.mutation({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Vs]).developer_credentials_rotate_secret_create({projectId:t}).then(o=>Vt(o,{clientId:Xs().clientId,secret:"mock-rotated-secret"},eh))},invalidatesTags:(t,n,{projectId:o})=>[{type:pn,id:`credentials-${o}`}]}),getPostmanCollection:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Wg]).developer_kit_postman_collection_list({extraQuery:{project_id:String(t)}}).then(o=>Vt(o,_h,i=>en(i)??i))}}),getPluginAnalytics:e.query({queryFn({projectId:t,period:n,dateFrom:o,dateTo:i},s){const c={period:n,dateFrom:o,dateTo:i};return vh()?Promise.resolve({data:wo(c)}):r.getClient(h.getContainer(s)).request({path:`/projects/v1/usage/${t}/timeseries`,method:"GET",query:Ch(c)}).then(d=>Vt(d,wo(c),oh))}}),getPluginBillingContext:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Hg]).billing_context_detail({projectId:t}).then(o=>Vt(o,hh,kh))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:`billing-${o}`}]}),getPluginUsage:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[qg]).usage_detail({projectId:t}).then(o=>Vt(o,gh,So))}}),getPluginPayments:e.query({queryFn({projectId:t,page:n=1,perPage:o=20},i){return bh()?Promise.resolve({data:Zs}):r.getClient(h.getContainer(i)).request({path:`/projects/v1/billing-context/${t}/payments`,method:"GET",query:{page:String(n),per_page:String(o)}}).then(s=>Vt(s,Zs,sh))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:`payments-${o}`}]})})}),{useGetPluginSummaryQuery:Sb,useGetPluginCredentialsQuery:wb,useRotatePluginSecretMutation:kb,useLazyGetPostmanCollectionQuery:Cb,useGetPluginAnalyticsQuery:Tb,useGetPluginBillingContextQuery:Ib,useGetPluginPaymentsQuery:Ab,useGetPluginUsageQuery:xb}=Er,ea="EmailRaw",Sr=r.createApi({reducerPath:"emailRawApi",tagTypes:[ea],baseQuery:r.fetchBaseQuery({baseUrl:"https://app.useblocks.io/api/wp-json/wp/v2/"}),endpoints:e=>({getEmailRaw:e.query({queryFn:function({emailId:t,secret_hash:n},o){return h.getApi(h.getContainer(o),[h.WpEmailApi]).email_detail({id:t},{extraQuery:{secret_hash:n}}).then(r.transformResponseFn(r.WpEmailToEmail))},providesTags:(t,n,o)=>[{type:ea,id:o}]})})}),{useGetEmailRawQuery:Pb}=Sr,wr=r.createApi({reducerPath:"yandexAuthApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({validateYandexToken:e.mutation({query:t=>({url:"/auth/yandex",method:"POST",body:t})})})}),{useValidateYandexTokenMutation:Rb}=wr,kr=r.createApi({reducerPath:"elamaAuthApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({validateElamaCode:e.mutation({query:t=>({url:"/auth/elama",method:"POST",body:t})})})}),{useValidateElamaCodeMutation:jb}=kr,Cr=r.createApi({reducerPath:"googleAuthApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({validateGoogleToken:e.mutation({query:t=>({url:"/auth/google",method:"POST",body:t})})})}),{useValidateGoogleTokenMutation:Ob}=Cr,ta=async e=>{const t=await e.text();let n=t;try{n=JSON.parse(t)}catch{n=t}return n},Th=(e,t,n)=>{if(!e)throw new Error(`Set ${n}`);return{url:`?proxy_url=${encodeURIComponent(e)}`,method:"POST",headers:{"Content-Type":"application/json"},body:t,responseHandler:ta}},Ih=(e,t,n)=>{if(!e)throw new Error(`Set ${n}`);return{url:`?proxy_url=${encodeURIComponent(e)}`,method:"POST",body:t,responseHandler:ta}},Tr=r.createApi({reducerPath:"requestPlaneApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({getRequest:e.mutation({query:t=>Ih("https://webhook.latenode.com/5868/prod/5c07527e-9d53-467a-a148-87220d46e9ae",t,"REACT_APP_PIPEDREAM_REQUEST_PLANE_SRC")}),getInvoiceRequest:e.mutation({query:t=>Th("https://webhook.latenode.com/5868/prod/5c07527e-9d53-467a-a148-87220d46e9ae",t,"REACT_APP_REQUEST_PLANE_WEBHOOK_URL")})})}),{useGetRequestMutation:Lb,useGetInvoiceRequestMutation:Mb}=Tr,Ir=r.createApi({reducerPath:"getCheckoutUrlApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({GetCheckoutUrl:e.mutation({query:t=>({url:`?proxy_url=${encodeURIComponent("https://webhook.latenode.com/5868/prod/5072387e-5ace-4ca7-9a25-2f952a7075af")}`,method:"POST",body:t})})})}),{useGetCheckoutUrlMutation:Nb}=Ir,ko=r.createApi({reducerPath:"recoverPasswordApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://app.useblocks.io/api/wp-json/bdpwr/v1/"}),endpoints:()=>({})}),Ar=r.createApi({reducerPath:"addUserToProjectApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/wp-json/user_to_project/v1/add_user"}),endpoints:e=>({addUserToProject:e.mutation({queryFn(t,n){return r.clientFromApi(n).userToProject.add_user_create(t,{type:h.ContentType.FormData})}})})}),{useAddUserToProjectMutation:Db}=Ar,xr=r.createApi({reducerPath:"recurrenceSubscriptionsOffApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({getCanselRecurrence:e.query({query:t=>({url:`?proxy_url=${encodeURIComponent(`https://webhook.latenode.com/5868/prod/38815aec-cb5d-4b40-8dcb-75e7453573a0?subscription_id=${t.sid}&user_id=${t.uid}`)}`})})})}),{useLazyGetCanselRecurrenceQuery:Fb,useGetCanselRecurrenceQuery:Bb}=xr,Pr=r.createApi({reducerPath:"recurrenceSubscriptionsOnApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({getRecurrence:e.query({query:t=>({url:`?proxy_url=${encodeURIComponent(`https://webhook.latenode.com/5868/prod/7ac13d46-e4af-4dea-ab21-aab55415575b?subscription_id=${t.sid}&user_id=${t.uid}`)}`})})})}),{useLazyGetRecurrenceQuery:$b,useGetRecurrenceQuery:Ub}=Pr,Ah="https://app.useblocks.io/api/v2",Rr=r.createApi({reducerPath:"authApi",baseQuery:r.fetchBaseQueryApp({baseUrl:Ah,prepareHeaders:e=>{const t=r.api.get(r.APP_COOKIES.em_token);return t&&!e.has("authorization")&&e.set("authorization",`Bearer ${t}`),e}}),endpoints:e=>({login:e.mutation({query:t=>({url:"/auth/token",method:"POST",body:t})}),register:e.mutation({query:t=>({url:"/auth/register",method:"POST",body:t})}),refreshToken:e.mutation({query:t=>({url:"/auth/token/refresh",method:"POST",body:t})}),logout:e.mutation({query:()=>({url:"/auth/token",method:"DELETE"})}),getUser:e.query({query:()=>"/auth/user",transformResponse:t=>{const n=Array.isArray(t)?t[0]:t;return r.WpUserToUser(n)}}),changePassword:e.mutation({query:t=>({url:"/auth/password/change",method:"POST",body:t})}),resetPassword:e.mutation({query:t=>({url:"/auth/password/reset",method:"POST",body:t})}),resetPasswordConfirm:e.mutation({query:t=>({url:"/auth/password/reset/confirm",method:"POST",body:t})})})}),{useLoginMutation:zb,useRegisterMutation:Gb,useRefreshTokenMutation:Wb,useLogoutMutation:Hb,useGetUserQuery:qb,useLazyGetUserQuery:Vb,useChangePasswordMutation:Kb,useResetPasswordMutation:Yb,useResetPasswordConfirmMutation:Qb}=Rr;function na(e){return{id:e.id??0,name:e.name??"",children:(e.children??[]).map(na)}}function xh(e){return(e?.folders??[]).map(na)}function Ph(e){return{items:(e?.items??[]).flatMap(t=>t.id?[{kind:t.kind??"email",id:t.id,name:t.name??"",title:t.title??"",preheader:t.preheader??"",folderId:t.folder_id??0,hasAmp:t.has_amp??!1,previewImage:t.preview_image??"",updatedAt:t.updated_at??"",imported:t.imported??!1}]:[]),total:e?.total??0}}function Co(e){const t=e.status??"pending";return{id:e.id??"",status:t,outcome:e.outcome,total:e.total??0,imported:e.imported??0,warnings:e.warnings??0,failed:e.failed??0,finished:t==="done"||t==="failed",items:(e.items??[]).map(n=>({kind:n.kind??"email",stripoId:n.stripo_id??0,name:n.name??"",status:n.status??"failed",reason:n.reason,emailId:n.email_id})),createdAt:e.created_at??"",finishedAt:e.finished_at}}function Rh(e){return{selectors:e.map(t=>({kind:t.kind,...t.ids?.length?{ids:t.ids}:{},...t.all?{all:!0}:{},...t.folderId?{folder_id:t.folderId}:{},...t.rootOnly?{root_only:!0}:{},...t.search?{search:t.search}:{}}))}}var To="StripoItems",Io="StripoFolders",jr="StripoImportJob",mn=(e,t)=>{const n=r.v2ResultOf(e);return"error"in n?{error:n.error}:{data:t(n.data)}},Or=r.createApi({reducerPath:"stripoImportApi",tagTypes:[To,Io,jr],baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({saveStripoKey:e.mutation({async queryFn({projectId:t,apiKey:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoKeyUpdate({id:String(t)},{api_key:n}),()=>{})},invalidatesTags:[To,Io]}),getStripoFolders:e.query({async queryFn({projectId:t,kind:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoFoldersList({id:String(t),kind:n}),xh)},providesTags:[Io]}),getStripoItems:e.query({async queryFn({projectId:t,kind:n,folderId:o,rootOnly:i,search:s,page:c,limit:d},u){return mn(await r.getClientV2(h.getContainer(u)).projects.stripoItemsList({id:String(t),kind:n,...o?{folder_id:o}:{},...i?{root_only:!0}:{},...s?{search:s}:{},page:c,limit:d}),Ph)},providesTags:[To]}),startStripoImport:e.mutation({async queryFn({projectId:t,selectors:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoImportsCreate({id:String(t)},Rh(n)),Co)},invalidatesTags:[jr]}),getCurrentStripoImport:e.query({async queryFn(t,n){const o=await r.getClientV2(h.getContainer(n)).projects.stripoImportsCurrentList({id:String(t)});return o.status===204?{data:null}:mn(o,Co)},providesTags:[jr]}),getStripoImport:e.query({async queryFn({projectId:t,jobId:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoImportsDetail({id:String(t),jobId:n}),Co)},providesTags:[jr]})})}),{useSaveStripoKeyMutation:Xb,useGetStripoFoldersQuery:Jb,useGetStripoItemsQuery:Zb,useLazyGetStripoItemsQuery:e0,useStartStripoImportMutation:t0,useGetCurrentStripoImportQuery:n0,useGetStripoImportQuery:r0}=Or,jh=r.createState({activeGroupsTags:[],activeProjectGroupsTags:[],groupsTemplateTotal:null,groupsTemplateProjectTotalPages:null,groupsTemplateProjectTotal:null}),Oh="projectSlice",Ao=r.createSlice({name:Oh,initialState:jh,reducers:{setActiveGroupsTags:(e,{payload:t})=>{e.activeGroupsTags=t,t.length&&(e.activeProjectGroupsTags=[])},setActiveProjectGroupsTags:(e,{payload:t})=>{e.activeProjectGroupsTags=t,t.length&&(e.activeGroupsTags=[])},resetAllTags:e=>{e.activeProjectGroupsTags=[],e.activeGroupsTags=[]}},extraReducers:e=>{e.addMatcher(r.emailsApi.endpoints.getTemplateEmails.matchFulfilled,(t,{payload:n,meta:o})=>{const{projectId:i}=o.arg.originalArgs;i?(t.groupsTemplateProjectTotal=+o.baseQueryMeta?.response.headers.get("X-WP-Total"),t.groupsTemplateProjectTotalPages=+o.baseQueryMeta?.response.headers.get("X-WP-TotalPages")):t.groupsTemplateTotal=+o.baseQueryMeta?.response.headers.get("X-WP-Total")})}}),{setActiveGroupsTags:o0,setActiveProjectGroupsTags:i0,resetAllTags:s0}=Ao.actions,Lh=r.createState({emailsTotal:0,elementsList:[],emailsTrashTotal:0,elementsTrashList:[],customFolders:{},elementsView:r.CARDS}),Mh="emailsPageSlice";function Nh(e){const t=e?.baseQueryMeta?.response;return Number(t?.headers?.get("X-WP-Total"))||0}function ra(e,t){const{emails:n,total:o,isSearch:i,page:s,tagOrFolderId:c}=t;if(t.status==="trash")!i&&o!==void 0&&(e.emailsTrashTotal=o),e.elementsTrashList=n;else if(c){const d=e.customFolders[c];e.customFolders={...e.customFolders,[c]:{list:n,page:s,total:o??d?.total??0}}}else o!==void 0&&(e.emailsTotal=o),e.elementsList=n}var xo=r.createSlice({name:Mh,initialState:Lh,reducers:{resetElementsList:e=>{e.elementsList=[]},syncElementsList:(e,{payload:t})=>{ra(e,t)},toggleElementsView:(e,t)=>{e.elementsView=t.payload},removeEmailFromList:(e,{payload:t})=>{const n=e.customFolders;t.folder!=="all"&&n[t.folder]?.list&&(n[t.folder]={...n[t.folder],list:n[t.folder].list.filter(o=>o.id!==t.emailId),total:n[t.folder].total-1},e.customFolders=n)}},extraReducers:e=>{e.addMatcher(r.emailsApi.endpoints.getEmails.matchFulfilled,(t,{meta:n,payload:o})=>{const i=n.arg.originalArgs;ra(t,{emails:o,total:Nh(n),status:i?.status,page:i?.page,isSearch:!!i?.name?.length,tagOrFolderId:i?.folderTag||i?.tags?.[0]})}),e.addMatcher(r.emailsApi.endpoints.getTemplateEmails.matchFulfilled,(t,{meta:n,payload:o})=>{const i=+n.baseQueryMeta?.response.headers.get("X-WP-Total")||0;t.elementsList=o,t.emailsTotal=i;const{projectGroup:s,projectId:c,tags:d}=n.arg.originalArgs;(s?.length&&c||d?.length||!d?.length&&!s?.length)&&(t.emailsTotal=i)}),e.addMatcher(r.emailsApi.endpoints.editEmail.matchFulfilled,(t,{payload:n})=>{t.elementsList.map(o=>o.id?.toString()===n.id?.toString()?Object.assign(o,{lock:n.lock,title:n.title,emailtags:n.emailtags}):o)})}}),{toggleElementsView:a0,resetElementsList:l0,syncElementsList:c0,removeEmailFromList:d0}=xo.actions,oa=r.combineReducers({[r.di.reducerPath]:r.di.reducer,[r.AiApi.reducerPath]:r.AiApi.reducer,[r.userSlice.name]:r.userSlice.reducer,[r.emailSlice.name]:r.emailSlice.reducer,[r.blockSlice.name]:r.blockSlice.reducer,[r.imageApi.reducerPath]:r.imageApi.reducer,[An.reducerPath]:An.reducer,[hr.reducerPath]:hr.reducer,[Ao.name]:Ao.reducer,[r.blocksApi.reducerPath]:r.blocksApi.reducer,[r.emailsApi.reducerPath]:r.emailsApi.reducer,[fr.reducerPath]:fr.reducer,[Xn.reducerPath]:Xn.reducer,[Jn.reducerPath]:Jn.reducer,[Zn.reducerPath]:Zn.reducer,[er.reducerPath]:er.reducer,[tr.reducerPath]:tr.reducer,[nr.reducerPath]:nr.reducer,[rr.reducerPath]:rr.reducer,[or.reducerPath]:or.reducer,[ir.reducerPath]:ir.reducer,[sr.reducerPath]:sr.reducer,[ar.reducerPath]:ar.reducer,[lr.reducerPath]:lr.reducer,[cr.reducerPath]:cr.reducer,[dr.reducerPath]:dr.reducer,[ur.reducerPath]:ur.reducer,[pr.reducerPath]:pr.reducer,[r.emailPageSlice.name]:r.emailPageSlice.reducer,[r.projectsApi.reducerPath]:r.projectsApi.reducer,[Pn.reducerPath]:Pn.reducer,[Qt.reducerPath]:Qt.reducer,[Rn.reducerPath]:Rn.reducer,[Er.reducerPath]:Er.reducer,[r.saveFileApi.reducerPath]:r.saveFileApi.reducer,[Sr.reducerPath]:Sr.reducer,[r.commentsApi.reducerPath]:r.commentsApi.reducer,[r.optimiseApi.reducerPath]:r.optimiseApi.reducer,[io.name]:io.reducer,[xo.name]:xo.reducer,[mr.reducerPath]:mr.reducer,[Cr.reducerPath]:Cr.reducer,[wr.reducerPath]:wr.reducer,[kr.reducerPath]:kr.reducer,[r.taxonomiesApi.reducerPath]:r.taxonomiesApi.reducer,[r.projectsPageSlice.name]:r.projectsPageSlice.reducer,[r.AiApiGenerator.reducerPath]:r.AiApiGenerator.reducer,[Tr.reducerPath]:Tr.reducer,[gr.reducerPath]:gr.reducer,[yr.reducerPath]:yr.reducer,[Gn.reducerPath]:Gn.reducer,[r.authorizationApi.reducerPath]:r.authorizationApi.reducer,[r.limitsApi.reducerPath]:r.limitsApi.reducer,[r.revisionHistorySlice.name]:r.revisionHistorySlice.reducer,[Ir.reducerPath]:Ir.reducer,[r.defaultModePanesSlice.name]:r.defaultModePanesSlice.reducer,[ko.reducerPath]:ko.reducer,[Ar.reducerPath]:Ar.reducer,[_r.reducerPath]:_r.reducer,[Pr.reducerPath]:Pr.reducer,[xr.reducerPath]:xr.reducer,[Rr.reducerPath]:Rr.reducer,[r.projectSettingsV2Api.reducerPath]:r.projectSettingsV2Api.reducer,[Or.reducerPath]:Or.reducer}),Dh=(e,t)=>t.type==="authorizationApi/resetApiState"?oa({[r.reducerPath]:e[r.reducerPath]},t):oa(e,t),ia=[r.AiApi,r.imageApi,hr,r.emailsApi,An,r.blocksApi,fr,Xn,Jn,Zn,er,tr,nr,rr,or,ir,sr,ar,lr,cr,dr,ur,pr,Sr,r.projectsApi,Pn,Qt,Rn,Er,r.commentsApi,r.optimiseApi,r.saveFileApi,mr,Cr,r.taxonomiesApi,wr,kr,r.AiApiGenerator,Tr,r.authorizationApi,r.limitsApi,gr,yr,Gn,Ir,ko,Rr,r.projectSettingsV2Api,Or,Ar,_r,Pr,xr];function Fh(e){let t={};if(e){const o=h.createIdentifier$1();h.DependencyResolver.inject(o,e),t={INJECTION:o}}const n=r.configureStore({reducer:Dh,middleware:o=>o({serializableCheck:!1}).concat(ia.map(i=>i.middleware)),preloadedState:t});return r.setupListeners(n.dispatch),n}var sa=h.createIdentifier$1("RtkApiRegistry");function Bh(e,t){e.inject(sa,new Map(t.map(n=>[n.reducerPath,n])))}function at(e,t){const n=e?.getInstance(sa)?.get(t);if(!n)throw new Error(`RTK api "${t}" is not in the container registry (provideRtkApiRegistry did not run)`);return n}function $h(e,t){let n={isCodeMode:void 0,direction:void 0};return r.provideCodeMode(e).watch(o=>{n.isCodeMode!==o.isCodeMode&&t.dispatch(r.setCodeMode(o.isCodeMode)),n.direction!==o.direction&&t.dispatch(r.switchCodeModeDirection(o.direction)),n={isCodeMode:o.isCodeMode,direction:o.direction}})}function Uh(e,t){const n=r.provideCurrentUser(e),o=r.authorizationApi.endpoints.getMe.select("");let i=n.get()?.profile;const s=()=>{const c=o(t.getState()).data;!c||c===i||(i=c,n.set({profile:c}))};return s(),{dispose:t.subscribe(s)}}var zh=h.createIdentifier$1("EmailSettingsPort");function Gh(e,t){e.inject(zh,{read:()=>r.selectEmailSettings(t.getState())??{},write:n=>{t.dispatch(r.setEmailSettings(n))},markAppearanceChanged:()=>{t.dispatch(r.markAppearanceNeedsUpdate())}})}var Wh="Invalid standaloneKey.",Hh="not implemented",u0=1,qh=h.createIdentifier$1("StandaloneMockGuard");function Po(){const e=new Error(Wh);return e.name="InvalidStandaloneKeyError",e}function Ro(e){return r.isStandaloneRuntime(h.getContainer(e))}function Vh(e){return e instanceof Error?e.name==="InvalidStandaloneKeyError"||e.message==="Invalid standaloneKey."||e.message==="not implemented":e===Hh}function aa(e){if(Ro(e))throw Po()}function Kh(e,t,n){return n instanceof Error&&n.name==="InvalidStandaloneKeyError"?n:Po()}var Yh=()=>()=>{throw Po()};function Qh(e){if(!e)throw new Error("DI container not found for standalone mock guard");e.inject(qh,1)}function Xh(e){return typeof e!="function"}var p0="[plugin-api-mock]";function la(){return!0}function Jh(e){try{if(e===null||typeof e!="object")return e;const t={};for(const n of Object.keys(e).slice(0,12)){const o=e[n];t[n]=typeof o=="string"&&o.length>120?`${o.slice(0,120)}…(${o.length})`:o}return t}catch{return"(unserializable arg)"}}function Zh(e,t){return n=>{const o=n.query,i=n.queryFn||((s,c,d,u)=>{if(!o)throw new Error("query not found EndpointDefinition");return u(o(s))});i&&(n.query=void 0,n.queryFn=async(s,c,d,u)=>{try{let p;const f=h.getContainer(c).getServices(e);for(let g=f.length-1;g>=0;g--){const y=f[g];if(p=p?await p(async m=>await y.execute(m),c):await y.execute(s),Xh(p))return{data:p,error:null}}if(p)p=await p(async(g,y=c,m=d,E=u)=>{aa(c);const k=await i(g,y,m,E);if(k.error)throw k.error;return k.data},c);else{aa(c),la();const g=await i(s,c,d,u);if(g.error)throw g.error;p=g.data}return{data:p,error:null}}catch(p){return Ro(c)&&Vh(p)?{error:Kh(t,Jh(s),p)}:(la(),{error:p})}})}}var ca=new Set;function it(e){return(t,n)=>{const o=Object.create(null),i=Object.keys(n),s=new h.Disposable;for(const c of i){const d=`api_listeners_flag_${t.reducerPath}/${c.toString()}`,u=h.createIdentifier$1(`api_listeners_${t.reducerPath}/${c.toString()}`);ca.has(d)||(o[c]=Zh(u,`${t.reducerPath}/${c.toString()}`),ca.add(d)),s.addDisposable(e.addService(u,{execute:n[c]}))}return Object.keys(o).length&&t.enhanceEndpoints({endpoints:o}),r.getDisposable(e).addDisposable(s),s}}function da(e,t){for(const n of Object.keys(t))try{t[n](e)}catch{}}function m0(e){return e}function ua(e,t){return e({body:t}).catch(()=>new Promise(n=>setTimeout(n,1e3)))}function e_(e){it(e)(at(e,"AiApi"),{sendMessage:({body:t})=>async(n,o)=>{const i=r.getEmitter(e,h.events.AI_TEXT_REQUEST_ID);if(!i.hasListeners())return ua(n,t);const s=t,c={message:s.message??s.context,locale:s.locale,entityId:s.entity_id,projectId:s.project_id!=null?String(s.project_id):void 0,subject:s.subject,preheader:s.preheader,textContent:s.textContent,context:s.context??s.connection,connection:s.connection,onProgress:(d,u)=>{r.getEmitter(e,h.events.AI_TEXT_PROGRESS_ID).fire({progress:Number.isFinite(d)?d:0,status:typeof u=="string"?u:void 0})},onStreamChunk:d=>{typeof d!="string"||!d||r.getEmitter(e,h.events.AI_TEXT_STREAM_ID).fire({partialHtml:d})},signal:o.signal};for(const d of i.getListeners([c])){const u=await d(c);if(u)return{status:200,_eventResult:!0,aiMessage:typeof u.message=="string"?u.message:"",aiHtml:typeof u.html=="string"?u.html:void 0}}return ua(n,t)},getDialog:t=>(n,o)=>Ro(o)?Promise.resolve({documents:[],totalCount:0}):n(t)})}function t_(e){const t=it(e),n=r.getEmitter(e,h.events.FILE_PROXY_EVENT_ID);t(at(e,"proxyApi"),{async getFile({url:o,tryFetch:i=!0,type:s}){return async c=>{const{requested:d}=r.getCurrentProject(e),u=(await n.fire({url:o,project:d})).filter(p=>p instanceof Blob)[0];if(u)switch(s){case"json":return JSON.parse(await u.text());case"text":return u.text();default:return u}else return c({url:o,tryFetch:i,type:s})}}})}function n_(e){it(e)(at(e,"tokenApi"),{tokenCreate(t){return n=>n(t)},tokenValidate(){return t=>t({})}})}function f0(e){return e}function r_(e){it(e)(at(e,"imageApi"),{sendAiImageRequest:function({body:t}){return async(n,o)=>{const i=r.getEmitter(e,h.events.AI_IMAGE_REQUEST_ID);if(!i.hasListeners()||t.request!=="create-image")return n({body:t});const s={prompt:t.message??"",size:t.size,entityId:t.entity_id,projectId:t.project_id!=null?String(t.project_id):void 0,onProgress:(c,d)=>{r.getEmitter(e,h.events.AI_IMAGE_PROGRESS_ID).fire({progress:Number.isFinite(c)?c:0,status:typeof d=="string"?d:void 0})},signal:o.signal};for(const c of i.getListeners([s])){const d=await c(s);if(d&&d.images?.length)return{data:{status:200,_eventResult:!0,task:{images:d.images}}}}return n({body:t})}},getAiImage(t){return n=>n(t)}})}async function pa(e,t,n,o,i){try{const s=(await e.fire({project:String(t),emailId:n})).filter(c=>c!=null);if(s.length)return s.flat()}catch{}return o(i)}function o_(e){const t=it(e),n=at(e,"blocksApi"),o=r.blocksDataSourceProvider(e),i=o.byForeignKey("project"),s=r.blockRevisionsDataSourceProvider(e);s.byForeignKey("parent");const{dispatch:c}=r.getStore(e),d=r.getDisposable(e);d.addDisposable(o.onChange(()=>c(n.util.invalidateTags(["Blocks"])))),d.addDisposable(o.onSave(({prev:f,patch:g,value:y})=>{const m=f?{...f,...g}:g;let E=r.mergeEntityPreservingMeta(f,g,y);return m&&E.html===m.html&&E.title===m.title&&(E={...E,renderGuid:m.renderGuid}),E},Number.MIN_VALUE));const u=r.getEmitter(e,r.READ_COMMON_BLOCKS_EVENT_ID),p=r.getEmitter(e,r.READ_TEMPLATE_BLOCKS_EVENT_ID);t(n,{async getBlocks(f){const g={};f.name&&(g.title=f.name),f.type&&(g.type=f.type);const y=f.projectId??await r.getBlocksProject(e);return await i.get(y,{filter:g,page:f.page,pageSize:f.pageSize,order:f.order,orderBy:f.orderby}).then(({data:m})=>m)},getBlocksSchema(){return f=>f(void 0)},getParentEmailBlocks(f){return async g=>{const y=r.getCurrentProject(e).requested||"";return pa(p,y,f.emailId||"",g,f)}},getTemplateBlocks(f){return async g=>{const y=r.getCurrentProject(e).requested||"";return pa(u,y,f.emailId||"",g,f)}},async getBlock(f){const g=r.getCurrentProject(e).card?.id;if(g!==void 0)return i.first(Number(g),{filter:{id:f}})},addBlock(f){return async g=>{const y=await o.create(f);return r.getAppConfig(e).preventSendDataToEM||g(y).catch(m=>{}),y}},editBlock({blockId:f,...g}){return o.update(f,g)},deleteBlock(f){return o.remove(typeof f=="object"?f.id:f)},addTag(f){return f},getDeletableTag([f,g]){return[]},autoSaveBlock({blockId:f,body:g}){return s.create({...g,parent:f})}})}function i_(e){const{emails:t,emailRevisions:n}=r.provideEmailDocuments(e),{dispatch:o}=r.getStore(e),i=r.getDisposable(e),s=it(e),c=at(e,"emailsApi");i.addDisposable(t.onChange(async()=>{o(c.util.invalidateTags(["Email"]))})),s(c,{getEmails:d=>[],getTemplateEmails:d=>[],async addEmail({source:d,...u}){const p=await t.create(u,{source:d});return p.renderGuid||(p.renderGuid=h.generateUUID()),p},editEmail(d){return async u=>{const{emailId:p,source:f,...g}=d;return r.isRevisionServiceEnabled(e)&&await u(d),t.update(p,g,{source:f})}},deleteEmail(d){return t.remove(typeof d=="object"?d.id:d)},addTag(){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},getDeletableTag([d,u]){return[]},autoSaveEmail({emailId:d,body:u}){return async p=>{r.isRevisionServiceEnabled(e)&&await p({emailId:d,body:u});const f=await n.create({...u,parent:d,modified:new Date().toString()});return f&&!f.html&&u.html?{...f,html:u.html}:f}}})}var s_="tmp",g0=h.createIdentifier$1();function a_(e){const t=it(e);if(!e.getInstance(h.DISPOSABLE_ID))throw new Error("Something was wrong");const n=r.getEmitter(e,h.events.UPLOAD_EVENT_ID),o=r.getEmitter(e,h.events.ON_SEND_TESTEMAIL_ID),i=r.getEmitter(e,h.events.ON_SEND_LIVEPREVIEW_ID);t(at(e,"saveFileApi"),{uploadImage(s){return async c=>{const{requested:d}=r.getCurrentProject(e),u=async()=>c({...s,user_id:String((await e.getInstanceAsync(h.APP_ID)).app_id)});if(s.folder===s_)return u();const p=await r.fireUploadImageEvent(n,{file:s.file,project:d});if(p.url)return[{file_url:p.url,project:d}];if(!r.shouldFallbackToBuiltInUpload(p,{isStandalone:r.isStandaloneRuntime(e)}))throw r.toUploadImageError(p);return u()}},sendTestEmail(s){return async c=>{const{requested:d}=r.getCurrentProject(e);(await o.fire({project:d,email_id:s.email_id,subject:s.subject,email:s.email,html:s.html,from_name:s.from_name})).some(u=>u===!1)&&await c({...s,user_id:String((await e.getInstanceAsync(h.APP_ID)).app_id)})}},async sendLivePreview(s){const{requested:c}=r.getCurrentProject(e);(await i.fire({project:c,id:s.email,subject:s.subject,html:s.content})).some(d=>d===!1)},sendShortLink(s){return c=>c(s)}})}function l_(e){it(e)(at(e,"emailRawApi"),{getEmailRaw({emailId:t,secret_hash:n}){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function Kt(e,t){for(var n=e<0?"-":"",o=Math.abs(e).toString();o.length<t;)o="0"+o;return n+o}function c_(e,t){var n,o;r.requiredArgs(1,arguments);var i=Ll(e);if(isNaN(i.getTime()))throw new RangeError("Invalid time value");var s=String((n=t?.format)!==null&&n!==void 0?n:"extended"),c=String((o=t?.representation)!==null&&o!==void 0?o:"complete");if(s!=="extended"&&s!=="basic")throw new RangeError("format must be 'extended' or 'basic'");if(c!=="date"&&c!=="time"&&c!=="complete")throw new RangeError("representation must be 'date', 'time', or 'complete'");var d="",u="",p=s==="extended"?"-":"",f=s==="extended"?":":"";if(c!=="time"){var g=Kt(i.getDate(),2),y=Kt(i.getMonth()+1,2),m=Kt(i.getFullYear(),4);d="".concat(m).concat(p).concat(y).concat(p).concat(g)}if(c!=="date"){var E=i.getTimezoneOffset();if(E!==0){var k=Math.abs(E),w=Kt(Math.floor(k/60),2),v=Kt(k%60,2),x=E<0?"+":"-";u="".concat(x).concat(w,":").concat(v)}else u="Z";var P=Kt(i.getHours(),2),K=Kt(i.getMinutes(),2),J=Kt(i.getSeconds(),2),N=d===""?"":"T",L=[P,K,J].join(f);d="".concat(d).concat(N).concat(L).concat(u)}return d}function d_(e){const t=it(e),n=at(e,"commentsApi"),o=r.commentsDataSourceProvider(e),i=o.byForeignKey("post"),{dispatch:s}=r.getStore(e);r.getDisposable(e).addDisposable(o.onChange(()=>s(n.util.invalidateTags(["Comments"])))),t(n,{getComments(c){return i.get(c).then(({data:d})=>d)},addComment({subjectId:c,author:d,parent:u,content:p,author_name:f,author_email:g,targetId:y}){const m={post:c,author:d,author_name:f,author_email:g,content:p,parent:u,target_id:y,date:c_(new Date),author_avatar_urls:{}};return o.create(m)},deleteComment(c){return o.remove(c)},editComment({commentId:c,...d}){return o.update(c,d)},deleteTarget(c){return o.update(c,{target_id:""})}})}function jo(e){return{id:String(e),name:"",myRole:"",members:[],invites:[],emailsCount:0,blocksCount:0,title:"",group:[],folder:[],blockfolder:[]}}function ma(e,t){return{project:Number(e),app_id:t?.app_id||0,app_config:t?.app_config||{},user:t?.user}}function u_(e,t){const n=jo(String(t)),o=r.getCurrentProject(e).card;return o&&String(o.id)===String(t)?Promise.resolve({...n,...o,id:String(t)}):Promise.resolve({...n,id:String(t)})}function p_(e){let t,n;const o=i=>((t!==i||!n)&&(t=i,n=u_(e,i)),n);it(e)(at(e,"projectsApi"),{getProjects(i={page:1}){return[]},getProject(i){return async s=>r.isStandaloneRuntime(e)?s(i):{...await o(i),id:String(i)}},addProject(i){throw new Error},async editProject({projectId:i,...s}){const c={...await o(i),...s,id:String(i)};return t=i,n=Promise.resolve(c),c},deleteProject(i){throw new Error},mutateProjectMembers(){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},addProjectMember(){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},getFrequentProjects(){return[]}})}function m_(e){let t={id:"0",username:"",email:"",password:"",code_editor:{},theme:"light",locale:r.getCurrentUser(e).profile?.locale,counters:{},avatar_urls:{},autosaves:!0};it(e)(at(e,"authorizationApi"),{getSchema:()=>n=>n({}),getMe:()=>t,editMe:n=>t={...t,...n},getSubscriptions:()=>[]})}function f_(e){it(e)(at(e,"notificationsApi"),{getNotifications(t){return[]},notificationShown({id:t,datetime:n}){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function g_(e){it(e)(at(e,"addUserToProjectApi"),{addUserToProject:()=>{}})}function h_(e){r.injectEmailTermsResolver(e,{resolve:async()=>{}}),it(e)(at(e,"taxonomiesApi"),{getTerms:()=>[],getStandardGroups:()=>[],addTerm:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},editTerm:t=>({id:t.id,name:t.name,parent:0,count:0}),deleteTerm:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function __(e){it(e)(at(e,"projectSettingsV2Api"),{getProjectIntegrations:()=>({}),getProjectWebhook:()=>"",getProjectStorage:()=>({}),getProjectTestRecipients:()=>[],getIntegrationCredentials:()=>({}),putProjectIntegration:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},deleteProjectIntegration:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},putProjectWebhook:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},putProjectSettings:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},putProjectTestRecipients:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function y_(e){it(e)(at(e,"stripoImportApi"),{getStripoFolders:()=>[],getStripoItems:()=>({items:[],total:0}),getCurrentStripoImport:()=>null,getStripoImport:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},saveStripoKey:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},startStripoImport:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}var fa={addUserToProjectApiMock:g_,AiApiMock:e_,authorizationApiMock:m_,blocksApiMock:o_,commentsApiMock:d_,emailsApiMock:i_,emailRawApiMock:l_,imageApiMock:r_,notificationsApiMock:f_,projectsApiMock:p_,projectSettingsV2ApiMock:__,proxyApiMock:t_,saveFileApiMock:a_,stripoImportApiMock:y_,taxonomiesApiMock:h_,tokenApiMock:n_},Oo=r.createApi({reducerPath:"tokenApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/wp-json/jwt-auth/v1/"}),endpoints:e=>({tokenCreate:e.mutation({queryFn(t,n){return r.clientFromApi(n).jwtAuth.token_create({body:t,type:h.ContentType.Json})}}),tokenValidate:e.mutation({queryFn(t,n){return r.clientFromApi(n).jwtAuth.token_validate_create({type:h.ContentType.Json})}})})}),{useTokenCreateMutation:h0,useTokenValidateMutation:_0}=Oo;function Lo(){const e=new Map;for(const t of ia)e.set(t.reducerPath,t);return e.set(Oo.reducerPath,Oo),[...e.values()]}function v_(e,t){const n=Object.keys(t.endpoints);n.length&&e(t,Object.fromEntries(n.map(o=>[o,Yh])))}function b_(e){Qh(e);const t=it(e);for(const n of Lo())v_(t,n)}function E_(e){if(!e)return;const t=h.decodeJwt(e)?.data,n=t?.data?.scope??t?.scope;return(Array.isArray(n)?n.flatMap(o=>typeof o=="string"?o.split(/\s+/):[]):typeof n=="string"?n.split(/\s+/):[]).find(o=>/^project_\d+$/.test(o))?.replace(/^project_/,"")||void 0}var S_={AiApi:new Set(["sendMessage","getDialog"]),imageApi:new Set(["sendAiImageRequest","getAiImage","getAiImageSSE"])};function w_(e){return r.getAppConfig(h.getContainer(e))}function k_(e){return e?.backendProxy!==void 0&&e?.backendProxyPolicy?.proxyAi===!0}function C_(e){return k_(w_(e))}function T_(e,t,n,o){return S_[t]?.has(n)?i=>C_(e)?s=>s(i):o(i):o}function I_(e){const t=it(e);return((n,o)=>{if(!n||typeof n.reducerPath!="string")return new h.Disposable;const i=Object.fromEntries(Object.entries(o??{}).map(([s,c])=>[s,typeof c=="function"?T_(e,n.reducerPath,s,c):c]));return t(n,i)})}function A_(e){const t=`blocks_${h.generateUUID().replaceAll("-","")}`,n=document.createElement("script");return n.type="text/javascript",n.text=`window.${t}(function(module, exports, require) { ${e}; })`,new Promise((o,i)=>{window[t]=function(s){const c={exports:{}},d=()=>{};s(c,c.exports,d),o(c.exports)},document.head.appendChild(n)}).finally(()=>{n.remove(),delete window[t]})}async function ga(e){const t=h.getContainer(e),n=t?.getInstance(h.STANDALONE_PROJECT_ID),o=n?void 0:await t?.getInstanceAsync(h.APP_ID).catch(()=>{}),i=n||(o?.project!==void 0?String(o.project):void 0);i&&t&&r.setCurrentProjectCard(t,jo(i))}async function x_(e,t){try{const n=function(d){const u=e.getInstance(h.STANDALONE_PROJECT_ID),p=u?ma(u,d):d;e.injectFactory(h.APP_ID,async()=>p)},o=I_(e),i=await r.readZipFromBase64(t),s=i.key&&r.zipEntryToText(i.key);if(typeof s!="string")return;const c=await A_(s);if(typeof c!="object"||c===null||typeof c.execute!="function")return;c.execute(n,o,Lo())}catch{}}async function ha(e,t){b_(h.getContainer(e)),await x_(h.getContainer(e),t),da(h.getContainer(e),fa)}var P_=zn(async e=>{const t=Fh(e);e.inject(h.STORE_ID,t),Bh(e,Lo()),Gh(e,t),r.getDisposable(e).addDisposable(Uh(e,t)),r.getDisposable(e).addDisposable($h(e,t));const n=h.getContainer(t);n&&(e.inject(h.MESSAGE_SERVICE_ID,r.getMessageService(n)),e.inject(r.CURRENT_PROJECT_ID,r.provideCurrentProject(n)));const o=e.getInstance(h.SECURITY_MODULE_ID);return o?(await ha(t,o),await ga(t)):da(h.getContainer(t),fa),{instance:{}}}),_a=["historyEnabled","commentsEnabled","aiAssistentEnabled","livePreviewEnabled","sendTestEnabled","sharePreviewEnabled","webversionEnabled","optimizeSpamAssassinEnabled","exportWebHookEnabled","aiLayoutConverterEnabled","elementAIimageEnabled","elementAItextEnabled","revisionService"];function R_(e){const t={...e};for(const n of _a)t[n]=!1;return t}function j_(e){const t={...e};for(const n of _a)n in t&&typeof t[n]=="boolean"&&(t[n]=!1);return t}function O_(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,o]of Object.entries(e))!o||typeof o!="object"||Array.isArray(o)||(t[n]=j_(o));return Object.keys(t).length>0?t:void 0}function Mo(e){const t=R_(e),n=O_(e.advancedConfigs),o={...t};return n?o.advancedConfigs=n:delete o.advancedConfigs,o}var y0=1,L_=2592e6;function ya(){return"useblocks".trim()||void 0}function M_(e){return{schemaVersion:1,savedAt:Date.now(),project:e.project,app_id:e.app_id,app_config:Mo(ba(e.app_config))}}function va(e){return{...e,app_config:ba(e.app_config)}}function ba(e){if(!e||typeof e!="object"||Array.isArray(e))return{};try{if(typeof structuredClone=="function")return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return{}}}async function N_(e){const t=ya();t&&await G_(t,M_(e))}async function D_(e=Date.now()){const t=ya();if(t)return W_(t,e)}function F_(e,t=Date.now()){return e.savedAt>t?!1:t-e.savedAt<=L_}function Ea(e){if(!e||typeof e!="object")return!1;const t=e,n=typeof t.project=="number"&&Number.isFinite(t.project)||typeof t.project=="string"&&t.project.trim()!=="";return t.schemaVersion===1&&typeof t.savedAt=="number"&&Number.isFinite(t.savedAt)&&n&&typeof t.app_id=="number"&&Number.isFinite(t.app_id)&&t.app_config!=null&&typeof t.app_config=="object"&&!Array.isArray(t.app_config)}var jt="snapshots",B_=1;function $_(){return`${"useblocks".trim()||"plugin"}-plugin-deferred-config`}function Lr(){return new Promise((e,t)=>{if(typeof indexedDB>"u"){t(new Error("indexedDB is not available"));return}const n=indexedDB.open($_(),B_);n.onerror=()=>t(n.error||new Error("indexedDB open failed")),n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(jt)||o.createObjectStore(jt)},n.onsuccess=()=>e(n.result)})}function U_(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error||new Error("indexedDB request failed"))})}function z_(){return{async get(e){const t=await Lr();try{const n=await U_(t.transaction(jt,"readonly").objectStore(jt).get(e));return n===void 0?void 0:n}finally{t.close()}},async put(e,t){const n=await Lr();try{const o=n.transaction(jt,"readwrite");o.objectStore(jt).put(t,e),await new Promise((i,s)=>{o.oncomplete=()=>i(),o.onerror=()=>s(o.error||new Error("indexedDB write failed")),o.onabort=()=>s(o.error||new Error("indexedDB write aborted"))})}finally{n.close()}},async delete(e){const t=await Lr();try{const n=t.transaction(jt,"readwrite");n.objectStore(jt).delete(e),await new Promise((o,i)=>{n.oncomplete=()=>o(),n.onerror=()=>i(n.error||new Error("indexedDB delete failed")),n.onabort=()=>i(n.error||new Error("indexedDB delete aborted"))})}finally{t.close()}},async clear(){const e=await Lr();try{const t=e.transaction(jt,"readwrite");t.objectStore(jt).clear(),await new Promise((n,o)=>{t.oncomplete=()=>n(),t.onerror=()=>o(t.error||new Error("indexedDB clear failed")),t.onabort=()=>o(t.error||new Error("indexedDB clear aborted"))})}finally{e.close()}}}}var Sa,No;function Do(){return Sa||(No||(No=z_()),No)}function wa(e){Do().delete(e).catch(()=>{})}async function G_(e,t){if(Ea(t))try{await Do().put(e,va(t))}catch{}}async function W_(e,t=Date.now()){try{const n=await Do().get(e);if(n===void 0)return;if(!Ea(n)){wa(e);return}if(!F_(n,t)){wa(e);return}return va(n)}catch{return}}function H_(e,t){if(e.getInstance(h.STANDALONE_FILE_PROXY_REGISTERED_ID))return;e.inject(h.STANDALONE_FILE_PROXY_REGISTERED_ID,!0);const n=h.getEvent(e,h.events.FILE_PROXY_EVENT_ID);t.addDisposable(n(async({url:o})=>(await fetch(o)).blob(),Number.MIN_VALUE))}function ka(e){try{return E_(e)||void 0}catch{return}}async function q_(e,t,n){if(!e)return;let o;try{const i=await e(t,n,void 0);o=String(i||"").trim()}catch{return}if(o)return{token:o,serverProjectId:ka(o)}}function V_(e){if(e==null)return;const t=String(e).trim();return/^\d+$/.test(t)?t:void 0}function K_(e){const t=String(e.getInstance(h.JWT_TOKEN_ID)||"").trim();if(t)return ka(t)}function Ca(e,t,n){e.inject(h.APP_ID,void 0),e.inject(h.APP_ID,Promise.resolve(ma(t,n)))}function Y_(e){return{app_id:e.app_id,app_config:Mo(e.app_config)}}async function Ta(){const e=await D_();return e?Y_(e):{app_config:Mo({})}}function Q_(e,t){e.getInstance(h.STANDALONE_ACTIVATED_ID)||(e.inject(h.SECURITY_MODULE_ID,void 0),e.inject(h.STANDALONE_BOOTSTRAP_TOKEN_ID,void 0),e.inject(h.STANDALONE_PROJECT_ID,void 0),t&&e.inject(h.APP_ID,void 0),e.inject(h.STANDALONE_FILE_PROXY_REGISTERED_ID,void 0))}async function Ia(e){const{container:t,store:n,standaloneKey:o,project:i,reason:s,getAuthToken:c,user:d}=e,u=e.disposable||t.getInstance(h.DISPOSABLE_ID);if(t.getInstance(h.STANDALONE_ACTIVATED_ID))return;const p=await q_(c,d,i),f=V_(i),g=p?.serverProjectId??K_(t)??(p?void 0:f);t.inject(h.SECURITY_MODULE_ID,o);let y=!1;try{if(p&&(t.inject(h.STANDALONE_BOOTSTRAP_TOKEN_ID,Promise.resolve(p.token)),c&&h.recreateTokenProvider(t,c,d,i)),g){const m=await Ta();t.inject(h.STANDALONE_PROJECT_ID,g),Ca(t,g,m),y=!0,r.setCurrentProjectCard(t,jo(g))}if(await ha(n,o),y=!0,!g){await ga(n);const m=t.getInstance(h.STANDALONE_PROJECT_ID);if(m)Ca(t,m,await Ta()),y=!0;else if(t.getInstance(h.APP_ID)!==void 0)try{(await t.getInstanceAsync(h.APP_ID))?.project==null}catch{}}u&&H_(t,u),t.inject(h.STANDALONE_ACTIVATED_ID,!0)}catch(m){throw Q_(t,y),m}}async function X_(e,t,n,o){const i=o?.attemptTimeout??h.isFailoverEnabled(n),s=h.isFailoverEnabled(n)?h.getOrderedOriginCandidates(n):h.getOriginChain(n).length>0?[h.getActiveBaseUrl(n)]:[];if(s.length===0)throw new Error("[apiOriginFailover] no API base URL configured");const c=e.startsWith("/")?e:`/${e}`;let d,u;for(let p=0;p<s.length;p++){const f=s[p],g=p===s.length-1,y=i?h.beginFailoverAttempt(t.signal):void 0;try{const m=await fetch(`${f}${c}`,{...t,...y?{signal:y.signal}:{}});if(!m.ok&&h.shouldFailoverResponse(m.status)){if(d=m,!g){h.reportOriginFailure(f,n);continue}break}return m.ok&&h.reportOriginSuccess(f,n),m}catch(m){const E=y?.timeoutError();if(!E&&!h.shouldFailoverError(m))throw m;u=E||m,g||h.reportOriginFailure(f,n)}finally{y?.done()}}if(h.isFailoverEnabled(n)&&h.abandonStickyOrigin(),d)return d;throw u instanceof Error?u:new Error("[apiOriginFailover] fetch chain failed")}function J_(e,t){const n=String(t.baseUrl||"").trim();if(n)return h.resolveExplicitApiBaseUrl(n);const o=e.getInstance(h.REST_CLIENT_FACTORY_ID),i=String(o?.getOptions()?.baseUrl||"").trim();return h.resolveExplicitApiBaseUrl(i||void 0)}async function Z_(e,t){if(t.getAuthToken)try{const n=await t.getAuthToken(t.user,t.project,void 0);if(String(n||"").trim())return!0}catch{if(!t.jwtAuth)return!1}if(t.jwtAuth)try{if(String(e.getInstance(h.JWT_TOKEN_ID)||"").trim())return!0;const n=J_(e,t);if(!n)return!1;const o=await X_("/jwt-auth/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.jwtAuth)},n,{attemptTimeout:!0});if(!o.ok)return!1;const i=await o.json();return i.token?(e.inject(h.JWT_ERROR_ID,void 0),e.inject(h.JWT_TOKEN_ID,i.token),!0):!1}catch{return!1}return!1}async function ey(e){try{if(e.getInstance(h.APP_ID)===void 0)return!1;const t=await ny(e.getInstanceAsync(h.APP_ID));return t!=null&&t.project!=null?t:!1}catch{return!1}}function ty(){return h.getFailoverAttemptTimeoutMs()*Math.max(1,h.getOriginChain().length)}function ny(e){const t=ty();return new Promise((n,o)=>{const i=setTimeout(()=>{n(void 0)},t);e.then(s=>{clearTimeout(i),n(s)},s=>{clearTimeout(i),o(s)})})}function Aa(e){return String(e.standaloneKey||"").trim()||void 0}function ry(e){return e.standaloneOnAuthFailure===!0?!0:e.config?.standaloneOnAuthFailure===!0}function oy(e){return ry(e)?!!Aa(e):!1}var iy=zn(async e=>{const t=e.getInstance(h.DISPOSABLE_ID),n=()=>e.getInstanceAsync(h.STORE_ID);return{async setOptions(o){if(!oy(o)){e.getInstance(h.STANDALONE_ACTIVATED_ID);return}const i=Aa(o);if(!i||e.getInstance(h.STANDALONE_ACTIVATED_ID))return;const s=await n(),c=!!(o.getAuthToken||o.jwtAuth),d=c?await Z_(e,o):!0;if(c&&!d){await Ia({container:e,store:s,standaloneKey:i,project:o.project,getAuthToken:o.getAuthToken,user:o.user,disposable:t,reason:"auth pipeline failed"});return}const u=await ey(e);if(u){await N_(u).catch(()=>{});return}await Ia({container:e,store:s,standaloneKey:i,project:o.project,getAuthToken:o.getAuthToken,user:o.user,disposable:t,reason:"app_init failed"})}}}),sy=h.defineMixin(e=>{let t;const n=r.getDisposable(e),o=h.getEvent(e,h.events.ON_DOCUMENT_SESSION_CHANGE);n.addDisposable(o(({history:s})=>{t=s}));const i=()=>t?Ni(t):void 0;return{instance:{undoRedoService:{undo:()=>i()?.undo(),redo:()=>i()?.redo(),clear:()=>i()?.clear(),getPast:s=>i()?.getPast(s)??[],getFuture:s=>i()?.getFuture(s)??[],canUndo:()=>i()?.canUndo()??!1,canRedo:()=>i()?.canRedo()??!1,createSnapshot:()=>i()?.createSnapshot(),restoreSnapshot:s=>i()?.restoreSnapshot(s)}}}});function ay(e){return{font_size:e.fontSize,font_family:e.fontFamily,tab_size:e.tabSize,word_wrap:e.wordWrap,minimap:e.minimap,insert_spaces:e.insertSpaces}}function ly(e){return{fontSize:e.fontSize,fontFamily:e.fontFamily,tabSize:e.tabSize,wordWrap:e.wordWrap!=="off",minimap:e.minimap?.enabled,insertSpaces:e.insertSpaces}}async function xa(e){const t=r.getCurrentUser(e).profile;if(t)return t;const n=e.getInstance(h.STORE_ID);if(n)return(await n.dispatch(r.authorizationApi.endpoints.getMe.initiate("",{forceRefetch:!0}))).data}function cy(e){const t=r.resolveTemplateDirectivesConfig(e);if(!(Object.keys(t.output).length>0||Object.keys(t.editor).length>0))return fs();const n=new Set(Object.keys(t.output).filter(i=>t.output[i]==="html-comment")),o=new Set(Object.keys(t.output));return{isConfigured:()=>!0,toEditorForm:i=>r.mapper.normalizeToPolicy(i,t.editor),toOutputForm:i=>r.mapper.normalizeToPolicy(i,t.output),keepWrappedOnOutput:n,editorPolicy:t.editor,warnAboutUnconfiguredInput:ms(o)}}function Pa(e){const t=r.getCodeMode(e);return{...Mr(e),editor:ly(r.getEditorOptions(e)),codeModeDirection:t.isCodeMode?t.direction:"none"}}function Mr(e){return e.getInstance(h.CONFIG_SOURCE_ID)?.get()??{}}function Fo(e){return e.getInstance(h.CONFIG_SOURCE_ID)?.layers()??{base:{},profile:{},serverSide:{},user:{},local:{},advancedConfigs:{}}}var dy=bo(e=>{const t=r.getDisposable(e),n=Ct(r.getEvent(e,h.events.ON_LIMIT_ID)),o=t.addDisposable(new kt(n)),i=Ct(r.getEvent(e,h.events.READ_LOCALE)),s=t.addDisposable(new kt(i)),c=Ct(r.getEvent(e,h.events.ON_TRANSLATE_ID)),d=t.addDisposable(new kt(c)),u=r.getEmitter(e,h.CONFIG_CHANGED_EVENT_ID),p=async()=>{try{return e.getInstance(h.APP_ID)===void 0?{}:(await e.getInstanceAsync(h.APP_ID))?.app_config||{}}catch{return{}}},f=Bs(),g=Bs();let y,m=!1,E;const k=async()=>{const A=Pa(e);if(!m){E=h.deepClone(A),m=!0;return}E!==void 0&&h.deepEqual(E,A)||(E=h.deepClone(A),await u.fire(A))},w=A=>{if(typeof A=="number")return String(A);if(typeof A=="string")return A},v=A=>{if(A!==void 0){const O=r.provideCurrentProject(e);O.set({...O.get(),requested:String(A)})}},x=async(A,O)=>{if(!A){const Z=await xa(e);return y=w(Z?.id),{didReset:!1}}const z=await xa(e),B=A.id!==void 0?w(A.id):w(z?.id),U=y!==void 0?String(y):void 0,de=B!==void 0?String(B):void 0,me=U!==void 0&&de!==void 0&&U!==de,H={...z,...r.filterUndefined(A),id:B};if(A.id===void 0&&!z?.id&&delete H.id,r.provideCurrentUser(e).set({profile:H}),me&&O){const Z=e.getInstance(h.INSTANCE_ID);if(Z?.reset)return await Z.reset(O),{didReset:!0}}return y=de,{didReset:!1}},P=A=>{const O=e.getInstance(h.CONFIG_SOURCE_ID);O?.setAdvancedConfigs({...A.advancedConfigs,...A.user?.advancedConfigs}),O?.replace(A.user,"user"),O?.replace(A.serverSide,"server")},K=async()=>{await e.getInstance(h.CONFIG_SOURCE_ID)?.ready(),r.getRevisionServiceFlag(e).set(Mr(e).revisionService===!0);const{codeModeDirection:A,editor:O}=Mr(e);O&&r.applyEditorOptions(e,ay(O)),A!==void 0&&(A==="none"?r.setCodeMode$1(e,!1):(r.setCodeMode$1(e,!0),r.setCodeModeDirection(e,A)))},J=async A=>{P(A),await K()};let N;const L=f.decorate(async({config:A={},project:O,user:z,advancedConfigs:B},U)=>{e.getInstance(h.CONFIG_SOURCE_ID)?.replace(await p(),"server"),await K(),e.inject(h.TEMPLATE_DIRECTIVES_ID,cy(Mr(e).templateDirectives)),v(O),U&&"commonStyles"in U&&r.setDefaultCommonStyles(e,U.commonStyles===void 0?void 0:U.commonStyles);const{didReset:de}=await x(z,U)});return{setOptions:g.decorate(async A=>{const{config:O={},project:z,user:B,advancedConfigs:U,handleReadLocale:de,handleLimitUsage:me,handleTranslate:H,storageProvider:Z}=A;e.inject(h.STORAGE_PROVIDER_ID,Z),s.setListener(de),o.setListener(me),d.setListener(H),await L({config:O,project:z,user:B,advancedConfigs:U},A).catch(De=>{}),await k(),N&&N.dispose(),N=new h.Disposable}),instance:{setConfig:g.decorate(async A=>{const O=A,{commonStyles:z,...B}=O;"commonStyles"in O&&r.setDefaultCommonStyles(e,z===void 0?void 0:z),await J({advancedConfigs:Fo(e).advancedConfigs,serverSide:await p(),user:B}),await k()}),getConfig:()=>Pa(e),updateConfig:g.decorate(async A=>{const O=A,{commonStyles:z,...B}=O;"commonStyles"in O&&r.setDefaultCommonStyles(e,z===void 0?void 0:z),await J({advancedConfigs:Fo(e).advancedConfigs,serverSide:await p(),user:{...Fo(e).user,...B}}),await k()}),handleReadLocale:i,handleLimitUsage:n,handleTranslate:c}}}),Nr;function Bo(){return Nr===void 0&&(Nr=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/4916b3a1.js")),void 0,{}.url).catch(e=>{throw Nr=void 0,e})),Nr}var Ra;function uy(){return Ra??=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/e47dcbb0.js")).then(e=>zt.__toESM(e.require_core())),void 0,{}.url),Ra}function py(e){const t=[0],n=[];let o=0;for(;o<e.length;){const i=e.charCodeAt(o);i===10||i===13?(n.push(o-t[t.length-1]),o+=i===13&&e.charCodeAt(o+1)===10?2:1,t.push(o)):o+=1}return n.push(e.length-t[t.length-1]),{starts:t,lengths:n}}function ja({starts:e,lengths:t},n,o){const i=Math.min(Math.max(n,1),e.length)-1;return e[i]+Math.min(Math.max(o,1),t[i]+1)-1}var my={error:8,warning:4,info:2};function fy(e,t){const n=e.evidence!==""?e.col+e.evidence.length:t.lengths[e.line-1]??e.col+1;return{severity:my[e.type]??8,message:e.message,startLineNumber:e.line,startColumn:e.col,endLineNumber:e.line,endColumn:n,startOffset:ja(t,e.line,e.col),endOffset:ja(t,e.line,n)}}async function gy(e){const{HTMLHint:t}=await uy(),n=py(e);return t.verify(e,r.EMAIL_CODE_RULESET).map(o=>fy(o,n))}var hy=class extends h.Disposable{_container;_dataSources;_currentEmail;_blockMetaWrites=Promise.resolve();constructor(e){super(),this._container=e,this._dataSources=r.getDataSources(e),this.addDisposable(h.getEvent(e,h.events.ON_EMAIL_CHANGED_ID)(t=>{this._currentEmail=t}))}async getBlocks(){const e=await this._readProjectBlocks();return await this._blockMetaWrites,(await this._dataSources.blocks.cache.values()).filter(t=>t.project===e).map(t=>Og(t,this._container))}async _readProjectBlocks(){const e=await r.getBlocksProject(this._container);return await this._dataSources.blocks.byForeignKey("project").get(e),e}async getComments(){const{cache:e}=this._dataSources.comments,t=await this.getEmailSnapshot();return(await e.values()).filter(n=>n.post===t.id).map(n=>Lg(n,this._container))}async getEmailRevisions(){const{cache:e}=this._dataSources.emailRevisions,t=await this.getEmailSnapshot();return(await e.values()).filter(n=>n.parent===t.id).map(n=>Mg(n,this._container))}async getEmailSnapshot(){return Up(r.getOpenEmail(this._container,this._currentEmail),this._container)}async getEmail(e=!0){return this.compile(e)}async compileEmail(e=!0){return this.compile(e)}async compile(e){const{compileEmail:t}=await Bo();return t(await this.getEmailSnapshot(),e,on(this._container).keepWrappedOnOutput)}setEmailMeta(e){const t=r.getOpenDocument(this._container);if(!t)return;const n=t.get().attributes.meta;r.writeEmailAttributes(t,{meta:r.applyMetaPatch({meta:n},e).meta});const o=t.get().serverId;o!=null&&this._dataSources.emails.cache.addOrUpdate(o,i=>i&&r.applyMetaPatch(i,e))}setBlockMeta(e,t){const n=async()=>{await this._readProjectBlocks();const{cache:o}=this._dataSources.blocks;await o.getIfPresent(e)&&await o.addOrUpdate(e,i=>i&&r.applyMetaPatch(i,t))};this._blockMetaWrites=this._blockMetaWrites.then(n).catch(()=>{})}getCodeErrors(){const e=r.getCodeErrors(this._container);return e.length>0?e:void 0}validateCode(){return Promise.resolve(gy(r.getOpenEmail(this._container,this._currentEmail).html??""))}};function Oa(){Bo().catch(()=>{})}function _y(e){const t=r.provideHeadlessMode(e).watch(n=>{n&&Oa()});e.getInstance(h.DISPOSABLE_ID)?.addDisposable(t),Ht(e).whenVisible(()=>{Xt(Oa)})}var yy=h.createIdentifier$1("EmailOperationsController");function La(e){return e.getOrCreateInstance(yy,()=>{const t=new hy(e);return e.getInstance(h.DISPOSABLE_ID)?.addDisposable(t),t})}function vy(e){La(e),_y(e)}function by(e){const t=La(e);return{getEmailSnapshot:()=>t.getEmailSnapshot(),getEmail:()=>t.getEmail(),async compileEmail(n,o=!0){if(!n)return t.compileEmail(o);const{compileEmail:i}=await Bo();return i(n,o,on(e).keepWrappedOnOutput)},validateCode:()=>t.validateCode(),getCodeErrors:()=>t.getCodeErrors(),getBlocks:()=>t.getBlocks(),getComments:()=>t.getComments(),getEmailRevisions:()=>t.getEmailRevisions(),setEmailMeta:n=>t.setEmailMeta(n),setBlockMeta:(n,o)=>t.setBlockMeta(n,o)}}var Ey=h.defineMixin(e=>{const t=e.getInstance(h.DISPOSABLE_ID),n=h.getEvent(e,h.events.UPLOAD_EVENT_ID),o=h.getEvent(e,h.events.FILE_PROXY_EVENT_ID),i=h.getEmitter(e,h.events.PROXY_URL_EVENT_ID).event,s=Ct(n),c=Ct(i),d=Ct(o),u=t.addDisposable(new kt(s)),p=t.addDisposable(new kt(d)),f=t.addDisposable(new kt(c));return{setOptions(g){u.setListener(g.handleLoadImage),p.setListener(g.handleFileProxy),f.setListener(g.handleUrlProxy)},instance:{handleLoadImage:s,handleFileProxy:d,handleUrlProxy:c}}}),Sy=h.defineMixin(e=>{const t=e.getInstance(h.DISPOSABLE_ID),n=h.getEvent(e,h.events.AI_TEXT_REQUEST_ID),o=h.getEvent(e,h.events.AI_IMAGE_REQUEST_ID),i=Ct(n),s=Ct(o),c=t.addDisposable(new kt(i)),d=t.addDisposable(new kt(s));return{setOptions(u){c.setListener(u.handleAITextRequest),d.setListener(u.handleAIImageRequest)},instance:{handleAITextRequest:i,handleAIImageRequest:s}}}),wy=class extends Error{cycle;constructor(e){super(`[units] цикл в зависимостях: ${e.join(" → ")}`),this.cycle=e}};function ky(e){const t=new Map;for(const n of e)for(const o of n.provides??[]){const i=t.get(o)??[];i.push(n),t.set(o,i)}return t}function Cy(e,t){const n=[];for(const o of e.awaits?.services??[])for(const i of t.get(o)??[])i!==e&&n.push(i);return n}function Ty(e){const t=ky(e),n=[],o=new Set,i=[],s=new Set,c=d=>{if(!o.has(d)){if(s.has(d)){const u=i.indexOf(d);throw new wy([...i.slice(u),d].map(p=>p.name))}s.add(d),i.push(d);for(const u of Cy(d,t))c(u);i.pop(),s.delete(d),o.add(d),n.push(d)}};for(const d of e)c(d);return n}var Iy="author,slug,date,modified,title,acf.html,id,parent,date_gmt",Ay="author,slug,date,modified,modified_gmt,title,acf.html,id,parent",xy=20,$o=[h.WpEblockApi];function Ma(e){return typeof e=="string"&&e?`${e.replace(/Z$/,"")}Z`:void 0}function Py(e){return{async readRevisions(t,n=1){const o=await h.getApi(e,$o).eblock_revisions_list({parent:t,per_page:xy,page:n},{extraQuery:{_fields:Iy}}),i=(o?.data??[]).map(c=>r.WpBlockRevisionToBlockRevision(c)),s=Number(o?.headers?.get("X-WP-TotalPages"));return{revisions:i,page:n,hasMore:Number.isFinite(s)&&n<s}},async readAutosave(t){const n=h.getApi(e,$o),[o,i]=await Promise.all([n.eblock_autosaves_list({id:t},{extraQuery:{_fields:Ay}}),n.eblock_detail({id:t},{extraQuery:{_fields:"modified_gmt"}})]),s=(o?.data??[]).map(d=>{const u=d,p=r.WpBlockRevisionToBlockRevision(u),f=Ma(u.modified_gmt);return f?{...p,modified:f}:p}),c=Date.parse(Ma(i?.data?.modified_gmt)??"");return r.autosaveStateFromSlots(s,Number.isFinite(c)?c:void 0)},async saveAutosave(t,n){const o=n,i=o.global_block&&o.html?r.injectEmBlockIdIntoBlockHtml(o.html,t):o.html??"";r.writePendingData(t,{sentAt:Date.now(),html:i,common_styles:""});const s=await h.getApi(e,$o).eblock_autosaves_create({id:t},r.BlockAutoSaveToWpBlockAutoSave({title:o.title,html:i,project:o.project,excerpt:new Date().toISOString()}),{type:h.ContentType.FormData});return r.WpBlockRevisionToBlockRevision(s?.data)}}}var Ry="author,slug,date,modified,title,meta,acf.html,acf.common_styles,id,parent,date_gmt",jy="author,slug,date,modified,modified_gmt,title,meta,acf.html,acf.common_styles,id,parent";function Na(e){return typeof e=="string"&&e?`${e.replace(/Z$/,"")}Z`:void 0}var Oy=20,Uo=[h.WpEmailApi];function Ly(e){return{async readRevisions(t,n=1){const o=await h.getApi(e,Uo).email_revisions_list({parent:t,per_page:Oy,page:n},{extraQuery:{_fields:Ry}}),i=(o?.data??[]).map(c=>r.WpEmailRevisionToEmailRevision(c)),s=Number(o?.headers?.get("X-WP-TotalPages"));return{revisions:i,page:n,hasMore:Number.isFinite(s)&&n<s}},async readAutosave(t){const n=h.getApi(e,Uo),[o,i]=await Promise.all([n.email_autosaves_list({id:t},{extraQuery:{_fields:jy}}),n.email_detail({id:t},{extraQuery:{_fields:"modified_gmt"}})]),s=(o?.data??[]).map(d=>{const u=d,p=r.WpEmailRevisionToEmailRevision(u),f=Na(u.modified_gmt);return f?{...p,modified:f}:p}),c=Date.parse(Na(i?.data?.modified_gmt)??"");return r.autosaveStateFromSlots(s,Number.isFinite(c)?c:void 0)},async saveAutosave(t,n){const o=await h.getApi(e,Uo).email_autosaves_create({id:t},r.EmailAutoSaveToWpEmailAutoSave({...n,excerpt:new Date().toISOString()}),{type:h.ContentType.FormData});return r.WpEmailRevisionToEmailRevision(o?.data)}}}var Da=["_embedded","id","author","title","meta","emailtags","folder","group","modified","date","type","parent","date_gmt","acf.description","acf.html","acf.common_styles","acf.is_template","acf.lock","acf.parent_email","acf.project","acf.secret_hash","acf.subject","acf.utm_parameters"].join(","),zo=[h.WpEmailApi],Fa=e=>r.EmailToWpEmail(e);function My(e){return{async readEmail(t){const n=await h.getApi(e,zo).email_detail({id:r.toNumberSafe(t)},{extraQuery:{_embed:"wp:term",_fields:Da}});if(!n)throw new r.EmailOpenFailedError("unavailable");if(n.ok===!1)throw r.openFailureFromResponse(n);return n.data?r.WpEmailToEmail(n.data):null},async createEmail(t){const n={status:"publish",...Fa(t)},o=await h.getApi(e,zo).email_create(n,{type:h.ContentType.Json});return r.WpEmailToEmail(o?.data)},async updateEmail(t,n){const o=await h.getApi(e,zo).email_partial_update({id:t},Fa(n),{type:h.ContentType.Json,extraQuery:{_embed:"wp:term",_fields:Da}});return r.WpEmailToEmail(o?.data)}}}function Ny(e){r.injectRestEmailPortFactories(e,{email:My,history:Ly,blockHistory:Py})}var Go=20,Dy=({source:e,emailtags:t,group:n,tags:o,...i})=>i;function Fy({revisions:e,revisionsByBlock:t}){const n=async(o,i)=>(t.clear(),await t.get(o,{page:i}),(await e.cache.values()??[]).filter(s=>String(s?.parent)===String(o)));return{async readRevisions(o,i=1){const s=await n(o,i);return{revisions:s.slice(Go*(i-1),Go*i),page:i,hasMore:s.length>Go*i}},async readAutosave(o){return r.autosaveStateFromRevisions(await n(o,1))},async saveAutosave(o,i){const s=Dy(i);return await e.create({...s,parent:o,modified:new Date().toString()})}}}var Ba=h.createIdentifier$1("blockDocuments.provided");function By(e){if(e.getInstance(Ba))return;e.inject(Ba,!0);const t=r.blockRevisionsDataSourceProvider(e);r.injectBlockHistoryPort(e,Fy({revisions:t,revisionsByBlock:t.byForeignKey("parent")}))}var $y=zt.__commonJSMin(((e,t)=>{(function(n){if(typeof window>"u")return;var o=0,i,s=!1,c=!1,d=7,u="[iFrameSizer]",p=u.length,f=null,g=window.requestAnimationFrame,y=Object.freeze({max:1,scroll:1,bodyScroll:1,documentElementScroll:1}),m={},E=null,k=Object.freeze({autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,license:"1jqr0si6pnt",log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,mouseEvents:!0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",onClose:function(){return!0},onClosed:function(){},onInit:function(){},onMessage:function(){O("onMessage function not defined")},onMouseEnter:function(){},onMouseLeave:function(){},onResized:function(){},onScroll:function(){return!0}});function w(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function v(C,T,R){C.addEventListener(T,R,!1)}function x(C,T,R){C.removeEventListener(T,R,!1)}function P(){for(var C=["moz","webkit","o","ms"],T=0;T<C.length&&!g;T+=1)g=window[C[T]+"RequestAnimationFrame"];g?g=g.bind(window):L("setup","RequestAnimationFrame not supported")}function K(C){var T="Host page: "+C;return window.top!==window.self&&(T=window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+C:"Nested host page: "+C),T}function J(C){return u+"["+K(C)+"]"}function N(C){return m[C]?m[C].log:s}function L(C,T){z("log",C,T,N(C))}function A(C,T){z("info",C,T,N(C))}function O(C,T){z("warn",C,T,!0)}function z(C,T,R,D){D===!0&&window.console}function B(C){function T(){function $(){et(oe),Z(ee),Ge("onResized",oe)}S("Height"),S("Width"),be($,oe,"init")}function R(){var $=Xe.slice(p).split(":"),le=$[1]?parseInt($[1],10):0,xe=m[$[0]]&&m[$[0]].iframe,Se=getComputedStyle(xe);return{iframe:xe,id:$[0],height:le+D(Se)+I(Se),width:$[2],type:$[3]}}function D($){return $.boxSizing!=="border-box"?0:($.paddingTop?parseInt($.paddingTop,10):0)+($.paddingBottom?parseInt($.paddingBottom,10):0)}function I($){return $.boxSizing!=="border-box"?0:($.borderTopWidth?parseInt($.borderTopWidth,10):0)+($.borderBottomWidth?parseInt($.borderBottomWidth,10):0)}function S($){var le=Number(m[ee]["max"+$]),xe=Number(m[ee]["min"+$]),Se=$.toLowerCase(),Me=Number(oe[Se]);L(ee,"Checking "+Se+" is in range "+xe+"-"+le),Me<xe&&(Me=xe,L(ee,"Set "+Se+" to min value")),Me>le&&(Me=le,L(ee,"Set "+Se+" to max value")),oe[Se]=""+Me}function ae(){function $(){function Se(){var We=0,Be=!1;for(L(ee,"Checking connection is from allowed list of origins: "+xe);We<xe.length;We++)if(xe[We]===le){Be=!0;break}return Be}function Me(){var We=m[ee]&&m[ee].remoteHost;return L(ee,"Checking connection is from: "+We),le===We}return xe.constructor===Array?Se():Me()}var le=C.origin,xe=m[ee]&&m[ee].checkOrigin;if(xe&&""+le!="null"&&!$())throw new Error("Unexpected message received from: "+le+" for "+oe.iframe.id+". Message was: "+C.data+". This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.");return!0}function we(){return u===(""+Xe).slice(0,p)&&Xe.slice(p).split(":")[0]in m}function Ye(){var $=oe.type in{true:1,false:1,undefined:1};return $&&L(ee,"Ignoring init message from meta parent page"),$}function Qe($){return Xe.slice(Xe.indexOf(":")+d+$)}function ze($){L(ee,"onMessage passed: {iframe: "+oe.iframe.id+", message: "+$+"}"),Ge("onMessage",{iframe:oe.iframe,message:JSON.parse($)}),L(ee,"--")}function Ze(){var $=document.body.getBoundingClientRect(),le=oe.iframe.getBoundingClientRect();return JSON.stringify({iframeHeight:le.height,iframeWidth:le.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(le.top-$.top,10),offsetLeft:parseInt(le.left-$.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,documentHeight:document.documentElement.clientHeight,documentWidth:document.documentElement.clientWidth,windowHeight:window.innerHeight,windowWidth:window.innerWidth})}function pt($,le){function xe(){fe("Send Page Info","pageInfo:"+Ze(),$,le)}Te(xe,32,le)}function bt(){function $(Me,We){function Be(){m[Se]?pt(m[Se].iframe,Se):le()}["scroll","resize"].forEach(function(ot){L(Se,Me+ot+" listener for sendPageInfo"),We(window,ot,Be)})}function le(){$("Remove ",x)}function xe(){$("Add ",v)}var Se=ee;xe(),m[Se]&&(m[Se].stopPageInfo=le)}function ft(){m[ee]&&m[ee].stopPageInfo&&(m[ee].stopPageInfo(),delete m[ee].stopPageInfo)}function lt(){var $=!0;return oe.iframe===null&&(O(ee,"IFrame ("+oe.id+") not found"),$=!1),$}function G($){var le=$.getBoundingClientRect();return H(ee),{x:Math.floor(Number(le.left)+Number(f.x)),y:Math.floor(Number(le.top)+Number(f.y))}}function V($){function le(){f=We,te(),L(ee,"--")}function xe(){return{x:Number(oe.width)+Me.x,y:Number(oe.height)+Me.y}}function Se(){window.parentIFrame?window.parentIFrame["scrollTo"+($?"Offset":"")](We.x,We.y):O(ee,"Unable to scroll to requested position, window.parentIFrame not found")}var Me=$?G(oe.iframe):{x:0,y:0},We=xe();L(ee,"Reposition requested from iFrame (offset x:"+Me.x+" y:"+Me.y+")"),window.top===window.self?le():Se()}function te(){Ge("onScroll",f)===!1?De():Z(ee)}function ue($){function le(){var Be=G(We);L(ee,"Moving to in page link (#"+Se+") at x: "+Be.x+" y: "+Be.y),f={x:Be.x,y:Be.y},te(),L(ee,"--")}function xe(){window.parentIFrame?window.parentIFrame.moveToAnchor(Se):L(ee,"In page link #"+Se+" not found and window.parentIFrame not found")}var Se=$.split("#")[1]||"",Me=decodeURIComponent(Se),We=document.getElementById(Me)||document.getElementsByName(Me)[0];We?le():window.top===window.self?L(ee,"In page link #"+Se+" not found"):xe()}function he($){var le={};if(Number(oe.width)===0&&Number(oe.height)===0){var xe=Qe(9).split(":");le={x:xe[1],y:xe[0]}}else le={x:oe.width,y:oe.height};Ge($,{iframe:oe.iframe,screenX:Number(le.x),screenY:Number(le.y),type:oe.type})}function Ge($,le){return U(ee,$,le)}function qe(){switch(m[ee]&&m[ee].firstRun&&Le(),oe.type){case"close":me(oe.iframe);break;case"message":ze(Qe(6));break;case"mouseenter":he("onMouseEnter");break;case"mouseleave":he("onMouseLeave");break;case"autoResize":m[ee].autoResize=JSON.parse(Qe(9));break;case"scrollTo":V(!1);break;case"scrollToOffset":V(!0);break;case"pageInfo":pt(m[ee]&&m[ee].iframe,ee),bt();break;case"pageInfoStop":ft();break;case"inPageLink":ue(Qe(9));break;case"reset":ve(oe);break;case"init":T(),Ge("onInit",oe.iframe);break;default:Number(oe.width)===0&&Number(oe.height)===0?O("Unsupported message received ("+oe.type+"), this is likely due to the iframe containing a later version of iframe-resizer than the parent page"):T()}}function st($){var le=!0;return m[$]||(le=!1,O(oe.type+" No settings for "+$+". Message was: "+Xe)),le}function Bt(){for(var $ in m)fe("iFrame requested init",Y($),m[$].iframe,$)}function Le(){m[ee]&&(m[ee].firstRun=!1)}var Xe=C.data,oe={},ee=null;Xe==="[iFrameResizerChild]Ready"?Bt():we()?(oe=R(),ee=oe.id,m[ee]&&(m[ee].loaded=!0),!Ye()&&st(ee)&&(L(ee,"Received: "+Xe),lt()&&ae()&&qe())):A(ee,"Ignored: "+Xe)}function U(C,T,R){var D=null,I=null;if(m[C])if(D=m[C][T],typeof D=="function")I=D(R);else throw new TypeError(T+" on iFrame["+C+"] is not a function");return I}function de(C){var T=C.id;delete m[T]}function me(C){var T=C.id;if(U(T,"onClose",T)===!1){L(T,"Close iframe cancelled by onClose event");return}L(T,"Removing iFrame: "+T);try{C.parentNode&&C.parentNode.removeChild(C)}catch(R){O(R)}U(T,"onClosed",T),L(T,"--"),de(C),i&&(i.disconnect(),i=null)}function H(C){f===null&&(f={x:window.pageXOffset===n?document.documentElement.scrollLeft:window.pageXOffset,y:window.pageYOffset===n?document.documentElement.scrollTop:window.pageYOffset},L(C,"Get page position: "+f.x+","+f.y))}function Z(C){f!==null&&(window.scrollTo(f.x,f.y),L(C,"Set page position: "+f.x+","+f.y),De())}function De(){f=null}function ve(C){function T(){et(C),fe("reset","reset",C.iframe,C.id)}L(C.id,"Size reset requested by "+(C.type==="init"?"host page":"iFrame")),H(C.id),be(T,C,"reset")}function et(C){function T(S){if(!C.id){L("undefined","messageData id not set");return}C.iframe.style[S]=C[S]+"px",L(C.id,"IFrame ("+I+") "+S+" set to "+C[S]+"px")}function R(S){!c&&C[S]==="0"&&(c=!0,L(I,"Hidden iFrame detected, creating visibility listener"),Fe())}function D(S){T(S),R(S)}var I=C.iframe.id;m[I]&&(m[I].sizeHeight&&D("height"),m[I].sizeWidth&&D("width"))}function be(C,T,R){R!==T.type&&g&&!window.jasmine?(L(T.id,"Requesting animation frame"),g(C)):C()}function fe(C,T,R,D,I){function S(){var ze=m[D]&&m[D].targetOrigin;L(D,"["+C+"] Sending msg to iframe["+D+"] ("+T+") targetOrigin: "+ze),R.contentWindow.postMessage(u+T,ze)}function ae(){O(D,"["+C+"] IFrame("+D+") not found")}function we(){R&&"contentWindow"in R&&R.contentWindow!==null?S():ae()}function Ye(){function ze(){m[D]&&!m[D].loaded&&!Qe&&(Qe=!0,O(D,"IFrame has not responded within "+m[D].warningTimeout/1e3+" seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ignored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning."))}I&&m[D]&&m[D].warningTimeout&&(m[D].msgTimeout=setTimeout(ze,m[D].warningTimeout))}var Qe=!1;D=D||R.id,m[D]&&(we(),Ye())}function Y(C){return C+":"+m[C].bodyMarginV1+":"+m[C].sizeWidth+":"+m[C].log+":"+m[C].interval+":"+m[C].enablePublicMethods+":"+m[C].autoResize+":"+m[C].bodyMargin+":"+m[C].heightCalculationMethod+":"+m[C].bodyBackground+":"+m[C].bodyPadding+":"+m[C].tolerance+":"+m[C].inPageLinks+":"+m[C].resizeFrom+":"+m[C].widthCalculationMethod+":"+m[C].mouseEvents}function pe(C){return typeof C=="number"}function ie(C,T){function R(){function V(ue){var he=m[G][ue];he!==1/0&&he!==0&&(C.style[ue]=pe(he)?he+"px":he,L(G,"Set "+ue+" = "+C.style[ue]))}function te(ue){if(m[G]["min"+ue]>m[G]["max"+ue])throw new Error("Value for min"+ue+" can not be greater than max"+ue)}te("Height"),te("Width"),V("maxHeight"),V("minHeight"),V("maxWidth"),V("minWidth")}function D(){var V=T&&T.id||k.id+o++;return document.getElementById(V)!==null&&(V+=o++),V}function I(V){if(typeof V!="string")throw new TypeError("Invaild id for iFrame. Expected String");return V===""&&(C.id=V=D(),s=(T||{}).log,L(V,"Added missing iframe ID: "+V+" ("+C.src+")")),V}function S(){switch(L(G,"IFrame scrolling "+(m[G]&&m[G].scrolling?"enabled":"disabled")+" for "+G),C.style.overflow=(m[G]&&m[G].scrolling)===!1?"hidden":"auto",m[G]&&m[G].scrolling){case"omit":break;case!0:C.scrolling="yes";break;case!1:C.scrolling="no";break;default:C.scrolling=m[G]?m[G].scrolling:"no"}}function ae(){(typeof(m[G]&&m[G].bodyMargin)=="number"||(m[G]&&m[G].bodyMargin)==="0")&&(m[G].bodyMarginV1=m[G].bodyMargin,m[G].bodyMargin=""+m[G].bodyMargin+"px")}function we(){var V=m[G]&&m[G].firstRun,te=m[G]&&m[G].heightCalculationMethod in y;!V&&te&&ve({iframe:C,height:0,width:0,type:"init"})}function Ye(){m[G]&&(m[G].iframe.iFrameResizer={close:me.bind(null,m[G].iframe),removeListeners:de.bind(null,m[G].iframe),resize:fe.bind(null,"Window resize","resize",m[G].iframe),moveToAnchor:function(V){fe("Move to anchor","moveToAnchor:"+V,m[G].iframe,G)},sendMessage:function(V){V=JSON.stringify(V),fe("Send Message","message:"+V,m[G].iframe,G)}})}function Qe(V){function te(){fe("iFrame.onload",V,C,n,!0),we()}function ue(Ge){if(!C.parentNode)return null;var qe=new Ge(function(st){st.forEach(function(Bt){Array.prototype.slice.call(Bt.removedNodes).forEach(function(Le){Le===C&&me(C)})})});return qe.observe(C.parentNode,{childList:!0}),qe}var he=w();he&&(i=ue(he)),v(C,"load",te),fe("init",V,C,n,!0)}function ze(V){if(typeof V!="object")throw new TypeError("Options is not an object")}function Ze(V){for(var te in k)Object.prototype.hasOwnProperty.call(k,te)&&(m[G][te]=Object.prototype.hasOwnProperty.call(V,te)?V[te]:k[te])}function pt(V){return V===""||V.match(/^(about:blank|javascript:|file:\/\/)/)!==null?"*":V}function bt(V){var te=V.split("Callback");if(te.length===2){var ue="on"+te[0].charAt(0).toUpperCase()+te[0].slice(1);this[ue]=this[V],delete this[V],O(G,"Deprecated: '"+V+"' has been renamed '"+ue+"'. The old method will be removed in the next major version.")}}function ft(V){V=V||{},m[G]=Object.create(null),m[G].iframe=C,m[G].firstRun=!0,m[G].remoteHost=C.src&&C.src.split("/").slice(0,3).join("/"),ze(V),Object.keys(V).forEach(bt,V),Ze(V),m[G]&&(m[G].targetOrigin=m[G].checkOrigin===!0?pt(m[G].remoteHost):"*")}function lt(){return G in m&&"iFrameResizer"in C}var G=I(C.id);lt()?O(G,"Ignored iFrame, already setup."):(ft(T),S(),R(),ae(),Qe(Y(G)),Ye())}function se(C,T){E===null&&(E=setTimeout(function(){E=null,C()},T))}var Ae={};function Te(C,T,R){Ae[R]||(Ae[R]=setTimeout(function(){Ae[R]=null,C()},T))}function Fe(){function C(){function I(S){function ae(Ye){return(m[S]&&m[S].iframe.style[Ye])==="0px"}function we(Ye){return Ye.offsetParent!==null}m[S]&&we(m[S].iframe)&&(ae("height")||ae("width"))&&fe("Visibility change","resize",m[S].iframe,S)}Object.keys(m).forEach(function(S){I(S)})}function T(I){L("window","Mutation observed: "+I[0].target+" "+I[0].type),se(C,16)}function R(){var I=document.querySelector("body");new D(T).observe(I,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0})}var D=w();D&&R()}function X(C){function T(){Ie("Window "+C,"resize")}L("window","Trigger event: "+C),se(T,16)}function Ee(){function C(){Ie("Tab Visible","resize")}document.visibilityState!=="hidden"&&(L("document","Trigger event: Visibility change"),se(C,16))}function Ie(C,T){function R(D){return m[D]&&m[D].resizeFrom==="parent"&&m[D].autoResize&&!m[D].firstRun}Object.keys(m).forEach(function(D){R(D)&&fe(C,T,m[D].iframe,D)})}function ge(){v(window,"message",B),v(window,"resize",function(){X("resize")}),v(document,"visibilitychange",Ee),v(document,"-webkit-visibilitychange",Ee)}function Re(){function C(D,I){function S(){if(I.tagName){if(I.tagName.toUpperCase()!=="IFRAME")throw new TypeError("Expected <IFRAME> tag, found <"+I.tagName+">")}else throw new TypeError("Object is not a valid DOM element")}I&&(S(),ie(I,D),R.push(I))}function T(D){D&&D.enablePublicMethods&&O("enablePublicMethods option has been removed, public methods are now always available in the iFrame")}var R;return P(),ge(),function(I,S){switch(R=[],T(I),typeof S){case"undefined":case"string":Array.prototype.forEach.call(document.querySelectorAll(S||"iframe"),C.bind(n,I));break;case"object":C(I,S);break;default:throw new TypeError("Unexpected data type ("+typeof S+")")}return R}}function Ue(C){C.fn?C.fn.iFrameResize||(C.fn.iFrameResize=function(R){function D(I,S){ie(S,R)}return this.filter("iframe").each(D).end()}):A("","Unable to bind to jQuery, it is not fully loaded.")}window.jQuery!==n&&Ue(window.jQuery),typeof define=="function"&&define.amd?define([],Re):typeof t=="object"&&typeof t.exports=="object"&&(t.exports=Re()),window.iFrameResize=window.iFrameResize||Re()})()})),Uy=zt.__toESM($y()),zy={checkOrigin:!1,minHeight:600,scrolling:!1};function Gy(e){const t=()=>e.iFrameResizer;return(0,Uy.default)(zy,e),{resize:()=>t()?.resize?.(),dispose:()=>t()?.removeListeners?.()}}function Wy(e){e.inject(Mi,Gy)}function Hy(e){const t=r.getMessageService(e),n=e.getInstance(r.LOCALE_SERVICE_ID);if(!n)return;let o="";const i=()=>{const d=n.snapshot(),u=d.id??"";if(!t.isInited()||u===o)return;const p=r.createI18n(d.catalog),f=y=>p.__(y),g=r.SANDBOX_TRANSLATIONS_MAP(f);o=u,t.send(r.EVENT_TYPES.SANDBOX_TRANSLATIONS,{name:u,data:g})},s=t.onInit(()=>{o="",i()}),c=n.state.watch(i);e.getInstance(h.DISPOSABLE_ID)?.addDispose(()=>{s.dispose(),c.dispose()})}function qy(e){const t=e?.content?.templateId;return t==null||t===""?void 0:String(t)}function Vy(e){e.getInstance(h.OPTIONS_SOURCE_ID)?.watch(t=>{const n=qy(t);n!==void 0&&Fg(e,n)})}var Wo={en_US:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/c00a8e02.js")).then(e=>e.en_US_exports),void 0,{}.url),ru_RU:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/8fb0fe48.js")),void 0,{}.url),uk_UA:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/9a70cc1e.js")),void 0,{}.url),es_ES:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/5bf994b4.js")),void 0,{}.url),pt_BR:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/a15ab67d.js")),void 0,{}.url),de_DE:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/ffb36e93.js")),void 0,{}.url),fr_FR:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/364dcebf.js")),void 0,{}.url),it_IT:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/dfddbd68.js")),void 0,{}.url),pl_PL:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/f3eda1c7.js")),void 0,{}.url)};async function Ky(e){const t=Wo[e];if(!t){const n=Wo.en_US;return n?(await n()).default:void 0}return(await t()).default}var v0=Object.keys(Wo),Yy=e=>e==="uk"?"uk_UA":e;function Qy(e){e.getInstance(r.LOCALE_SERVICE_ID)?.useAntdLoader(t=>Ky(Yy(t)))}function Xy(e){}function $a(e,t,n){let o=!1;const i=e.watch(s=>{o||!t(s)||(o=!0,n())});o&&i.dispose()}function Jy(e,t){const n=e.getInstance(h.CONFIG_SOURCE_ID);n&&$a(n,o=>!!o?.codeEnabled||!!o?.codeSideEnabled,()=>{tv(e,()=>{nv(e,()=>{ev(e,()=>{Ht(e).whenVisible(()=>{Xt(()=>{Zy(t).catch(()=>{})})})})})})})}async function Zy(e){await e()}function ev(e,t){const n=e.getInstance(Ns);if(!n){Xt(t);return}const o=()=>{if(n.pipeline.filledGeneration()!==void 0){t();return}Xt(o)};Xt(o)}function tv(e,t){const n=e.getInstance(r.EMAIL_DOCUMENTS_ID);if(!n)return;if(n.current()){t();return}let o=!1;const i=n.subscribe(()=>{o||!n.current()||(o=!0,t())});o&&i()}function nv(e,t){const n=e.getInstance(h.OPTIONS_SOURCE_ID);n&&$a(n,o=>!!o?.element,t)}function rv(e){Jy(e,tu)}var Ua=h.createIdentifier$1("NotificationService");function za(e,t="success"){return typeof e=="string"&&(e={message:e}),r.filterUndefined({type:e.type||t,data:e.data,innerException:e.innerException,title:e.message,description:e.description,actions:e.btn,onClose:e.onClose,duration:e.duration,icon:e.icon,placement:e.placement,style:e.style,closeIcon:e.closeIcon,props:e.props,role:e.role})}var ov="bottomRight";function Ho(e,t){return typeof e=="string"||typeof e=="object"?za(e,t):e}var iv=class extends h.Disposable{send;onNotify;onError;onSuccess;constructor(e,t,n){super(),this.send=n,this.onNotify=Ct(t,c=>c,c=>Ho(c)),this.onError=Ct(h.filter(t,c=>c.type==="error"),c=>c,c=>Ho(c,"error")),this.onSuccess=Ct(h.filter(t,c=>c.type==="success"),c=>c,c=>Ho(c));const o=this.addDisposable(new kt(this.onNotify)),i=this.addDisposable(new kt(this.onError)),s=this.addDisposable(new kt(this.onSuccess));this.addDisposable(e.watch(({handleNotify:c,handleError:d,handleSuccess:u})=>{o.setListener(c),i.setListener(d),s.setListener(u)}))}notify(e){this.send({placement:ov,...za(e)})}};function sv(e){e.injectFactory(Ua,()=>{const t=new iv(e.getInstance(h.OPTIONS_SOURCE_ID),h.getEvent(e,h.events.ON_NOTIFICATION),n=>{r.executeCommand(e,r.NOTIFY_COMMAND_ID,n)});return e.getInstance(h.DISPOSABLE_ID)?.addDisposable(t),t},!0)}function av(e){const t=r.getEmailDocuments(e),n=i=>{e.getInstance(h.STORE_ID)?.dispatch(r.taxonomiesApi.util.invalidateTags([{type:"folder",id:i}]))},o=t.onSaved(i=>{i.created&&n("folder")});e.getInstance(h.DISPOSABLE_ID)?.addDispose(o)}function b0(e){return e}var lv=[{name:"rest.legacySections",provides:[h.REST_CLIENT_ID],setup:h.provideLegacyRestSections},{name:"canvas.resizer",provides:[Mi],setup:Wy},{name:"canvas.sandboxLocale",awaits:{services:[r.LOCALE_SERVICE_ID]},setup:Hy},{name:"locale.brandCatalog",awaits:{services:[r.LOCALE_SERVICE_ID]},setup:Xy},{name:"email.restPorts",provides:[r.REST_EMAIL_PORTS_ID],setup:Ny},{name:"block.historyPort",setup:By},{name:"email.templatePrefetch",setup:Vy},{name:"locale.antd",awaits:{services:[r.LOCALE_SERVICE_ID]},setup:Qy},{name:"save.listsFollow",setup:av},{name:"monaco.prewarm",awaits:{services:[h.CONFIG_SOURCE_ID]},setup:rv},{name:"notifications",provides:[Ua],setup:sv},{name:"email.operations",setup:vy}],cv=h.defineMixin(e=>{for(const t of Ty(lv))t.setup(e);return{instance:by(e)}}),dv=h.combineMixins([cv,P_,iy,dy,Ey,Sy,jg,sy,$s,Us]);async function uv(e){const t=new Map;typeof e=="object"&&(e=e.code);const{amp2html:n,html2amp:o}=await(0,Ve.__vitePreload)(async()=>{const{amp2html:c,html2amp:d}=await Promise.resolve().then(()=>ye("./static/core/30f16e98.js"));return{amp2html:c,html2amp:d}},void 0,{}.url),i=await yt.changeHtml(e,async c=>{await yt.replaceImagesInDocument(c.document,d=>r.mapper.getEscapedText(d)!==d?d:r.toAbsoluteUrl(d),t);for(const d of c.document.querySelectorAll(".em-amp-show-disabled"))d.remove();c.handleRender(async({contentDocument:d,managedNodeController:u})=>{await o(d,{mappedTags:{script:"___script"},commit:()=>u.commit()})})},[800]),s=await yt.changeHtml(e,async c=>{await yt.replaceImagesInDocument(c.document,d=>r.mapper.getEscapedText(d)!==d?d:r.toAbsoluteUrl(d),t);for(const d of c.document.querySelectorAll(".em-amp-show-only"))d.remove();await n(c.document,{mappedTags:{script:"___script"}})},[800]);return{code:e,html:s,ampHtml:i}}async function pv(){const{installDiagnostics:e}=await(0,Ve.__vitePreload)(async()=>{const{installDiagnostics:t}=await Promise.resolve().then(()=>ye("./static/core/199dc589.js"));return{installDiagnostics:t}},void 0,{}.url);return e()}async function mv(e,t){const{initDevTools:n}=await(0,Ve.__vitePreload)(async()=>{const{initDevTools:o}=await Promise.resolve().then(()=>ye("./static/core/52fbc985.js"));return{initDevTools:o}},void 0,{}.url);n(e,t)}var fv="1.1.85-dev.3";nn.asyncMixins=dv,nn.initDevTools=mv,nn.installDiagnostics=pv,nn.parseAMP=uv,nn.version=fv});
857
+ </tr>`)}},fn=async()=>{const M=oe();st(M,async q=>{try{const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q),ne=await x(q,[re.width],e.utm_parameters,async He=>{ot(He)}),W=await te({htmlContent:ne,notification:E}).unwrap(),Ce=window.URL.createObjectURL(new Blob([W],{type:"application/pdf"})),_e=document.createElement("a");_e.href=Ce,_e.setAttribute("download",`${qe()}.pdf`),document.body.appendChild(_e),_e.click(),document.body.removeChild(_e),window.URL.revokeObjectURL(Ce)}catch{}})},Ot=M=>{const q=oe();st(q,Q=>{be({event:"click",action:"export_email",export_type:"HTML"});const re=document.querySelector(".email-preview"),ne=getComputedStyle(re);x(Q,[ne.width],e.utm_parameters,async W=>{await Be(W),ot(W),await r.processAmp(W,M)}).then(W=>{const Ce=new Blob([W],{type:"text/html;charset=utf-8"});(0,sn.saveAs)(Ce,`${qe()}.html`)}).catch(W=>{})},!0)},ct=M=>{const q=oe();st(q,Q=>{be({event:"click",action:"export_email",export_type:"TEXT"});const re=document.querySelector(".email-preview"),ne=getComputedStyle(re);x(Q,[ne.width],e.utm_parameters,async W=>{await Be(W),ot(W),await r.processAmp(W,M);const[{htmlToText:Ce},{EmailTextPlainConvertOptions:_e}]=await Promise.all([(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/230f23ec.js")),void 0,{}.url),(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/6541580a.js")),void 0,{}.url)]);W.handleReadHtml(He=>{He.html=Ce(He.contentDocument,_e)})}).then(W=>{const Ce=new Blob([W],{type:"text/plain;charset=utf-8"});(0,sn.saveAs)(Ce,`${qe()}.txt`)}).catch(W=>{})})},Et=()=>{const M=oe();st(M,q=>{be({event:"click",action:"export_email",export_type:"MARKDOWN"});const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q),{utm_parameters:ne}=e;x(q,[re.width],ne,async W=>{ot(W),await r.processAmp(W,"html");const{htmlToMarkdown:Ce}=await(0,Ve.__vitePreload)(async()=>{const{htmlToMarkdown:_e}=await Promise.resolve().then(()=>ye("./static/core/b743a76d.js"));return{htmlToMarkdown:_e}},void 0,{}.url);W.handleReadHtml(_e=>{_e.html=Ce(_e.contentDocument)})}).then(W=>{const Ce=new Blob([W],{type:"text/markdown;charset=utf-8"});(0,sn.saveAs)(Ce,`${qe()}.md`)}).catch(W=>r.reportError(W,{origin:"markdown-export"}))})},Lt=M=>{const q=oe();st(q,Q=>{be({event:"click",action:"export_email",export_type:"Clipboard"});const re=document.querySelector(".email-preview"),ne=getComputedStyle(re);x(Q,[ne.width],e.utm_parameters,async W=>{await Be(W),ot(W),await r.processAmp(W,M)}).then(W=>navigator.clipboard.writeText(W).then(function(){E.success(n("The email has been copied to the clipboard."))})).catch(W=>{})},!0)},jn=async M=>{Re&&mo(Re)},On=()=>{Ue(null),T("")},gn=async()=>{if(!R){D(!0);try{const M=await Se([800,tf],Zm);if(!M)return;const{hrefs:q,dispose:Q}=M;try{const[re,ne]=await Promise.all(q.map(_e=>yt.getImageByUrl(_e).then(He=>yt.imageToBlob(He)))),W=qe(),Ce=await yt.htmlFilesToZip(Jm(W,{desktop:re,mobile:ne}));(0,sn.saveAs)(Ce,Cs(W).archive),be({event:"click",action:"export_email",export_type:"Image"})}finally{Q()}}catch{E.error({title:n("Error"),description:n("Failed to export the email as images. Please try again.")})}finally{D(!1)}}},Ln=M=>{const q=J.get(r.APP_COOKIES.em_token);return fetch(`https://app.useblocks.io/api/wp-json/cors-proxy/v1/get?url=${encodeURIComponent(M)}`,{headers:{authorization:`Bearer ${q}`}}).then(Q=>Q.blob())},Mn=M=>new Promise((q,Q)=>{const re=()=>Ln(M).then(q,Q);fetch(M).then(ne=>q(ne.blob()),re).catch(()=>{})}),gt=(M,q)=>{const Q=oe();st(Q,re=>{be({event:"click",action:"export_email",export_type:"Outlook"});const ne=document.querySelector(".email-preview"),W=getComputedStyle(ne),Ce=async(_e,He)=>{_e.document,await r.processAmp(_e,He),await Be(_e),ot(_e)};P(e.title,re,[W.width,W.height],e.utm_parameters,M?_e=>Ce(_e,"html"):_e=>Ce(_e),q?{embedImagesAsBase64:!0,getImageBlob:Mn}:void 0).then(_e=>{const He=new Blob([_e],{type:"text/html;charset=utf-8"});(0,sn.saveAs)(He,`${qe()}.eml`)}).catch(_e=>{})})},St=M=>{k({centered:!0,mask:{closable:!0},title:n("Embed images in the file?"),content:n('If "Yes", images will be included in the file itself. This is useful for offline viewing or if external images are blocked, but increases file size. If "No", images will be loaded from external links.'),okText:n("Yes"),cancelText:n("No"),onOk:()=>gt(M,!0),onCancel:()=>gt(M,!1)})},ce=async()=>{const M=oe();st(M,async q=>{be({event:"click",action:"export_email",export_type:"ZIP"});const Q=document.querySelector(".email-preview"),re=getComputedStyle(Q),ne=await K(q,[re.width,void 0],e.utm_parameters,Mn,async Ce=>{await Be(Ce),ot(Ce),Tt&&await r.processAmp(Ce,"html")});Tt&&(ne["amp.html"]=await x(q,[re.width],e.utm_parameters,async Ce=>{await Be(Ce),ot(Ce),await r.processAmp(Ce,"amp")}));const W=await yt.htmlFilesToZip(ne);(0,sn.saveAs)(W,`${qe()}.zip`)},!0)},ke=async()=>{if(be({event:"click",action:"duplicate_email",entity_type:"email",entity_id:e.id,project_id:e.project,context:"editor"}),e.isNew)E.warning({title:n("To create a copy, you need to save the email.")});else{if((await B.fire(e)).some(M=>M===!1))return;ft({title:xt.generateCopyTitle(e.title),...e.meta!==void 0?{meta:e.meta}:{},project:Number(ue?.id),description:e.description,html:xt.generateCopyHtml(oe()||"",String(e.title)),parent_email:e.parent_email||6892,common_styles:e.common_styles||"",utm_parameters:{utm_source:e.utm_parameters?.utm_source,utm_medium:e.utm_parameters?.utm_medium,utm_campaign:e.utm_parameters?.utm_campaign,utm_term:e.utm_parameters?.utm_term,utm_content:e.utm_parameters?.utm_content},emailtags:e.emailtags,folder:e.folder}).unwrap().then(M=>{u(`/projects/${ue.id}/emails/${M.id}`),E.success({title:n('The copy of email "')+e.title+n('" was successfully created.')}),be({event:"duplicate",action:"duplicate_email_success",entity_type:"email",entity_id:e.id,cloned_entity_id:M.id,project_id:e.project,context:"editor"}),he("folder")}).catch(M=>{E.error({title:M.data.code,description:M.data.message})})}},Ne=()=>{be({event:"click",action:"click_delete_email_menu_item",entity_type:"email",entity_id:e.id,project_id:e.project,context:"editor"}),e.isNew?E.success(n("The draft of the email has been deleted.")):nt(e,u)},nt=(M,q)=>{be({event:"open",action:"open_delete_email_modal",entity_type:"email",entity_id:M.id,project_id:M.project,context:"editor"}),k({mask:{closable:!0},centered:!0,title:o('Are you sure to delete "',"email")+M.title+n('" email?'),icon:(0,a.jsx)(r.EmIcons,{icon:"DeleteOutlined",component:_.icons$DeleteOutlined,size:22,style:{color:_.ui_kit$iconColors.danger,marginInlineEnd:12,flexShrink:0}}),okText:n("Yes"),cancelText:n("No"),onOk:()=>bt(M,q)})},je=()=>{go().catch(()=>{}),r.uploadFile("application/zip, message/rfc822, text/html",Yt)},Yt=async M=>{const q=M[0];try{i(r.setIsGlobalLoading(!0));const{createDocumentProcessor:Q,createFileProcessor:re,importEmail:ne}=await go(),{html:W,hasBrowserExtensionArtifacts:Ce}=await ne(q,re(c,d,g,ue,N),Q(q))??{html:"",hasBrowserExtensionArtifacts:!1};Ce&&U.fire();const[_e]=yt.getFileNameAndExt(q.name.replaceAll("&nbsp;"," ")),He=_e||xt.getTitleFromHtml(W)||"";ee(W,{undoable:!0}),s({title:He}),i(r.setIsGlobalLoading(!1)),le.fire({html:W})}catch(Q){i(r.setIsGlobalLoading(!1));const re=Q instanceof Error?Q.message:Q;E.error({title:re})}be({event:"upload_file",action:"import_email"})},$t=()=>{const M=oe();M&&(be({event:"click",action:"convert_layout"}),le.fire({html:M}))},dt=[];N.emailDropdownMenuClone&&dt.push({label:n("Clone"),icon:(0,a.jsx)(r.EmIcons,{icon:"CopyOutlined",component:_.icons$CopyOutlined,size:16,strokeWidth:N.iconStrokeWidth}),key:"Clone",className:"em-analytics__email-clone",disabled:lt.isLoading,onClick:ke}),N.emailDropdownMenuImport&&dt.push({label:o("Import","verb"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"CloudUploadOutlined",component:_.icons$CloudUploadOutlined,style:Dt}),locked:Qe.isLocked,strokeWidth:N.iconStrokeWidth}),key:"Import",className:"em-analytics__editor-page__import",onClick:()=>{if(Qe.isLocked){Ze("template_import");return}be({event:"click",action:"import_email"}),je()}});const Nn=oe(),Ut=!e.hasOwnProperty("type")&&bs(Nn,L)!==null;N.emailDropdownMenuConvert&&Ut&&dt.push({label:n("Convert"),icon:(0,a.jsx)(r.EmIcons,{icon:"SwapOutlined",component:_.icons$SwapOutlined,size:16,strokeWidth:N.iconStrokeWidth}),key:"ConvertLayout",className:"em-analytics__email-convert",onClick:$t}),(p||f||g.id?.toString()===e.author?.toString())&&(N.emailDropdownMenuLock&&dt.push({label:(0,a.jsx)(ys,{element:e,context:"editor"},"Lock"),icon:e.lock?(0,a.jsx)(r.EmIcons,{icon:"UnLock",component:_.icons$UnLock,size:16,strokeWidth:N.iconStrokeWidth}):(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:16,strokeWidth:N.iconStrokeWidth}),disabled:e.isNew}),N.emailDropdownMenuRemove&&dt.push({label:n("Remove"),icon:(0,a.jsx)(r.EmIcons,{icon:"DeleteOutlined",component:_.icons$DeleteOutlined,size:16,strokeWidth:N.iconStrokeWidth}),key:"Remove",className:"em-analytics__email-remove",style:{color:"#ff4d4f"},onClick:Ne}));const Tt=e.isAmp,It=[],Dr=()=>[...Tt?[{key:"html_txt",label:`${n("Plain text")} (HTML)`,onClick:()=>ct("html")},{key:"сode_txt",label:`${n("Plain text")} (AMP)`,onClick:()=>ct("amp")}]:[{key:"plain_txt",label:n("Plain text"),onClick:()=>ct()}],{key:"markdown",label:n("Markdown"),onClick:()=>Et()}];N.exportHtmlEnabled&&It.push({key:"html",label:n("Code"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileTextOutlined",component:_.icons$FileTextOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:Tt?{children:[{key:"сode_html",label:n("AMP"),onClick:()=>Ye.isLocked?Ze("export_amp"):Ot("amp")},{key:"html_amp",label:n("HTML"),onClick:()=>Ot("html")}]}:{onClick:()=>Ot()}}),N.exportZipEnabled&&It.push({key:"zip",label:n("ZIP"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileZipOutlined",component:_.icons$FileZipOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:{onClick:()=>ce().catch(M=>{})}}),N.exportClipboardEnabled&&It.push({key:"clipboard",label:n("Clipboard"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"SnippetsOutlined",component:_.icons$SnippetsOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:Tt?{children:[{key:"clipboard_html",label:n("AMP"),onClick:()=>Ye.isLocked?Ze("export_amp"):Lt("amp")},{key:"clipboard_amp",label:n("HTML"),onClick:()=>Lt("html")}]}:{onClick:()=>Lt()}}),N.exportTextEnabled&&It.push({key:"text",label:n("Text"),icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileOutlined",component:_.icons$FileOutlined,style:Dt}),locked:I.isLocked,strokeWidth:N.iconStrokeWidth}),...I.isLocked?{onClick:()=>Ze("export_html")}:N.exportMarkdownEnabled?{children:Dr()}:Tt?{children:[{key:"сode_txt",label:n("AMP"),onClick:()=>Ye.isLocked?Ze("export_amp"):ct("amp")},{key:"html_txt",label:n("HTML"),onClick:()=>ct("html")}]}:{onClick:()=>ct()}}),N.exportOutlookEnabled&&It.push({key:"outlook",icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FileWordOutlined",component:_.icons$FileWordOutlined,style:Dt}),locked:we.isLocked,strokeWidth:N.iconStrokeWidth}),label:n("Outlook"),onClick:()=>we.isLocked?Ze("export_platforms"):St(!!Tt)}),N.exportPdfEnabled&&It.push({key:"pdf",icon:(0,a.jsx)(qt,{icon:(0,a.jsx)(r.EmIcons,{icon:"FilePdfOutlined",component:_.icons$FilePdfOutlined,style:Dt}),locked:S.isLocked,strokeWidth:N.iconStrokeWidth}),label:n("PDF"),onClick:()=>S.isLocked?Ze("export_pdf"):fn()}),N.exportPngEnabled&&It.push({key:"img",icon:(0,a.jsx)(qt,{icon:R?(0,a.jsx)(r.EmIcons,{icon:"LoadingOutlined",component:_.icons$LoadingOutlined,spin:!0,style:Dt}):(0,a.jsx)(r.EmIcons,{icon:"FileImageOutlined",component:_.icons$FileImageOutlined,style:Dt}),locked:ae.isLocked,strokeWidth:N.iconStrokeWidth}),label:n("PNG"),disabled:!ae.isLocked&&R,onClick:()=>ae.isLocked?Ze("export_png"):gn()});const ht=e.author;return(0,a.jsxs)(_.ui_kit$Space,{children:[N.emailDropdownMenuEnabled?(0,a.jsx)(_.ui_kit$Dropdown,{arrow:{pointAtCenter:!0},placement:"bottom",menu:{items:dt},children:(0,a.jsx)(_.ui_kit$Button,{type:"default",block:!1,className:"email-page-header__btn email-page-header__btn_extra",onClick:()=>{},children:(0,a.jsx)(r.EmIcons,{icon:"DotsHoriz",component:_.icons$DotsHoriz,size:18,strokeWidth:N.iconStrokeWidth})})},"Actions"):N.emailDropdownMenuImport&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Import","verb"),placement:"bottom",children:N.emailDropdownMenuImportButton?(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__editor-page__import",icon:(0,a.jsx)(r.EmIcons,{icon:"CloudUploadOutlined",component:_.icons$CloudUploadOutlined,size:16,strokeWidth:N.iconStrokeWidth}),onClick:()=>{be({event:"click",action:"import_email"}),je()},children:n("Import")}):(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__editor-page__import",type:"text",icon:(0,a.jsx)(r.EmIcons,{icon:"CloudUploadOutlined",component:_.icons$CloudUploadOutlined,size:22,strokeWidth:N.iconStrokeWidth}),onClick:()=>{be({event:"click",action:"import_email"}),je()}})}),N.emailExportEnabled&&(0,a.jsx)(_.ui_kit$Dropdown,{arrow:{pointAtCenter:!0},placement:"bottom",menu:{items:It},children:(0,a.jsx)(_.ui_kit$Button,{className:"em-analytics__email-page__export",type:"default",icon:(0,a.jsx)(r.EmIcons,{icon:"CloudDownloadOutlined",component:_.icons$CloudDownloadOutlined,size:16,strokeWidth:N.iconStrokeWidth}),children:n("Export")},"Export")},"Export"),!e.hasOwnProperty("type")&&(0,a.jsx)(_s,{disabled:fe,email:e},"Save"),!!e.hasOwnProperty("type")&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Au,{disabled:fe,rightCol:void 0,block:e,isEditableRights:p||f||g.id?.toString()===ht?.toString(),autoSaveBlockResult:t})},"Save"),(0,a.jsx)(Xp,{open:pe,codeSize:r.getCodeSize(Te),onMinimize:Bt,onDownloadAsIs:Le,onCancel:Xe}),Re&&mo(Re)&&(0,a.jsx)(lm,{integration:mo(Re),visible:!!Re,loading:et,onConfirm:jn,onCancel:On,__:n}),(0,a.jsx)(r.PlanUpgradePrompt,{open:X,sideOnOk:void 0,onCancel:()=>Ee(!1),initialSlide:Ie})]})},_r=r.createApi({reducerPath:"confirmationMailApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/",responseHandler:e=>e.text()}),endpoints:e=>({getConfirmationMail:e.query({query:({userId:t,email:n})=>({url:`?proxy_url=${encodeURIComponent(`https://webhook.latenode.com/5868/prod/1fbda9c1-3211-4b12-be45-9cd2ea73d73d?user_id=${t}&user_email=${n}`)}`})})})}),{useLazyGetConfirmationMailQuery:sf}=_r,af=()=>{const{__:e}=r.useI18n(),t=r.useNotification(),n=r.useCurrentUser(),[o]=sf(),[i,s]=(0,l.useState)(!1),c=r.usePushToDataLayer();(0,l.useEffect)(()=>{n.hasOwnProperty("email_confirmation")&&s(n.email_confirmation)},[n,i]);const d=()=>{c({event:"click",action:"click_resend_confirmation_email",user_email:n.email,user_id:n.id}),o({userId:n.id,email:n.email}).then(({data:u,error:p})=>{u?t.success(e("Confirmation email has been sent to {confirmedEmail}.").replace("{confirmedEmail}",n.email)):p&&t.error(p)})};return n?.email_confirmation||!n?.privacy_policy_agreement?null:(0,a.jsx)("div",{className:"main__ribbon",children:(0,a.jsxs)("span",{children:[(0,a.jsx)(r.EmIcons,{icon:"EmailConfirmation",component:_.icons$EmailConfirmation,size:16,style:{marginRight:10,verticalAlign:"-0.15em"}}),e("Confirmation email was sent to")," ",(0,a.jsx)("em",{children:n.email}),". ",e("Didn't receive an email?")," ",(0,a.jsxs)(_.ui_kit$Button,{type:"primary",size:"small",className:"main__ribbon-resend",style:{fontSize:16,lineHeight:1,display:"inline-flex",alignItems:"center",gap:8},onClick:d,children:[e("Resend"),(0,a.jsx)(r.EmIcons,{icon:"SendOutlined",component:_.icons$SendOutlined,size:16,style:{flexShrink:0}})]})]})})},lf=({className:e,leftBlock:t,rightBlock:n,isHeaderCodeMenuOpen:o=!1})=>{const{token:i}=(0,_.ui_kit$useToken)(),s=(0,l.useRef)(),c=r.useAppConfig();return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(af,{}),c.headerShow&&(0,a.jsx)("header",{className:(0,rt.default)("header",{[e]:e}),style:{borderColor:i.colorBorder},children:!o&&(0,a.jsx)(r.CSSTransition,{nodeRef:s,in:!o,timeout:300,classNames:"transition",children:(0,a.jsxs)("div",{className:"header__container container",children:[(0,a.jsx)("div",{className:"header__left",style:{flexGrow:1},children:t}),(0,a.jsx)("div",{className:"header__right",children:(0,a.jsx)(_.ui_kit$Space,{size:10,children:n})})]})})})]})},cf=e=>{},Ts=h.createIdentifier$1("canvas.headerFlow");function df(e){const t=(0,l.useCallback)(n=>e?e.subscribe(n):()=>{},[e]);return(0,l.useSyncExternalStore)(t,()=>e?.isReady()===!0)}var Is=({email:e,isCollaborationEditor:t})=>{const[n]=_.ui_kit$Form.useForm(),{__:o}=r.useI18n();let i=r.useDispatch();const s=r.useEmailAttributesWriter(),c=r.useAppNavigate(),d=r.useOpenPlanCatalog(),u=qi("header"),p=r.useCurrentUser(),f=r.useContainer().getInstance(Ts),g=r.useProjectData(),{owner:y,admin:m}=Qn(),{token:E}=(0,_.ui_kit$useToken)(),k=r.useAppConfig(),w=r.usePushToDataLayer(),v=(0,l.useRef)(),x=(0,l.useRef)(),P=(0,l.useRef)(),K=r.useEventEmitter(h.events.ON_PREVIOUSBUTTON_CLICK_ID),J=r.useEventEmitter(h.events.ON_PREHEADER_CHANGED_ID),N=r.useEventEmitter(h.events.ON_SUBJECT_CHANGED_ID),L=r.useSelector(r.selectCodeModeDirection),A=e.hasOwnProperty("type")?r.BLOCK:r.EMAIL,O=r.useSelector(r.selectElementSettings$1),z=r.useSelector(r.selectElementSettings),B=A==="email"?O:z,U=r.useSelector(r.selectIsCodeMode),[de,me]=(0,l.useState)(!1),[H,Z]=(0,l.useState)(!1),[De,ve]=(0,l.useState)(!1),et=(0,l.useCallback)(()=>ve(!1),[]),be=(0,l.useCallback)(()=>{ve(!1),d()},[d]),fe=Gi("email_generate"),Y=fe.exceeded?r.getLimitUpgradePresetDefinition(fe.exceeded.presetId):null;(0,l.useEffect)(()=>{const I=!!B?.type&&(B?.type===r.ELEMENT_TYPES.TEXT||B?.type===r.ELEMENT_TYPES.LINK||B.type===r.ELEMENT_TYPES.BUTTON)&&U&&L!=="bottom";me(I),i(r.setHeaderCodeMenuOpen(I))},[B,L,U]);const pe=(0,l.useCallback)(()=>{w({event:"click",action:"click_back_button",entity_type:A==="block"?"block":"email",entity_id:e?.id,project_id:e?.project||g?.id,context:"editor"}),K.fire(e)},[c,K,e,g?.id,w,A]),{document:ie}=r.useCurrentSession(),se=df(ie);r.usePrevious(([I])=>{se&&I!==e.subject&&N.fire(e.subject)},[e.subject,se]);const Ae=(0,l.useCallback)(I=>{const S=I.target.value;N.fire(S)},[N]),Te=(0,l.useCallback)(I=>{const S=I.target.value;J.fire(S)},[J]);r.usePrevious(([I])=>{se&&I!==e.preheader&&J.fire(e.preheader)},[e.preheader,se]);const Fe=(0,l.useCallback)((I,S="?")=>{I.subject?.length,I.preheader?.length,n.setFieldValue("subject",I.subject??""),n.setFieldValue("preheader",I.preheader??"")},[n]),X=(0,l.useRef)(void 0);(0,l.useEffect)(()=>{const I=e?.renderGuid??(e?.id!=null?String(e.id):void 0);!se||!I||X.current===I||(X.current=I,Fe(e,"identity"))},[se,e,Fe]);const Ee=(0,l.useCallback)(I=>{const S=I.target.value.trim();s({subject:S})},[s]),Ie=r.useEvent(h.events.BEFORE_SAVE_EMAIL),ge=(0,l.useCallback)(async I=>{const S=x.current?.input;if(document.activeElement===S){const we=S.value.trim();we!==I.subject&&(I.subject=we,s({subject:we}))}const ae=P.current?.input;if(document.activeElement===ae){const we=ae.value.trim();we!==I.preheader&&(I.preheader=we,s({preheader:we}))}await f?.whenDelivered()},[f,s]);(0,l.useEffect)(()=>{const I=Ie(ge);return()=>I.dispose()},[Ie,ge]);const Re=(0,l.useCallback)(I=>{const S=I.target.value.trim();s({preheader:S})},[s]),Ue=r.useEvent(h.events.ON_HEADER_APPLIED_ID);(0,l.useEffect)(()=>{const I=Ue(({field:S,value:ae})=>{n.setFieldValue(S,ae)});return()=>I.dispose()},[Ue,n]),cf(e.title===null?o("New email title"):e.title);const C=(0,l.useCallback)(()=>{i(r.setActiveSettingsTab(r.AICHAT)),setTimeout(()=>{const I=document.querySelector('li.ai-response-change-context[role="theme-and-preheader-generator"]');I&&I.click()},100)},[i]),T=(0,l.useCallback)(()=>{fe.isLocked?fe.state.state==="locked_by_limit"&&fe.exceeded?ve(!0):Z(!0):C()},[fe,C]),R=(0,a.jsx)(a.Fragment,{children:(0,a.jsxs)(_.ui_kit$Space,{ref:v,size:10,children:[k.headerArrowBackVisible&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Back"),placement:"left",children:(0,a.jsx)(_.ui_kit$Button,{type:"text",icon:(0,a.jsx)(r.EmIcons,{icon:"ArrowLeftOutlined",component:_.icons$ArrowLeftOutlined,size:22,strokeWidth:k.iconStrokeWidth}),onClick:pe,shape:"circle"})}),(0,a.jsx)("div",{children:(k.headerTitleVisible||k.headerPreheaderVisible)&&(0,a.jsxs)(_.ui_kit$Form,{form:n,layout:"vertical",name:"subject_preheader_form",autoComplete:"off",initialValues:{subject:"",preheader:""},children:[k.headerTitleVisible&&(0,a.jsx)("div",{style:{marginTop:se?-3:0},children:(0,a.jsxs)(_.ui_kit$Space,{style:{width:"100%"},align:"baseline",size:12,children:[(0,a.jsx)("div",{className:"subject_preheader_form__title",children:o("Subject")}),se?(0,a.jsxs)("div",{className:"ant-page-header-heading",children:[(0,a.jsx)(_.ui_kit$Form.Item,{name:"subject",noStyle:!0,children:(0,a.jsx)(_.ui_kit$Input,{className:"ant-page-header-heading-title",ref:x,placeholder:o("Enter subject line here"),variant:"borderless",autoComplete:"off","data-lpignore":"true","data-1p-ignore":"","data-bwignore":"true","data-form-type":"other",onChange:Ae,onPressEnter:Ee,onBlur:I=>{Ee(I),document.querySelector(".ant-page-header-heading-title").closest(".ant-page-header-heading").classList.remove("focus")},onFocus:()=>{document.querySelector(".ant-page-header-heading-title").closest(".ant-page-header-heading").classList.add("focus")},disabled:k.lockPreheaderAndTitle})}),k.aiAssistentEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Generate with AI"),children:(0,a.jsx)(r.EmIcons,{icon:"AI",component:_.icons$AI,size:12,strokeWidth:k.iconStrokeWidth,onClick:T})})]}):(0,a.jsx)(_.ui_kit$Skeleton.Input,{active:!0,size:16,style:{width:"40%",marginTop:3}})]})}),k.headerPreheaderVisible&&(0,a.jsx)("div",{children:(0,a.jsxs)(_.ui_kit$Space,{style:{width:"100%"},align:"baseline",size:12,children:[(0,a.jsx)("div",{className:"subject_preheader_form__title",children:o("Preheader")}),se?(0,a.jsxs)("div",{className:"ant-page-header-heading ant-page-header-heading_preheader",children:[(0,a.jsx)(_.ui_kit$Form.Item,{name:"preheader",noStyle:!0,children:(0,a.jsx)(_.ui_kit$Input,{className:"ant-page-header-heading-preheader",ref:P,placeholder:o("Enter preheader here"),variant:"borderless",autoComplete:"off","data-lpignore":"true","data-1p-ignore":"","data-bwignore":"true","data-form-type":"other",onChange:Te,onPressEnter:Re,onBlur:I=>{Re(I),document.querySelector(".ant-page-header-heading-preheader").closest(".ant-page-header-heading").classList.remove("focus")},onFocus:()=>{document.querySelector(".ant-page-header-heading-preheader").closest(".ant-page-header-heading").classList.add("focus")},disabled:k.lockPreheaderAndTitle})}),k.aiAssistentEnabled&&(0,a.jsx)(_.ui_kit$Tooltip,{title:o("Generate with AI"),children:(0,a.jsx)(r.EmIcons,{icon:"AI",component:_.icons$AI,size:12,strokeWidth:k.iconStrokeWidth,onClick:T})})]}):(0,a.jsx)(_.ui_kit$Skeleton.Input,{active:!0,size:16,style:{width:"80%",marginTop:2}})]})})]})})]})}),D=(0,a.jsxs)(a.Fragment,{children:[k.emailIdShow&&!!e.id&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"email-page-header__email-id",children:"ID"+e.id}),(0,a.jsx)(_.ui_kit$Divider,{orientation:"vertical"})]}),(0,a.jsx)(ps,{emailElement:e,isCollaborationEditor:t}),k.commandButtonsEnabled&&(0,a.jsxs)(a.Fragment,{children:[e.lock?(0,a.jsx)(r.EmIcons,{icon:"Lock",component:_.icons$Lock,size:18,strokeWidth:k.iconStrokeWidth,className:(0,rt.default)("lock-icon",{"lock-icon__disabled":!(y||m||p.id?.toString()===e.author?.toString())}),style:{color:E.colorPrimary,verticalAlign:"sub"}},"Lock"):null,(0,a.jsx)(of,{email:e,isHeaderCodeMenuOpen:de},"Buttons")]})]});return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(lf,{className:"email-pane__header",leftBlock:u?R:null,rightBlock:u?D:null,isHeaderCodeMenuOpen:de}),(0,a.jsx)(r.PlanUpgradePrompt,{open:H,onCancel:()=>Z(!1),initialSlide:9}),Y&&fe.exceeded?(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(oo,{open:De,onClose:et,title:o(Y.titleKey),subtitle:o(Y.subtitleKey),usageResource:Y.usageResource,previousDisplay:r.presetLimitDisplay(fe.exceeded.previousLimit),nextDisplay:r.presetLimitDisplay(fe.exceeded.nextLimit),onChangePlan:be})}):null]})};Is.propTypes={};function uf(e){const t=r.parseEmBlockVersion(e);if(!t)return e;const n=o=>String(o).padStart(2,"0");return`${n(t.getDate())}.${n(t.getMonth()+1)}.${t.getFullYear()} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}var pf=({open:e,blocks:t,projectId:n,onClose:o})=>{const{__:i,_n:s}=r.useI18n(),c=r.useSendPostMessage(),d=r.useNotification(),[u,p]=(0,l.useState)({});(0,l.useEffect)(()=>{e&&p(Object.fromEntries(t.map(m=>[m.emBlockId,!0])))},[e,t]);const f=(0,l.useMemo)(()=>Object.values(u).filter(Boolean).length,[u]),g=(m,E)=>{p(k=>({...k,[m]:E}))},y=()=>{const m=t.filter(E=>u[E.emBlockId]);m.length&&(m.forEach(E=>{c({operation:r.EVENT_TYPES.SANDBOX_GLOBAL_BLOCK_REPLACE,settings:{emBlockId:E.emBlockId,blockHTML:E.savedHtml,type:"project",...n?{project:String(n)}:{}}})}),d.success({message:i("Updated")+" "+m.length+" "+s("block","blocks",m.length),placement:"bottomRight"}),o())};return(0,a.jsxs)(_.ui_kit$Modal,{title:(0,a.jsx)("div",{className:"ant-modal-title",children:i("Update global blocks")}),open:e,onOk:y,onCancel:o,footer:(0,a.jsxs)("div",{className:"update-global-blocks-modal__footer",children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",onClick:o,children:i("Cancel")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",disabled:f===0,onClick:y,children:i("Update")})]}),children:[(0,a.jsx)("div",{className:"update-global-blocks-modal__hint",children:i("These global blocks have a newer saved version. Select the ones to update in the template.")}),(0,a.jsx)("div",{className:"update-global-blocks-modal__list",children:t.map(m=>(0,a.jsxs)("div",{className:"update-global-blocks-modal__row",children:[(0,a.jsx)(_.ui_kit$Switch,{checked:!!u[m.emBlockId],onChange:E=>g(m.emBlockId,E)}),(0,a.jsxs)("span",{className:"update-global-blocks-modal__title",title:m.title,children:[m.title,(0,a.jsxs)("span",{className:"update-global-blocks-modal__version",children:[i("Version of")," ",uf(m.savedVersion)]})]}),m.instances>1&&(0,a.jsxs)("span",{className:"update-global-blocks-modal__count",children:[m.instances," ",s("instance","instances",m.instances)]})]},m.emBlockId))})]})};function mf(e){const t=new Map;return e?.trim()&&new DOMParser().parseFromString(e,"text/html").querySelectorAll('[em="block"][em-block-id]').forEach(n=>{const o=n.getAttribute("em-block-id");if(!o)return;const i=n.getAttribute("em-block-version")??void 0,s=t.get(o);s?(s.versions.add(i),s.count+=1):t.set(o,{versions:new Set([i]),count:1})}),t}function ff(e,t){const n=mf(e);if(!n.size||!t?.length)return[];const o=[];for(const i of t){if(!i.global_block||!i.id||!i.html)continue;const s=String(i.id),c=n.get(s);if(!c)continue;const d=r.readRootEmBlockAttrs(i.html).emBlockVersion;d&&[...c.versions].some(u=>u!==d)&&o.push({emBlockId:s,title:i.title?.trim()||s,savedHtml:i.html,savedVersion:d,templateVersion:[...c.versions][0],instances:c.count})}return o}var As="em-block-id";function gf({projectId:e,document:t}){const n=r.useEvent(h.events.ON_EMAIL_INIT_ID),o=r.useHeadless(),[i,s]=(0,l.useState)([]),[c,d]=(0,l.useState)(!1),[u,p]=(0,l.useState)(null),f=(0,l.useCallback)(E=>t?.subscribe(E)??(()=>{}),[t]),g=(0,l.useSyncExternalStore)(f,()=>!!t?.getContent().includes(As)),{data:y}=r.blocksApi.endpoints.getBlocks.useQuery(r.projectBlocksArgs(e),{skip:!e||!g}),m=(0,l.useRef)(!1);return(0,l.useEffect)(()=>{g&&m.current&&t&&(m.current=!1,p(t.getContent()))},[g,t]),(0,l.useEffect)(()=>{const E=new h.Disposable;return E.addDisposable(n(k=>{if(k?.reset)return;const w=k?.html??"",v=w.includes(As);m.current=!v,p(v?w:null)})),()=>E.dispose()},[n]),(0,l.useEffect)(()=>{if(u==null||!y)return;if(o){p(null);return}const E=ff(u,y);E.length&&(s(E),d(!0)),p(null)},[u,y,o]),{outdatedBlocks:i,isOpen:c,close:(0,l.useCallback)(()=>d(!1),[])}}var hf=({open:e,html:t,emBlockId:n,onSaveAsNew:o,onClose:i})=>{const{__:s}=r.useI18n(),c=r.useSendPostMessage(),d=r.useNotification(),[u]=r.useEditBlockMutation(),[p,f]=(0,l.useState)(!1),g=async()=>{if(!n||!t){i();return}f(!0);const y=new Date,m=r.formatEmBlockVersion(y),E=r.injectEmBlockIdIntoBlockHtml(t,String(n),y),k=await u({blockId:String(n),html:E});if(f(!1),"error"in k&&k.error){d.error({message:s("Failed to update the global block."),placement:"bottomRight"});return}c({operation:r.EVENT_TYPES.SANDBOX_EBLOCK_SET_EM_BLOCK_ID,settings:{emBlockId:String(n),emBlockVersion:m}}),d.success({message:s("The global block was updated."),placement:"bottomRight"}),i()};return(0,a.jsx)(_.ui_kit$Modal,{title:(0,a.jsx)("div",{className:"ant-modal-title",children:s("Saving changes in the block")}),open:e,onCancel:i,footer:(0,a.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",disabled:p,onClick:o,children:s("Create new block")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",loading:p,onClick:g,children:s("Update current block")})]}),children:(0,a.jsx)("div",{children:s("This is a global block. You can create a new one to apply changes only in this email, or update the current one — then the changes will be applied everywhere this block is used.")})})},_f=(function(){var e=window.__useblocks__;if(e&&e.assetUrl)return e.assetUrl("converter-intro.bf4ee74d750b35ae2c10.png");if(e&&e.publicPath)try{return new URL("static/media/converter-intro.bf4ee74d750b35ae2c10.png",e.publicPath).href}catch{}try{return new URL("/static/media/converter-intro.bf4ee74d750b35ae2c10.png",typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?window.location.href:"").href}catch{return"/static/media/converter-intro.bf4ee74d750b35ae2c10.png"}})(),yf={closable:!1},vf=_f,bf=({open:e,onConfirm:t,onCancel:n,neverSuggestAgain:o,onNeverSuggestAgainChange:i})=>{const{__:s}=r.useI18n();return(0,a.jsx)(_.ui_kit$Modal,{className:"convert-layout-modal",title:(0,a.jsx)("div",{className:"convert-layout-modal__title",children:s("Template conversion")}),open:e,onOk:t,onCancel:n,mask:yf,width:480,footer:(0,a.jsxs)("div",{className:"convert-layout-modal__footer",style:{display:"flex",flexDirection:"column",gap:16},children:[(0,a.jsx)(_.ui_kit$Switch,{size:"small",checked:o,onChange:i,label:s("Don't suggest again"),labelSize:"small"}),(0,a.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",onClick:n,children:s("Cancel")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",onClick:t,children:s("Convert")})]})]}),children:(0,a.jsxs)("div",{className:"convert-layout-modal__content",style:{display:"flex",flexDirection:"column",alignItems:"center",gap:24,padding:"0 8px",overflow:"hidden"},children:[(0,a.jsx)("div",{className:"convert-layout-modal__text convert-layout-modal__intro-text",style:{textAlign:"center"},children:s("This layout was not created in our editor. Convert it to unlock full editing capabilities: easily change texts, replace images, and manage blocks.")}),(0,a.jsx)("img",{src:vf,alt:"Converter Intro",className:"convert-layout-modal__image",style:{display:"block",width:"100%",maxWidth:"100%",height:"auto",borderRadius:8}})]})})},Ef={closable:!1},Sf=({open:e,message:t,onRetry:n,onCancel:o})=>{const{__:i}=r.useI18n();return(0,a.jsx)(_.ui_kit$Modal,{title:(0,a.jsx)("div",{className:"ant-modal-title",children:i("Conversion failed")}),open:e,onOk:n,onCancel:o,mask:Ef,footer:(0,a.jsxs)("div",{className:"convert-layout-modal__footer",children:[(0,a.jsx)(_.ui_kit$Button,{size:"large",onClick:o,children:i("Cancel")}),(0,a.jsx)(_.ui_kit$Button,{size:"large",type:"primary",onClick:n,children:i("Try again")})]}),children:(0,a.jsxs)("div",{className:"convert-layout-modal__text",children:[i("Something went wrong during layout conversion. You can try running the conversion again."),t?(0,a.jsx)("div",{className:"convert-layout-modal__error-details",children:t}):null]})})},wf=({open:e,progress:t})=>{const{__:n}=r.useI18n();return e?(0,a.jsx)("div",{className:"conversion-overlay",children:(0,a.jsxs)("div",{className:"conversion-overlay__content",children:[(0,a.jsx)(_.ui_kit$Spin,{size:"large"}),(0,a.jsx)("div",{className:"conversion-overlay__title",children:n("Converting layout…")}),(0,a.jsx)("div",{className:"conversion-overlay__hint",children:n("This may take several minutes. Please keep this tab open.")}),(0,a.jsx)(_.ui_kit$Progress,{className:"conversion-overlay__progress",percent:Math.round(t),status:"active",strokeColor:r.emCssVar("colorPrimary")})]})}):null},yr=r.createApi({reducerPath:"layoutConverterApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({createConvertJob:e.mutation({query:({html:t})=>({url:"/ai/converter/jobs",method:"POST",body:{html:t}})}),getConvertJobStatus:e.query({query:t=>({url:`/ai/converter/jobs/${t}`,method:"GET"})})})}),{useCreateConvertJobMutation:kf,useLazyGetConvertJobStatusQuery:Cf}=yr;function Tf(){try{return window.localStorage.getItem(r.LOCAL_STORAGE_ITEMS.em_layout_convert_never_suggest)==="true"}catch{return!1}}function If(e){try{e?window.localStorage.setItem(r.LOCAL_STORAGE_ITEMS.em_layout_convert_never_suggest,"true"):window.localStorage.removeItem(r.LOCAL_STORAGE_ITEMS.em_layout_convert_never_suggest)}catch{}}function xs(e){return e==="beefree"?(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/79749848.js")).then(t=>t.convertBeeFreeToEmailMaker),void 0,{}.url):(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/e0d71533.js")).then(t=>t.convertStripoToEmailMaker),void 0,{}.url)}var Af=5,Ps=95,xf=35e3,Pf=1e3,Rf=e=>new Promise(t=>setTimeout(t,e));function jf(e,t){if(e&&typeof e=="object"){const n=e,o=n.data;if(o&&typeof o=="object"){const i=o.error;if(typeof i=="object"&&i?.message)return i.message;if(typeof i=="string"&&i)return i;if(o.message)return o.message}if(typeof o=="string"&&o)return o;if(n.error)return n.error;if(n.message)return n.message}return t}function Of(){const{__:e}=r.useI18n(),t=r.useContentReplacer(),n=r.useNotification(),o=vs(),{aiLayoutConverterEnabled:i,anyConverterEnabled:s}=o,c=r.useHeadless(),d=r.useEvent(h.events.ON_EMAIL_INIT_ID),u=r.useEvent(h.events.ON_LAYOUT_CONVERT_REQUEST_ID),[p]=kf(),[f]=Cf(),[g,y]=(0,l.useState)(Tf),m=(0,l.useRef)(g),E=(0,l.useCallback)(ie=>{m.current=ie,y(ie),If(ie)},[]),[k,w]=(0,l.useState)(!1),[v,x]=(0,l.useState)(!1),[P,K]=(0,l.useState)(0),[J,N]=(0,l.useState)(!1),[L,A]=(0,l.useState)(""),O=(0,l.useRef)(""),z=(0,l.useRef)(null),B=(0,l.useRef)(null),U=(0,l.useRef)(!1),de=(0,l.useRef)({cancelled:!0}),me=(0,l.useRef)(null);(0,l.useEffect)(()=>{U.current=v},[v]);const H=(0,l.useCallback)(()=>{me.current!==null&&(clearInterval(me.current),me.current=null)},[]),Z=(0,l.useCallback)(()=>{H();const ie=Date.now();me.current=setInterval(()=>{const se=Date.now()-ie,Ae=Ps*(1-Math.exp(-se/xf));K(Te=>Math.max(Te,Math.min(Ps,Ae)))},Pf)},[H]),De=(0,l.useCallback)(ie=>{ie&&(t(ie,{undoable:!0}),B.current=ie)},[t]),ve=(0,l.useCallback)(async ie=>{const se={cancelled:!1};de.current=se,N(!1);const Ae=z.current;if(Ae==="beefree"||Ae==="stripo"){try{const Te=await xs(Ae),Fe=se.cancelled?"":Te(ie);if(Fe&&!se.cancelled){De(Fe),n.success({message:r.isUseBlocksBuild()?e("Layout converted to Blocks format"):e("Layout converted to EmailMaker format"),placement:"bottomRight"});return}}catch{}if(!i){se.cancelled||(A(e("Layout conversion failed")),N(!0));return}}if(i){x(!0),K(0),Z();try{const Te=await p({html:ie}).unwrap();if(se.cancelled)return;let Fe=Te.retry_after>0?Te.retry_after:Af;for(;!se.cancelled;){if(await Rf(Fe*1e3),se.cancelled)return;const X=await f(Te.job_id).unwrap();if(se.cancelled)return;if(X.retry_after&&X.retry_after>0&&(Fe=X.retry_after),X.status==="completed"){H(),K(100),De(X.html??""),n.success({message:r.isUseBlocksBuild()?e("Layout converted to Blocks format"):e("Layout converted to EmailMaker format"),placement:"bottomRight"}),setTimeout(()=>{se.cancelled||(x(!1),K(0))},400);return}if(X.status==="failed")throw new Error(X.error?.message||e("Layout conversion failed"))}}catch(Te){if(se.cancelled)return;H(),x(!1),K(0),A(jf(Te,e("Layout conversion failed"))),N(!0)}}},[e,i,De,p,n,f,Z,H]),et=(0,l.useCallback)(()=>{w(!1);const ie=O.current;ie&&ve(ie)},[ve]),be=(0,l.useCallback)(()=>{w(!1),B.current=O.current},[]),fe=(0,l.useCallback)(()=>{N(!1);const ie=O.current;ie&&ve(ie)},[ve]),Y=(0,l.useCallback)(()=>{N(!1),B.current=O.current},[]),pe=(0,l.useCallback)((ie,se=!1)=>{const Ae=bs(ie,o);if(s&&!c&&Ae&&!U.current){if(se)B.current=null;else{if(m.current)return;if(B.current===ie)return}O.current=ie,z.current=Ae,Ae!=="ai"&&xs(Ae).catch(()=>{}),w(!0)}},[s,o,c]);return(0,l.useEffect)(()=>{if(!s)return;const ie=new h.Disposable;return ie.addDisposable(d(se=>{se?.reset||pe(se?.html??"")})),()=>ie.dispose()},[s,d,pe]),(0,l.useEffect)(()=>{if(!s)return;const ie=new h.Disposable;return ie.addDisposable(u(se=>{pe(se?.html??"",!0)})),()=>ie.dispose()},[s,u,pe]),(0,l.useEffect)(()=>()=>{de.current.cancelled=!0,H()},[H]),{isPromptOpen:k,isConverting:v,progress:P,isErrorOpen:J,errorMessage:L,confirmConversion:et,cancelPrompt:be,retryConversion:fe,closeError:Y,neverSuggestAgain:g,setNeverSuggestAgain:E}}var Lf=6e4,Rs=new Map;function Mf(e){const t=e?String(e):"",n=Rs.get(t);if(n&&(Rs.delete(t),!(Date.now()-n.at>Lf)))return n.promise}var ho={data:void 0,isSuccess:!1,isError:!1,error:void 0,isLoading:!1};function Nf(e){const t=r.useStore(),n=(0,l.useRef)(t);n.current=t;const[o,i]=(0,l.useState)(ho),s=e?String(e):void 0;return(0,l.useEffect)(()=>{if(!s){i(ho);return}let c=!1;return i({...ho,isLoading:!0}),(Mf(s)??r.resolveEmailPort(h.getContainer(n.current)).readEmail(s)).then(d=>{c||i({data:d??void 0,isSuccess:!0,isError:!1,error:void 0,isLoading:!1})}).catch(d=>{c||i({data:void 0,isSuccess:!1,isError:!0,error:d,isLoading:!1})}),()=>{c=!0}},[s]),o}var ob=2;function Df(){const e=r.useProjectData()?.id,t=!0,{data:n,isError:o,isFetching:i,refetch:s}=r.useGetProjectPlanQuery(e,{skip:t}),[c,d]=(0,l.useState)(0),u=(0,l.useRef)(!1),p=!!o,f=c>=2,g=(0,l.useCallback)(()=>{u.current=!1,d(0),s()},[s]);(0,l.useEffect)(()=>{},[p,i,s,c,t]),(0,l.useEffect)(()=>{},[p,e,f,t]);const y="ready";return(0,l.useMemo)(()=>({status:y,retry:g}),[y,g])}var ib=300,Ff=h.createIdentifier$1("prewarm.queue");function Bf(e){const t=[];let n=!1,o=!1,i;const s=()=>{i&&(i.unwatch(),e.clearTimer(i.timer),i=void 0)},c=()=>{const p=t.shift();if(!p)return;o=!0;const f=()=>{o=!1,u()};p.start().then(f,f)},d=()=>{s(),e.idle(()=>{if(!(o||t.length===0)){if(e.activity.inFlight()>0){u();return}c()}})};function u(){if(!n||o||i||t.length===0)return;const p=()=>e.setTimer(d,300),f={timer:e.activity.inFlight()===0?p():void 0,unwatch:e.activity.watch(()=>{e.clearTimer(f.timer),f.timer=e.activity.inFlight()===0?p():void 0})};i=f}return e.whenVisible(()=>{n=!0,u()}),{add(p){t.some(f=>f.name===p.name)||(t.push(p),u())},remove(p){const f=t.findIndex(g=>g.name===p);f>=0&&t.splice(f,1),t.length===0&&s()}}}function $f(e){return e.getOrCreateInstance(Ff,()=>Bf({activity:h.getNetworkActivity(e),whenVisible:t=>Ht(e).whenVisible(t),idle:Xt,setTimer:(t,n)=>window.setTimeout(t,n),clearTimer:t=>window.clearTimeout(t)}))}function Uf({projectId:e,project:t,emailProjectId:n,parentEmailId:o}){const i=r.useContainer(),s=r.useAppDispatch(),d=!!r.useCookieManager().get(r.APP_COOKIES.em_token);(0,l.useEffect)(()=>{const u=$f(i),p=[],f=[],g=(m,E)=>{f.push(m),u.add({name:m,start:()=>{const k=E();return p.push(k),Promise.resolve(k)}})},y=r.parentEmailSource(o);return y&&g("blocks.parentEmail",()=>s(r.blocksApi.endpoints.getParentEmailBlocks.initiate(r.parentEmailBlocksArgs(y)))),g("blocks.template",()=>s(r.blocksApi.endpoints.getTemplateBlocks.initiate(r.templateBlocksArgs()))),e&&g("blocks.list",()=>s(r.blocksApi.endpoints.getBlocks.initiate(r.projectBlocksArgs(e)))),g("blocks.schema",()=>s(r.blocksApi.endpoints.getBlocksSchema.initiate(void 0))),t?.id&&g("blocks.tags",()=>s(r.taxonomiesApi.endpoints.getTerms.initiate({project:t,kind:r.BLOCK_TAGS}))),()=>{f.forEach(m=>u.remove(m)),p.forEach(m=>m.unsubscribe())}},[i,s,e,t,n,o,d])}var _o="AUTOSAVE_RECOVERY";function zf(e,t,n=!1,o){const i=t?.get().serverId??void 0,{__:s}=r.useI18n(),c=r.useNotification(),d=r.useAppConfig(),u=r.useSelector(r.selectMonacoFocusing),p=r.useContainer(),f=p?.getInstance(Ts),g=(0,l.useRef)(0),y=r.useSelector(r.selectIsPanelHistoryCollapsed),m=r.useSelector(r.selectActiveSettingsTab),E=r.useDispatch(),k=(0,l.useSyncExternalStore)((0,l.useCallback)(L=>o?.subscribe(L)??(()=>{}),[o]),()=>o?.recoveryFacts()),w=d?.revisionService===!0,v=k?.isRecovering===!0,x=k?.applied,P=(0,l.useCallback)(()=>{E(r.markAppearanceNeedsUpdate());const L=e?.renderGuid,A=e?.preheader,O=e?.subject;L&&(A||O)&&f?.reassert({...A?{preheader:A}:{},...O?{subject:O}:{}})},[E,f,e?.preheader,e?.subject,e?.title,e?.common_styles,e?.renderGuid,t,o]);(0,l.useEffect)(()=>()=>{clearTimeout(g.current),o?.endForcedHeaders()},[i,o]),(0,l.useEffect)(()=>{w&&v&&c.info({key:_o,title:s("Loading latest changes..."),duration:0})},[w,v,c,s]);const K=(0,l.useRef)({emailId:void 0,seq:0});(0,l.useEffect)(()=>{if(!x||k?.emailId!==i||(K.current.emailId!==i&&(K.current={emailId:i,seq:0}),x.seq<=K.current.seq))return;K.current={emailId:i,seq:x.seq},P();const{phase:L}=x;!w||L==="normal"||(L==="found"?c.success({key:_o,title:s("Changes loaded"),duration:3}):L==="timeout"?c.warning({key:_o,title:s("Locally saved version applied"),description:s("Syncing with the server in the background..."),duration:5}):L==="bg"&&c.info({key:"AUTOSAVE_BG_SYNCED",title:s("Email synced with the server"),duration:3}))},[w,x,k?.emailId,i,P,c,s]),(0,l.useEffect)(()=>{if(!n)return;const L=A=>{A.preventDefault()};return window.addEventListener("beforeunload",L),()=>window.removeEventListener("beforeunload",L)},[n]);const J=!y||u||m==="Discuss",N=p?r.provideAutosaveUiFacts(p):void 0;(0,l.useEffect)(()=>{N?.set({...N.get()??{isUserBusy:!1,saveContext:{}},isUserBusy:J})},[N,J])}var Gf=class extends Error{label;timeoutMs;constructor(e,t){super(`[${e}] timed out after ${t}ms`),this.name="OperationTimeoutError",this.label=e,this.timeoutMs=t}};function Wf(e,t,n){return t<=0?e:new Promise((o,i)=>{let s=!1,c;const d=u=>{s||(s=!0,c!==void 0&&(clearTimeout(c),c=void 0),u())};c=setTimeout(()=>{d(()=>i(new Gf(n,t)))},t),e.then(u=>{d(()=>o(u))},u=>{d(()=>i(u))})})}var Hf=2,vr=Symbol("sandbox:frame-replaced");function an(e,t,n,o,i,s,c){const d=`sandbox:${t}`,u=s?.getSandboxTimeoutMs(t)??r.DEFAULT_SANDBOX_OP_TIMEOUT_MS[t],p=()=>{let E=Wf(e.sendAsync(n,o),u,d);return E=h.raceWithAbortSignal(E,s?.signal),r.logShowPipelineWait(d,E,i)};if(t==="INIT_START"&&Ki(e)){const E=s?.getSandboxReadyTimeoutMs()??2e4,k=e,w=v=>{const x=Yi(k,E,s?.signal);return r.logShowPipelineWait("sandbox:INIT_START:ready-wait",x,i).then(()=>{if(!c||v<=0)return p();const P=c.getGeneration();let K;const J=new Promise((L,A)=>{K=c.onChange(()=>{c.getGeneration()!==P&&A(vr)})}),N=p();return N.catch(()=>{}),Promise.race([N,J]).finally(()=>K?.()).catch(L=>{if(L!==vr)throw L;return{...i},w(v-1)})})};return w(Hf)}if(!c)return p();const f=c.getGeneration();let g;const y=new Promise((E,k)=>{g=c.onChange(()=>{c.getGeneration()!==f&&k(vr)})}),m=p();return m.catch(()=>{}),Promise.race([m,y]).finally(()=>g?.()).catch(E=>{throw E===vr&&{...i},E})}function js(e,t,n,o){return{html:e,guid:t,...Object.keys(n).length>0?{templateDirectivesPolicy:n}:{},...o!==void 0?{rev:o}:{}}}var Os="self-init:";function qf(e){return e.startsWith(Os)}function Ls(e,t){const n=e.getActiveShowRequest();return qf(t)?n===null:n?.showId===t&&e.hasPendingShow(t)}function Vf(e){const t=()=>e.initPipeline(),n=e.messageService,o=()=>e.waitScope?.()??t();let i="";const s=()=>e.readDocument()?r.readDocumentContent(e.readDocument()):i,c=()=>on(e.container).editorPolicy,d=()=>e.readEmail(),u=()=>{const p=d();return{...p,id:e.isTemplate()||p.isNew?void 0:p.id,html:s()}};return{readContent:s,publicEmail:u,sendInitStart:()=>an(n,"INIT_START",r.EVENT_TYPES.SANDBOX_INIT_START,{guid:d().renderGuid},void 0,o()),sendInited:()=>an(n,"INITED",r.EVENT_TYPES.SANDBOX_INITED,{guid:d().renderGuid},void 0,o()),async sendContent(){const p=d(),{html:f,hasBrowserExtensionArtifacts:g}=r.prepareEmailHtmlForEditor(p?.html||"");g&&e.events.browserExtensionDetected(),r.loadDocumentContent(e.readDocument(),f),i=f,await an(n,"SET_ENTITY",r.EVENT_TYPES.SANDBOX_SET_ENTITY,js(s(),p.renderGuid,c(),e.readDocument()?.get().version),{guid:p.renderGuid,emailId:p.id??null},o())},refreshContent:()=>an(n,"SET_ENTITY",r.EVENT_TYPES.SANDBOX_SET_ENTITY,js(s(),d().renderGuid,c(),e.readDocument()?.get().version),void 0,o()),sendPreheader:async()=>{const p=d();if(p.preheader!==void 0)return an(n,"PREHEADER",r.EVENT_TYPES.SANDBOX_PREHEADER_UPDATE,{value:p.preheader,guid:p.renderGuid,force:!0},void 0,o())},sendSubject:async()=>{const p=d();if(p.subject!==void 0)return an(n,"SUBJECT",r.EVENT_TYPES.SANDBOX_SUBJECT_UPDATE,{value:p.subject,guid:p.renderGuid,force:!0},void 0,o())},revealFilled:()=>e.revealFilled?.()??Promise.resolve(),showFilled:p=>e.showFilled?.(p),readTarget:()=>e.readTarget?.(),fireWillInit:()=>e.events.willInit(u()),fireInit(p,f){if(!Ls(t(),p)){t().getActiveShowRequest()?.showId;return}const g=d();g.id,g.renderGuid,t().completeShow(p),r.writeEmailAttributes(e.readDocument(),{is_inited:!0},{source:"system"});const y=u();return f&&(y.reset=!0),e.events.inited(y)},fireEmailChanged(){e.events.emailChanged(u())},fireContentChanged(){e.events.contentChanged(s())}}}function Kf(e){const t=()=>e.initPipeline();let n=!1,o,i,s,c=0,d;const u=Vf({...e,waitScope:()=>({getSandboxTimeoutMs:w=>t().getSandboxTimeoutMs(w),getSandboxReadyTimeoutMs:()=>t().getSandboxReadyTimeoutMs(),signal:d?.signal??t().signal})});let p;const f=(w,v)=>{if(p===w)return;p=w;const x=c;setTimeout(()=>{c!==x||t().signal.aborted||E(w,v).catch(()=>{})},0)},g=()=>{d?.abort(),d=void 0};let y;const m=()=>{const w=t().signal;w!==y&&(y?.removeEventListener("abort",g),y=w,w.addEventListener("abort",g))};async function E(w,v){const x=++c;g(),d=new AbortController,m();const P=()=>c!==x,K=u.readTarget(),J=t().generation,N=()=>J===t().generation&&!t().signal.aborted,L=v?"init:reset-":"init:";if(!v){const z=u.publicEmail();z?.id,z?.renderGuid,z?.preheader}let A=!1,O=!1;try{n=!0,await u.sendInitStart(),u.fireWillInit(),await(v?u.refreshContent():u.sendContent()),A=!0,v||u.publicEmail()?.id;try{await u.sendPreheader()}catch(z){r.logShowPipelineError(`${L}preheader-failed`,{showId:w,error:String(z)})}try{await u.sendSubject()}catch(z){r.logShowPipelineError(`${L}subject-failed`,{showId:w,error:String(z)})}if(P()||u.showFilled(K),await u.sendInited(),O=!0,i===w){const z=e.readSandboxGeneration?.()??s;z!==void 0&&(o=z)}await u.revealFilled()}catch(z){throw P()||r.logShowPipelineError(`${L}failed`,{showId:w,contentApplied:A,sandboxInitedAcked:O,superseded:!1,...e.describeSurface?.(),error:String(z)}),!P()&&Ls(t(),w)&&t().failShow(w,z),z}finally{k(w,v,L,{superseded:P(),sessionGeneration:J,contentApplied:A,sandboxInitedAcked:O,commit:N()})}}function k(w,v,x,P){const{superseded:K,contentApplied:J,sandboxInitedAcked:N}=P;if(K){`${x}`;return}N&&P.commit?u.fireInit(w,v||void 0):N?r.logShowPipelineError(`${x}aborted (stale session or signal)`,{showId:w,sessionGeneration:P.sessionGeneration,currentGeneration:t().generation,aborted:t().signal.aborted}):J?r.logShowPipelineError(`${x}aborted (sandbox INITED ack missing)`,{showId:w}):r.logShowPipelineError(`${x}aborted (content not applied)`,{showId:w}),n=!1,d=void 0,!N&&i===w&&(i=void 0,o===s&&(o=void 0)),!N&&J&&f(w,v)}return{channel:u,isEventsLocked:()=>n,filledGeneration:()=>o,markFilled:w=>{o=w},lastCorrelation:()=>i,markCorrelation:w=>{i=w},bumpRunSeq:()=>{c+=1},noteSandboxGeneration:w=>{s=w},fill:w=>E(w,!1),refill:w=>E(w,!0),stop:()=>{c+=1,g(),n=!1,y?.removeEventListener("abort",g),y=void 0}}}function Yf(e,t,n){if(!e?.renderGuid||!e.showId||e.showId!==t.showId)return!1;if(t.isNew)return e.id==null;const o=t.emailId??t.navId;return o!=null&&String(e.id??"")!==String(o)?!1:Ms(e,n)}function Ms(e,t){return t?e?.id==null?!1:String(e.id)===String(t):!0}function Qf(e){const{pipeline:t,readEmail:n,readDocument:o,readRouteEmailId:i,readSandboxGeneration:s}=e,c=f=>{const g=n(),y=i();if(!Yf(g,f,y)){f.showId,f.navId,f.emailId,g?.id,g?.showId,g?.renderGuid;return}f.showId,g?.id,g?.renderGuid,t.markFilled(s()),t.markCorrelation(f.showId),t.fill(f.showId).catch(()=>{})};return{showRequested:f=>{c(f)},showRequestIdentityChanged:()=>{const f=e.initPipeline().getActiveShowRequest();f&&c(f)},selfInitChanged:()=>{if(e.initPipeline().getActiveShowRequest())return;const f=s();if(t.filledGeneration()===f)return;const g=n(),y=i();if(!g?.renderGuid||!Ms(g,y))return;const m=`${Os}${g.renderGuid}`;t.markFilled(f),t.markCorrelation(m);const E=o()?.isReady()===!0;g.id,g.renderGuid,(E?k=>t.refill(k):k=>t.fill(k))(m).catch(()=>{t.lastCorrelation()===m&&t.markFilled(void 0)})},saasChanged:()=>{const f=n();f?.renderGuid,f?.showToken,f?.id}}}var Ns=h.createIdentifier$1("canvas.sandboxFill"),Xf=class extends Error{showId;constructor(e,t){super(`[useblocks] show() timed out after ${t}ms waiting for editor init (showId=${e}). Check earlier console errors: wrong host-plugin publicPath (chunks return HTML), mount element removed without destroy(), or sandbox init never completed. Search for [show-pipeline] and [AMD] messages.`),this.name="ShowPipelineTimeoutError",this.showId=e}},Jf=class{_activeRequest=null;_pending=new Map;_listeners=new Set;getActiveShowRequest(){return this._activeRequest}onShowRequested(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}requestShow(e,t,n){return this._rejectPending(h.createAbortError("Superseded by newer show()")),n.aborted?Promise.reject(h.createAbortError(n.reason)):(this._activeRequest=e,new Promise((o,i)=>{const s=setTimeout(()=>{this._settle(e.showId,()=>{i(new Xf(e.showId,t))})},t);s.unref?.();const c=()=>{this._settle(e.showId,()=>{i(h.createAbortError(n.reason))})};n.addEventListener("abort",c,{once:!0});const d=()=>{clearTimeout(s),n.removeEventListener("abort",c)};this._pending.set(e.showId,{request:e,resolve:o,reject:i,timeoutId:s,dispose:d});for(const u of this._listeners)u(e)}))}completeShow(e){this._settle(e,t=>{t.resolve()})}hasPendingShow(e){return this._pending.has(e)}failShow(e,t){this._settle(e,n=>{n.reject(t)})}rejectAll(e){this._rejectPending(e),this._activeRequest=null}_settle(e,t){const n=this._pending.get(e);n&&(n.dispose(),this._pending.delete(e),this._activeRequest?.showId===e&&(this._activeRequest=null),t(n))}_rejectPending(e){for(const[,t]of this._pending)t.dispose(),t.reject(e);this._pending.clear()}};function Zf(e,t){return{contentReady:t.contentReady??e?.contentReady,sandboxReady:t.sandboxReady??e?.sandboxReady,sandbox:t.sandbox?{...e?.sandbox,...t.sandbox}:e?.sandbox}}function eg(e){if(!e||!(e.contentReady!==void 0||e.sandboxReady!==void 0||e.sandbox!==void 0))return;const t=r.resolveContentReadyTimeoutMs(e),n=r.resolveSandboxReadyTimeoutMs(e),o=r.resolveSequentialSandboxOpBudgetMs(e.sandbox);t<n+o}var tg=class{_controller=new AbortController;_externalSignalDisposable=new h.Disposable;_sessionChangeListeners=new Set;_showRegistry=new Jf;_timeouts;_generation=0;_sessionStarted=!1;get signal(){return this._controller.signal}get generation(){return this._generation}get contentReadyTimeoutMs(){return r.resolveContentReadyTimeoutMs(this._timeouts)}getSandboxTimeoutMs(e){return r.resolveSandboxOpTimeoutMs(e,this._timeouts?.sandbox)}getSandboxReadyTimeoutMs(){return r.resolveSandboxReadyTimeoutMs(this._timeouts)}bumpGeneration(){this._generation+=1}getActiveShowRequest(){return this._showRegistry.getActiveShowRequest()}onShowRequested(e){return this._showRegistry.onShowRequested(e)}requestShow(e){return this._showRegistry.requestShow(e,this.contentReadyTimeoutMs,this._controller.signal)}completeShow(e){this._showRegistry.completeShow(e)}hasPendingShow(e){return this._showRegistry.hasPendingShow(e)}failShow(e,t){this._showRegistry.failShow(e,t)}rejectAllPendingShows(e){this._showRegistry.rejectAll(e)}onSessionReplaced(e){return this._sessionChangeListeners.add(e),()=>{this._sessionChangeListeners.delete(e)}}configure(e){e.timeouts!==void 0&&(this._timeouts=Zf(this._timeouts,e.timeouts),eg(this._timeouts));const t=e.replaceSession===!0||!this._sessionStarted||e.timeouts!==void 0||e.signal!==void 0;this._sessionStarted=!0,t&&(this._replaceSessionController(),this.bumpGeneration()),(e.signal!==void 0||t)&&this._linkExternalSignal(e.signal)}abort(e){const t=e??h.createAbortError("Editor instance destroyed");this._showRegistry.rejectAll(t),this._controller.signal.aborted||(this._controller.abort(t),this.bumpGeneration()),this._externalSignalDisposable.dispose(),this._externalSignalDisposable=new h.Disposable}_replaceSessionController(){this._externalSignalDisposable.dispose(),this._externalSignalDisposable=new h.Disposable,this._showRegistry.rejectAll(h.createAbortError("Init session replaced")),this._controller.signal.aborted||this._controller.abort(h.createAbortError("Init session replaced")),this._controller=new AbortController,this._emitSessionReplaced()}_emitSessionReplaced(){for(const e of this._sessionChangeListeners)e()}_linkExternalSignal(e){if(!e)return;if(e.aborted){this._controller.signal.aborted||(this._controller.abort(e.reason??h.createAbortError()),this.bumpGeneration());return}const t=()=>{this._controller.signal.aborted||(this._controller.abort(e.reason??h.createAbortError()),this.bumpGeneration())};e.addEventListener("abort",t),this._externalSignalDisposable.addDispose(()=>{e.removeEventListener("abort",t)})}},ng=(()=>{const e=new tg;return e.configure({}),e})();function yo(){const e=r.useStore();return(0,l.useMemo)(()=>h.getContainer(e)?.getInstance(h.INIT_PIPELINE_ID)??ng,[e])}function rg(e){const t=yo(),n=(0,l.useRef)(e);n.current=e,(0,l.useEffect)(()=>{let o;const i=()=>{o?.();const c=t.signal;if(c.aborted){n.current();return}const d=()=>n.current();c.addEventListener("abort",d),o=()=>c.removeEventListener("abort",d)};i();const s=t.onSessionReplaced(i);return()=>{s(),o?.()}},[t])}function og(e){const t=yo(),n=(0,l.useRef)(e);n.current=e,(0,l.useEffect)(()=>t.onShowRequested(o=>n.current(o)),[t])}var ig=(e,t,n,o,i)=>{const s=r.useStore(),c=r.useMessageService(),d=yo(),u=(0,l.useRef)(d);u.current=d;const p=r.useEventEmitter(h.events.WILL_EMAIL_INIT_ID),f=r.useEventEmitter(h.events.ON_EMAIL_INIT_ID),g=r.useEventEmitter(h.events.ON_CONTENT_CHANGED_ID),y=r.useEventEmitter(h.events.ON_EMAIL_CHANGED_ID),m=r.useEventEmitter(h.events.ON_BROWSER_EXTENSION_DETECTED_ID),E=e?.id!==void 0,k=e?.showToken??0,w=k,v=(0,l.useRef)(w);v.current=w;const x=(0,l.useRef)(void 0);x.current=e;const[P,K]=(0,l.useState)(()=>r.getSandboxGeneration(c)),J=(0,l.useRef)(P);J.current=P,(0,l.useEffect)(()=>(K(r.getSandboxGeneration(c)),r.onSandboxGenerationChange(c,()=>{K(r.getSandboxGeneration(c))})),[c]);const N=(0,l.useRef)(o);N.current=o;const L=(0,l.useRef)(t);L.current=t;const A=i?.standalone?void 0:h.getContainer(s)?.getInstance(Ns),O=!A,z=(0,l.useRef)(A?.pipeline);z.current||(z.current=Kf({container:h.getContainer(s),messageService:c,initPipeline:()=>u.current,readDocument:()=>N.current,readEmail:()=>x.current,isTemplate:()=>!!L.current,readSandboxGeneration:()=>J.current,events:{willInit:H=>p.fire(H),inited:H=>f.fire(H),contentChanged:H=>g.fire(H),emailChanged:H=>y.fire(H),browserExtensionDetected:()=>m.fire()}}));const B=z.current,U=(0,l.useRef)(n);U.current=n;const de=(0,l.useRef)(void 0);O&&!de.current&&(de.current=Qf({pipeline:B,initPipeline:()=>u.current,readEmail:()=>x.current,readDocument:()=>N.current,readRouteEmailId:()=>U.current,readSandboxGeneration:()=>J.current}));const me=de.current;B.noteSandboxGeneration(J.current),(0,l.useEffect)(()=>{if(O)return()=>z.current?.stop()},[O]),(0,l.useEffect)(()=>{A?.setRoute({emailId:n,isTemplate:t})},[A,n,t]),(0,l.useEffect)(()=>{const H=x.current;if(O&&!B.isEventsLocked()&&e?.renderGuid===H?.renderGuid&&H?.is_inited&&H){const Z=B.channel.readContent();y.fire({...H,id:t||H.isNew?void 0:H.id,html:Z})}},[B,e?.renderGuid,e?.preheader,e?.common_styles,e?.meta,e?.subject,e?.utm_parameters?.utm_campaign||"",e?.utm_parameters?.utm_content||"",e?.utm_parameters?.utm_medium||"",e?.utm_parameters?.utm_source||"",e?.utm_parameters?.utm_term||"",y,t,O]),(0,l.useEffect)(()=>{if(O){const H=r.subscribeToContent(o,()=>{const Z=x.current;if(!B.isEventsLocked()&&e?.renderGuid===Z?.renderGuid&&Z){const De=B.channel.readContent();g.fire(De),y.fire({...Z,id:t||Z.isNew?void 0:Z.id,html:De})}});return()=>H.dispose()}},[o,B,g,y,e,t,O]),rg(()=>{O&&B.stop()}),og(H=>{me?.showRequested(H)}),(0,l.useEffect)(()=>{me?.showRequestIdentityChanged()},[me,d,e?.renderGuid,e?.showId,e?.id,n]),(0,l.useEffect)(()=>{me?.selfInitChanged()},[me,d,e?.renderGuid,e?.showId,e?.id,n,o,P]),r.usePrevious(()=>{me?.saasChanged()},[e?.renderGuid,k,E,me]),Zr(async()=>{if(!O)return;const H=d.getActiveShowRequest()?.showId;H&&(B.markFilled(J.current),await B.refill(H))},{async:!0})};function sg(e){const t=r.useEvent(h.events.ON_EMAIL_INIT_ID);(0,l.useEffect)(()=>{if(!e)return;const n=t(()=>e.clear());return()=>n.dispose()},[e,t])}function ag(e,t){const n=r.useEventEmitter(h.events.ON_DOCUMENT_SESSION_CHANGE);(0,l.useEffect)(()=>{n.fire({document:e,history:t})},[e,t,n])}function lg({templateEmailId:e,templateEmail:t,newEmail:n}){return e?t:n}function cg({routeEmailId:e,draft:t}){const n=r.useStore();(0,l.useRef)(0),(0,l.useEffect)(()=>{},[n,e,t])}function dg(e,t){return t}function ug(e){return!1}function pg({documents:e,push:t,projectId:n,subscription:o}){(0,l.useEffect)(()=>e.onSaved(i=>{i.intent==="publish"&&t({event:"save",action:"save_email",email_id:i.serverId??void 0,project_id:n,subscription:o})}),[e,t,n,o])}function mg(e){const t=r.useStore();(0,l.useEffect)(()=>{},[t,e])}function fg(e,t,n){const o=r.useAppNavigate(),i=r.useContainer();(0,l.useEffect)(()=>{},[o,e,t,n,i])}function gg(e){if(!e)return{status:"unknown"};if("status"in e){const t=e.data,n=t&&typeof t=="object"?t.message:void 0,o=typeof n=="string"?n:typeof t=="string"?t:void 0;return{status:String(e.status),message:o}}return{status:e.name??"unknown",message:e.message}}function Ds(e,t,n){const{status:o,message:i}=gg(n);r.reportMessage(`Failed to load ${e} ${t??"?"}: ${o}`,{origin:"entity-load-error",tags:{mechanism:"entity-load-error",entity_type:e,http_status:o},level:"error",contexts:{entity_load_error:{entityType:e,entityId:t,status:o,message:i,url:window.location.href}}})}var{Content:hg}=_.ui_kit$Layout,_g={paddingTop:"40px"},yg=()=>{const{__:e}=r.useI18n(),{owner:t,admin:n}=Qn(),o=r.useDispatch(),i=Vr(),s=r.useAppNavigate(),{modal:c}=_.ui_kit$App.useApp(),d=r.useAppConfig(),u=r.useRootElement(),p=r.useCookieManager(),f=r.useMessageService(),{emailId:g,preview:y}=r.useRouteParams(),m=r.useEditorProjectId(),E=r.useAppSearchParams(),k=r.useSelector(r.selectIsCodeMode),w=r.useSelector(r.selectActiveModal),v=r.useCurrentUser(),x=r.useProjectData(),P=(0,l.useMemo)(()=>r.createNewEmailDraft(x?{id:Number(x.id),title:x.name}:void 0),[x]),K=r.useSelector(r.selectIsGlobalLoading),[J]=r.useLazyGetMeQuery(),{isSuccess:N,data:L}=r.useGetSubscriptionsQuery(),A=Df(),[O,z]=(0,l.useState)(!1),[B,U]=(0,l.useState)(!1),[de,me]=(0,l.useState)(),[H,Z]=(0,l.useState)(null),[De,ve]=(0,l.useState)(!1),[et,be]=(0,l.useState)(!1),[fe,Y]=(0,l.useState)(!1),[pe,ie]=(0,l.useState)(!1),[se,Ae]=(0,l.useState)(!1),Te=(0,l.useRef)(),{confirm:Fe}=c,{counters:X,subscription:Ee}=v,Ie=X?.emails_counter;p.get(r.APP_COOKIES.em_template_email);const ge=E.get("template")||!B&&!g&&p.get(r.APP_COOKIES.em_new_email),{isSuccess:Re,isLoading:Ue,isError:C,error:T,data:R}=Nf(g?void 0:ge),D=lg({templateEmailId:ge,templateEmail:R,newEmail:P});cg({routeEmailId:g,draft:D});const{document:I,email:S,error:ae}=r.useOpenEmail(),we=S?.id!=null?String(S.id):void 0,Ye=dg(g,we);(0,l.useEffect)(()=>{},[g,we,I,ge]),fg(g,S?.id,m);const Qe=r.useStore(),ze=r.getEmailDocuments(h.getContainer(Qe)),Ze=(0,l.useCallback)((ce,ke)=>ze.save(ce,ke),[ze]),pt=(0,l.useCallback)(()=>ze.saveState(),[ze]),bt=r.usePushToDataLayer();pg({documents:ze,push:bt,projectId:m,subscription:Ee?.post_title}),(0,l.useEffect)(()=>{!B&&S?.id&&U(!0)},[U,B,S?.id]);const ft=ze.history();ag(I,ft),sg(ft),ig(S,ug(g),Ye,I);const lt=Jr({document:I,history:ft});zf(S,I,ze.saveState().saving,ze),mg(m),(0,l.useEffect)(()=>{r.injectEmailRightsResolver(h.getContainer(Qe),ce=>!!(t||n||v.id?.toString()===ce?.author?.toString()))},[Qe,t,n,v.id]);const G=Kp({email:S,save:Ze,saveState:pt,documentSession:I}),{outdatedBlocks:V,isOpen:te,close:ue}=gf({projectId:m,document:I});Uf({projectId:m,project:x,emailProjectId:S?.project,parentEmailId:S?.parent_email});const he=w===r.MODALS.ADD_NEW_EBLOCK_MODAL,Ge=kn(he),qe=kn(fe),{isPromptOpen:st,isConverting:Bt,progress:Le,isErrorOpen:Xe,errorMessage:oe,confirmConversion:ee,cancelPrompt:$,retryConversion:le,closeError:xe,neverSuggestAgain:Se,setNeverSuggestAgain:Me}=Of(),We=ae??(ge?T:void 0),Be=!!We,ot=!S&&!Be,fn=!!S;(0,l.useEffect)(()=>{Be&&We&&Ds("email",g||ge,We)},[Be,We,g,ge]),(0,l.useEffect)(()=>{ge&&Re&&(U(!0),E.set({}))},[ge,Re,E]),(0,l.useEffect)(()=>(o(r.switchIsPanelHistoryCollapsed(!0)),()=>o(r.switchIsPanelHistoryCollapsed(!0))),[o]);const Ot=(0,l.useCallback)(()=>{i.toggle(),o(r.resetPanes())},[o,i]);(0,l.useEffect)(()=>{y&&!k&&Ot()},[k,y,Ot]),(0,l.useEffect)(()=>{document.body.classList.add("editor"),o(r.setActiveSettingsTab(r.BUILD))},[o]),(0,l.useEffect)(()=>{!O&&Ie<3&&(J(),z(!0))},[J,Ie,O]);const ct=(0,l.useCallback)(()=>{lt.undo()},[lt]),Et=(0,l.useCallback)(()=>{lt.redo()},[lt]);(0,l.useEffect)(()=>{Te.current!==S?.id&&(lt.clear(),Te.current=S?.id)},[S,lt]);const Lt=(0,l.useCallback)(ce=>{(window.navigator.appVersion.indexOf("Mac")&&ce.metaKey||ce.ctrlKey)&&ce.code==="KeyZ"&&(ce.preventDefault(),ce.shiftKey?Et():ct())},[ct,Et]);(0,l.useEffect)(()=>()=>{o(r.resetPanes()),o(r.closeModal()),o(r.closeModal$1()),o(r.resetElementHistorySlice())},[o]);const jn=(0,l.useCallback)(ce=>{const ke=()=>{o(r.openModal(r.MODALS.ADD_NEW_EBLOCK_MODAL))},Ne=ce.data.operation,nt=ce.data,je=ce.data.action,Yt=u.querySelector("#iframe-scroll-top"),$t=u.querySelector("#iframe-scroll-bottom");if(Ne===r.EVENT_TYPES.APPLICATION_EBLOCK_ADD){const dt=nt.settings?.emBlockId;dt?Z({html:nt.data,emBlockId:String(dt)}):(me(nt.data),ke())}if(Ne===r.EVENT_TYPES.APPLICATION_ACTION&&(je==="undo"?ct():je==="redo"&&Et()),Ne===r.EVENT_TYPES.APPLICATION_SCROLL_BLOCK_SHOW){const dt=u.querySelector("#email_iframe_slot"),Nn=document.body.getBoundingClientRect().height,Ut=dt.getClientRects()[0];Ut.top<0&&(Yt.style.display="block"),Ut.top+Ut.height>Nn&&($t.style.display="block")}Ne===r.EVENT_TYPES.APPLICATION_SCROLL_BLOCK_HIDE&&(Yt.style.display="none",$t.style.display="none")},[o,ct,Et,u]);r.useListenPostMessage(jn);const On=ce=>{if(ce.target?.closest?.(".file-manager, .ant-modal.file-manager"))return;const ke=ce.dataTransfer,Ne=(ke?Array.from(ke.types||[]):[]).includes(r.DND_SOCIAL_LIST_REORDER_MIME),nt=typeof ce.composedPath=="function"?ce.composedPath():[];ce.target?.closest?.(".selected-social-form")||nt.some(je=>je&&je.nodeType===1&&typeof je.classList?.contains=="function"&&je.classList.contains("selected-social-form"))||Ne||(ce.preventDefault(),ce.target&&f.send({operation:r.EVENT_TYPES.SANDBOX_DRAG_CANCEL}),u.querySelectorAll(".em-dragging-element").forEach(je=>{je.classList.remove("em-dragging-element")}))},gn=(0,l.useRef)({});(0,l.useEffect)(()=>{const ce=new h.Disposable,ke=Ne=>nt=>gn.current[Ne]?.(nt);return ce.addDisposable(r.addWindowListenerFromShadow(u,"drop",ke("drop"))),ce.addDisposable(r.addWindowListenerFromShadow(u,"dragover",ke("dragover"))),ce.addDisposable(r.addWindowListenerFromShadow(u,"dragstart",ke("dragstart"))),ce.addDisposable(r.addWindowListenerFromShadow(u,"dragend",ke("dragend"))),()=>{ce.dispose()}},[u]),(0,l.useEffect)(()=>(window.addEventListener("keydown",Lt),()=>{window.removeEventListener("keydown",Lt)}),[Lt]);const Ln=ce=>{if(ce.preventDefault(),ce.target?.closest?.(".file-manager, .ant-modal.file-manager"))return;const ke=u.querySelector("#iframe-scroll-top"),Ne=u.querySelector("#iframe-scroll-bottom"),nt=d.sidePanelFloating?u.querySelector("#pane-content-wrapper"):u.querySelector(".email-pane__col_preview"),je=u.querySelector(".blocks-app").getBoundingClientRect().top,{height:Yt,top:$t}=u.querySelector("#email_iframe_slot").getBoundingClientRect(),dt=nt.getBoundingClientRect().height;$t>96?ke.style.display==="block"&&(ke.style.display="none"):(ke.style.display==="none"||ke.style.display==="")&&(ke.style.display="block"),Yt-dt+$t-je<44?Ne.style.display==="block"&&(Ne.style.display="none"):Ne.style.display==="none"&&(Ne.style.display="block"),ce.target===ke&&nt.scrollBy(0,-15),ce.target===Ne&&nt.scrollBy(0,15)},Mn=()=>{const ce=u.querySelector("#iframe-scroll-top"),ke=u.querySelector("#iframe-scroll-bottom");ce&&ke&&(ce.style.display="none",ke.style.display="none"),u.querySelectorAll(".em-dragging-element").forEach(Ne=>{Ne.classList.remove("em-dragging-element")})},gt=ce=>{const ke=ce.target,Ne=ke instanceof Element?ke:ke.parentElement;if(!(Ne instanceof Element)||Ne.closest(".selected-social-form"))return;Ne.parentElement?.classList.add("em-dragging-element");const nt=!!Ne.closest(".blocks-search__result-wrapper");var je=nt?r.cloneBlockPreviewForDrag(Ne.querySelector(".blocks-search__result-html")):Ne.cloneNode(!0);je.classList.add("em-ghost-element"),je.style.height=nt?"auto":"70px",je.style.width=nt?"600px":"109px",je.style.position="absolute",je.style.top="0",je.style.left="0",je.style.zIndex="-1",Ne.appendChild(je),ce.dataTransfer.setDragImage(je,0,0),window.setTimeout(function(){je.parentNode.removeChild(je)},1e3)};gn.current={drop:On,dragover:Ln,dragstart:gt,dragend:Mn};const St=(0,l.useCallback)(()=>{Fe({title:e("You reached the plan limit"),icon:(0,a.jsx)(r.EmIcons,{icon:"ExclamationCircleOutlined",component:_.icons$ExclamationCircleOutlined}),content:(0,a.jsx)("div",{style:{maxWidth:"330px"},children:e("Switch to a different plan to save more emails.")}),centered:!0,okText:e("Choose a plan"),cancelText:e("Continue without saving"),width:"unset",onOk(){s("/billing")},onCancel(){}})},[s,e,Fe]);return(0,l.useEffect)(()=>{if(N&&L){const ce=L?.find(ke=>ke.id?.toString()===Ee?.ID?.toString())?.limits?.emails_limit;ce&&Ie>=ce&&!De&&!g&&t&&(St(),ve(!0))}},[L,N,Ee,Ie,De,St,g,t]),(0,l.useEffect)(()=>{const ce=f.onInit(()=>{f.send({operation:r.EVENT_TYPES.SANDBOX_LOCK_EDIT,data:!1})});return()=>ce.dispose()},[f]),(0,a.jsx)(r.DocumentSessionProvider,{document:I,history:ft,children:(0,a.jsx)(hs.Provider,{value:G,children:(0,a.jsxs)(_.ui_kit$Layout,{className:"email-page",children:[ot&&(0,a.jsx)(_.ui_kit$PageLoader,{}),!ot&&A.status==="pending"&&(0,a.jsx)(_.ui_kit$PageLoader,{}),A.status==="error"&&(0,a.jsx)(hg,{style:_g,children:(0,a.jsx)("div",{className:"container",children:(0,a.jsx)(_.ui_kit$Result,{status:"warning",title:e("Failed to load plan data"),subTitle:e("Editor features depend on your plan. Check your connection and try again."),extra:(0,a.jsx)(_.ui_kit$Button,{type:"primary",onClick:A.retry,children:e("Try again")})})})}),Be&&We&&!1,S&&!ot&&A.status==="ready"&&(0,a.jsxs)(_.ui_kit$Layout,{className:"email-pane",children:[K&&(0,a.jsx)("div",{className:"email-pane__loader",children:(0,a.jsx)(_.ui_kit$PageLoader,{small:!0})}),(0,a.jsx)(Is,{email:S,isCollaborationEditor:et}),(0,a.jsx)(Np,{emailElement:S,isSuccess:fn,setIsCollaborationEditor:be,setIsShowAddAllBlocksModal:Y,triggerOpenSavedBlocksTab:pe})]}),Ge&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Cu,{isModalVisible:he,htmlContent:de,projectId:m,setIsShowAddAllBlocksModal:Y,setIsShowAddAllBlocksModalForNewEmail:Ae,currentEmail:S})}),(0,a.jsx)(pf,{open:te,blocks:V,projectId:m,onClose:ue}),(0,a.jsx)(hf,{open:!!H,html:H?.html,emBlockId:H?.emBlockId,onSaveAsNew:()=>{me(H?.html),Z(null),o(r.openModal(r.MODALS.ADD_NEW_EBLOCK_MODAL))},onClose:()=>Z(null)}),qe&&(0,a.jsx)(l.Suspense,{fallback:null,children:(0,a.jsx)(Tu,{isModalVisible:fe,currentEmail:S,setIsShowAddAllBlocksModal:Y,setTriggerOpenSavedBlocksTab:ie,autoStart:!se,projectId:m})}),(0,a.jsx)(bf,{open:st,onConfirm:ee,onCancel:$,neverSuggestAgain:Se,onNeverSuggestAgainChange:Me}),(0,a.jsx)(wf,{open:Bt,progress:Le}),(0,a.jsx)(Sf,{open:Xe,message:oe,onRetry:le,onCancel:xe})]})})})};function vg(){const e=r.useStore(),t=r.getEmailDocuments(h.getContainer(e)),n=(0,l.useCallback)(o=>t.subscribe(o),[t]);return(0,l.useSyncExternalStore)(n,()=>!!t.current())}function bg(e,t){const n=r.useStore(),o=r.useAppConfig(),i=r.useStorageProvider();(0,l.useRef)(new Set),(0,l.useEffect)(()=>{},[e,t,o,n,i])}var Eg=30;function Sg(e){const t=r.useContainer(),n=r.useGetProjectQuery(+e,{skip:!e,refetchOnMountOrArgChange:Eg}),{isSuccess:o,isError:i,error:s,data:c,isFetching:d}=n;bg(e,o),(0,l.useEffect)(()=>{t&&r.setCurrentProjectRefreshing(t,d)},[t,d]),(0,l.useEffect)(()=>{t&&o&&c&&String(c.id)===String(e)&&r.setCurrentProjectCard(t,c)},[o,c,t,e]),(0,l.useEffect)(()=>{i&&s&&Ds("project",e,s)},[i,s,e]);const u=r.useProjectData(),p=!!u&&String(u.id)===String(e);return{...n,projectReady:p}}var An=r.createApi({reducerPath:"promoApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.emailmaker.ru/api/wp-json/promo/v1/"}),endpoints:e=>({checkPromo:e.mutation({queryFn:({code:t,type:n},o)=>r.clientFromApi(o).promo.set_code_create({code:t,type:n})}),getPromoInfo:e.query({queryFn({code:t},n){return r.clientFromApi(n).promo.get_code_info_list({code:t})}})})}),{useCheckPromoMutation:sb,useGetPromoInfoQuery:ab}=An;function wg(){const e=r.useContainer(),[t,n]=(0,l.useState)();return(0,l.useEffect)(()=>{if(!e)return;let o=!0;return r.getAppProject(e).then(i=>{o&&i!=null&&n(String(i))},()=>{}),()=>{o=!1}},[e]),t}var kg=()=>{const e=r.useDispatch(),t=r.useCookieManager(),n=r.useCurrentUser(),o=r.useContainer();(0,l.useEffect)(()=>{const s=n?.code_editor;s&&o&&r.applyEditorOptions(o,s)},[n,o]),(0,l.useEffect)(()=>{const s=t.get(r.APP_COOKIES.em_token),c=t.get(r.APP_COOKIES.promocode);s&&c&&(e(An.endpoints.checkPromo.initiate({code:c,type:"by_link"})),t.remove(r.APP_COOKIES.promocode))},[e,t]),r.useNotifyCommand();const i=vg();return Sg(wg()),i?(0,a.jsx)(Ql,{hasEmail:!0,children:(0,a.jsx)(l.Suspense,{fallback:(0,a.jsx)(_.ui_kit$PageLoader,{}),children:(0,a.jsx)(yg,{})})}):null};function Cg(e,t){const n=(0,l.useRef)(!1);(0,l.useEffect)(()=>{!e||n.current||(n.current=!0,r.mark(r.PHASES.appVisible),t&&Ht(t).noteShellVisible())},[e,t])}var xn=new WeakMap,Tg="data-useblocks-config-styles";function Ig(e){return typeof e=="string"?e.trim():""}function Fs(e,t){if(e.firstChild){e.insertBefore(t,e.firstChild);return}e.appendChild(t)}function Ag(e,t,n){if(!e||typeof document>"u")return null;const o=Ig(t),i=xn.get(e),s=n||e;if(!o)return i&&(i.remove(),xn.delete(e)),null;if(i)return i.textContent!==o&&(i.textContent=o),(i.parentNode!==s||i!==s.firstChild)&&Fs(s,i),i;const c=document.createElement("style");return c.setAttribute(Tg,"true"),c.textContent=o,Fs(s,c),xn.set(e,c),c}function vo(e){if(!e)return;const t=xn.get(e);t&&(t.remove(),xn.delete(e))}var xg={height:"100%",display:"flex",justifyContent:"center",alignItems:"center"},Pg=({children:e,handleBeforeRender:t})=>{const[n,o]=(0,l.useState)(),i=r.useIsLocaleInited();Cg(i,r.useContainer());const s=r.useAppConfig().styles,c=(0,l.useRef)(null),d=(0,l.useRef)(!1),u=(0,l.useRef)(void 0),p=r.useRootElement();return(0,l.useLayoutEffect)(()=>{d.current||(d.current=!0,t&&t())},[]),(0,l.useLayoutEffect)(()=>{if(!p){u.current&&(vo(u.current),u.current=void 0);return}u.current&&u.current!==p&&vo(u.current),Ag(p,s,c.current||void 0),u.current=p},[p,s]),(0,l.useLayoutEffect)(()=>()=>{u.current&&(vo(u.current),u.current=void 0)},[]),(0,a.jsxs)(_.ui_kit$StyleProvider,{container:r.findShadowRoot(p)||document.head,children:[(0,a.jsxs)("div",{ref:c,className:"App blocks-app blocks-plugin",style:i?{}:{visibility:"hidden"},children:[(0,a.jsx)(r.ModalRootContext.Provider,{value:n,children:e}),(0,a.jsx)("div",{ref:o,className:"blocks-modal-container"})]}),!i&&(0,a.jsx)(_.ui_kit$Space,{size:"large",style:xg,children:(0,a.jsx)(_.ui_kit$Spin,{size:"large"})})]})};async function Rg({container:e,renderTarget:t,mapKey:n,disposable:o,chunkLoadedFire:i}){const s=await e.getInstanceAsync(h.STORE_ID);return new Promise(c=>{if(o.isDisposed()){c();return}const d=(0,nl.createRoot)(t),u=(0,a.jsx)(r.Provider,{store:s,children:(0,a.jsx)(Wl,{onLoad:c,children:(0,a.jsx)(r.RootContext.Provider,{value:{element:n},children:(0,a.jsx)(_.ui_kit$StyleProvider,{container:r.isDocumentFragment(n)?document.head:n,children:(0,a.jsx)(r.LocaleProvider,{children:(0,a.jsx)(Pg,{handleBeforeRender:i,children:(0,a.jsx)(pl,{children:(0,a.jsx)(Gl,{children:(0,a.jsx)(kg,{})})})})})})})})});d.render(u),o.addDispose(c),o.addDispose(()=>{try{d.unmount()}catch(p){if(p instanceof DOMException&&p.name==="NotFoundError"||p instanceof Error&&p.name==="NotFoundError"&&/removeChild/i.test(p.message)){r.logShowPipelineError("mount:unmount-dom-mismatch (host container was already removed)",{hint:"Usually harmless during host React StrictMode teardown. Ensure instance.destroy() runs before the host removes the mount container."});return}throw p}}),o.addDispose(()=>{h.ELEMENT_MAP.delete(n)})})}var lb="multiple init call on single HTMLELEMENT",jg=zn(async e=>{let t=null,n=!1;const o=h.getEmitter(e,h.events.ON_CHUNKS_LOADED),i=e.getInstance(h.DISPOSABLE_ID);let s,c=!1;const d=()=>{c||(c=!0,r.mark(r.PHASES.chunksLoaded),o.fire())},u=(p,f)=>Rg({container:e,renderTarget:p,mapKey:f,disposable:s,chunkLoadedFire:d});return{instance:{getElement(){return t}},async setOptions(p){const f=e.getInstance(h.INIT_PIPELINE_ID),g=await h.waitForElement(p.element,i,f.signal),y=e.getInstance(h.INSTANCE_ID),m=!!p.hidden&&!!g;if(t===g&&n===m)return;const E=t===g&&n&&!m;n=m,i.addDisposable(o.event(()=>{p.handleChunkLoaded&&p.handleChunkLoaded()})),t&&h.ELEMENT_MAP.delete(t),g&&h.ELEMENT_MAP.has(g),s&&s.dispose(),s=i.addDisposable(new h.Disposable);const k=p.element!==void 0;if(r.setHeadlessMode(e,!g||m),r.setHiddenMount(e,m),!g){r.mark(r.MOUNT_HEADLESS_MARK);const v=document.createElement("div");v.style.position="absolute",v.style.left="-10000px",v.style.top="-10000px",v.style.width="1600px",v.style.height="1000px",document.body.appendChild(v),t=v,d(),s.addDispose(()=>{v.parentNode===document.body&&v.remove()});return}const w=r.findShadowRoot(g);if(w&&s.addDisposable(new ul({shadowRoot:w})),k&&g instanceof Element){const v=g;il(v,()=>{i.isDisposed()||s?.isDisposed()||(r.logShowPipelineError("mount:detached (host removed element without destroy)",{elementId:v.id||null}),f.abort(ol()))},s)}if(m){r.mark(r.MOUNT_HEADLESS_MARK),t=g,d();return}if(k&&g instanceof Element){const v=g,x=cl(v);t=v;const P=u(x,v);return dl(v,x,s),P}return t=g,u(g,g)},dispose(){s&&!s.isDisposed()&&s.dispose()}}});function bo(e){return zn(async t=>(await t.getInstanceAsync(h.STORE_ID),await e(t)))}function Og({html:e,renderGuid:t,...n},o){const{requested:i}=r.getCurrentProject(o);return r.filterUndefined({...n,code:on(o).toOutputForm(e),project:i===void 0?n.project:i,guid:void 0,link:void 0,status:void 0,slug:void 0,password:void 0,comment_status:void 0,template:void 0,blocktags:void 0,project_title:void 0,ping_status:void 0,lock:void 0,tag:void 0,is_template:void 0})}function Lg(e,t){return r.filterUndefined({...e,link:void 0,comment_status:void 0})}function Mg({html:e,...t},n){return r.filterUndefined({...t,code:e,guid:void 0,compiled:r.filterUndefined({html:e,ampHtml:e&&""})})}var Bs=e=>{const t={current:Promise.resolve(),state:e,decorate:(n,o)=>(o&&(n=n.bind(o)),function(...i){const s=t.current.then(()=>n(...i));return t.current=s.then(c=>{t.state=c},c=>{}),s})};return t},Ng=h.createIdentifier$1("emailTemplate.reads");async function Dg(e,t){try{return await r.getRestEmailPortFactories(e).email(e).readEmail(t)??void 0}catch(n){r.logShowPipelineError("show:template-read-failed",{templateId:t,error:n instanceof Error?n.message:"неизвестная ошибка"});return}}function Fg(e,t){const n=e.getOrCreateInstance(Ng,()=>new Map),o=n.get(t);if(o!==void 0)return o;const i=Dg(e,t).then(s=>(s===void 0&&n.delete(t),s));return n.set(t,i),i}var kt=class extends h.Disposable{_event;_listener;_disposeEvent;constructor(e){super(),this._event=e}setListener(e){this._listener!==e&&(this._listener=e,this._disposeEvent&&this._disposeEvent(),e?this._disposeEvent=this._event(e):this._disposeEvent=void 0)}dispose(){this._disposeEvent&&this._disposeEvent(),super.dispose()}};function Ct(e,t,n){const o=h.snapshot(e);return(i,s,c)=>{const d=o(async u=>{const p=t?t(u):u;c&&i.bind(c);const f=await i(p);return n?n(f):f},s,c);return()=>d.dispose()}}var cb=h.createIdentifier("application_block_inserted"),db=h.createIdentifier$1("DataController"),ub=h.createIdentifier$1("DataEvents"),Bg=h.createIdentifier$1("plugin.startupShow");function $g(e){return e.getInstance(Bg)?.current??Promise.resolve()}var $s=bo(async()=>({instance:{}})),Us=bo(async e=>({instance:{},async setOptions(){await $g(e)}})),pb=h.combineMixins([$s,Us]),zs=()=>({title:"",description:"",website:"",company_size:"",industry:"",email:"",phone:"",logo_url:""}),Ug={title:"title",description:"description",website:"website",company_size:"company_size",industry:"industry",email:"email",phone:"phone",logo_url:"logo"},Gs=e=>({...zs(),title:e?.title??"",description:e?.description??"",website:e?.website??"",company_size:e?.company_size??"",industry:e?.industry??"",email:e?.email??"",phone:e?.phone??"",logo_url:e?.logo??""}),Ws=e=>(e??[]).filter(t=>!!t?.code).map(({code:t,label:n})=>({value:t,label:n??t})),zg=e=>({company_sizes:Ws(e?.company_sizes),industries:Ws(e?.industries)}),mb=Object.keys(zs()),Hs="ProjectProfile",Pn=r.createApi({reducerPath:"projectSettingsProfileApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),tagTypes:[Hs],endpoints:e=>({getProjectProfile:e.query({async queryFn(t,n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.profileList({id:String(t)}));return"error"in o?{error:o.error}:{data:Gs(o.data)}},providesTags:(t,n,o)=>[{type:Hs,id:String(o)}]}),getProjectProfileOptions:e.query({async queryFn(t,n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.profileOptionsList());return"error"in o?{error:o.error}:{data:zg(o.data)}}}),updateProjectProfileField:e.mutation({async queryFn({projectId:t,field:n,value:o},i){const s={[Ug[n]]:o},c=r.v2ResultOf(await r.getClientV2(h.getContainer(i)).projects.profilePartialUpdate({id:String(t)},s));return"error"in c?{error:c.error}:{data:Gs(c.data)}},async onQueryStarted({projectId:t},{dispatch:n,queryFulfilled:o}){try{const{data:i}=await o;n(Pn.util.updateQueryData("getProjectProfile",t,()=>i))}catch{}}})})}),{useGetProjectProfileQuery:fb,useGetProjectProfileOptionsQuery:gb,useUpdateProjectProfileFieldMutation:hb}=Pn,qs="ProjectStorage",Rn=r.createApi({reducerPath:"projectSettingsStorageApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),tagTypes:[qs],endpoints:e=>({getProjectStorage:e.query({async queryFn(t,n){const o=r.v2ResultOf(await r.getClientV2(h.getContainer(n)).projects.storageList({id:String(t)}));return"error"in o?{error:o.error}:{data:o.data}},providesTags:(t,n,o)=>[{type:qs,id:String(o)}]}),updateProjectStorage:e.mutation({async queryFn({projectId:t,body:n},o){const i=r.v2ResultOf(await r.getClientV2(h.getContainer(o)).projects.storageUpdate({id:String(t)},n));return"error"in i?{error:i.error}:{data:i.data}},async onQueryStarted({projectId:t},{dispatch:n,queryFulfilled:o}){const{data:i}=await o;n(Rn.util.upsertQueryData("getProjectStorage",t,i))}}),testProjectStorageConnection:e.mutation({async queryFn({projectId:t,body:n},o){const i=r.v2ResultOf(await r.getClientV2(h.getContainer(o)).projects.storageTestCreate({id:String(t)},n));return"error"in i?{error:i.error}:{data:i.data}}})})}),{useGetProjectStorageQuery:_b,useUpdateProjectStorageMutation:yb,useTestProjectStorageConnectionMutation:vb}=Rn,Gg=class{http;constructor(e){this.http=e}settings_summary_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/settings-summary/${e}`,method:"GET",...n})},Vs=class{http;constructor(e){this.http=e}developer_credentials_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}`,method:"GET",...n});developer_credentials_partial_update=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}`,method:"PATCH",...n});developer_credentials_rotate_secret_create=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}/rotate-secret`,method:"POST",...n});developer_credentials_verify_secret_create=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/developer-credentials/${e}/verify-secret`,method:"POST",...n})},Wg=class{http;constructor(e){this.http=e}developer_kit_postman_collection_list=(e={})=>this.http.request({path:"/projects/v1/developer-kit/postman-collection",method:"GET",...e})},Hg=class{http;constructor(e){this.http=e}billing_context_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/billing-context/${e}`,method:"GET",...n});billing_context_payments_list=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/billing-context/${e}/payments`,method:"GET",query:t,...n})},qg=class{http;constructor(e){this.http=e}usage_detail=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/usage/${e}`,method:"GET",...n});usage_timeseries_list=({projectId:e,...t},n={})=>this.http.request({path:`/projects/v1/usage/${e}/timeseries`,method:"GET",query:t,...n})},Ke={PLUGIN_INIT:"plugin_init",LINK_CHECK:"link_check",IMAGE_CHECK:"image_check",SPAM_ASSASSIN:"spam_assassin",AI_IMAGE:"ai_image",AI_WRITE:"ai_write",AI_REPHRASE:"ai_rephrase"},Zt={TODAY:"today",WEEK:"week",MONTH:"month",CUSTOM:"custom"},bb=[Ke.PLUGIN_INIT,Ke.LINK_CHECK,Ke.IMAGE_CHECK,Ke.SPAM_ASSASSIN,Ke.AI_IMAGE,Ke.AI_WRITE],ln={current:0,limit:null},Vg=()=>({pluginInit:{...ln},aiAssistant:{...ln},aiImage:{...ln},linkCheck:{...ln},imageCheck:{...ln},spamAssassin:{...ln}}),tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Je=(e,t,n="")=>{for(const o of t){const i=e[o];if(typeof i=="string")return i;if(typeof i=="number"&&Number.isFinite(i))return String(i)}return n},Ft=(e,t,n=0)=>{for(const o of t){const i=e[o];if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()&&Number.isFinite(Number(i)))return Number(i)}return n},Eo=(e,t,n=!1)=>{for(const o of t){const i=e[o];if(typeof i=="boolean")return i}return n},br=(e,t)=>{for(const n of t){const o=e[n];if(o===null)return null;if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()&&Number.isFinite(Number(o)))return Number(o)}return null},Kg=new Set(Object.values(Ke)),Yg=e=>Kg.has(e)?e:null,en=e=>tt(e)&&"data"in e&&(e.ok===!0||typeof e.success=="boolean"||e.success===void 0)?e.data:e,cn=(e,t)=>{for(const n of t){const o=e[n];if(tt(o))return o}return null},Qg=(e,t)=>{for(const n of t){const o=e[n];if(!Array.isArray(o))continue;const i=o.filter(s=>typeof s=="string");if(i.length>0)return i}},Xg=e=>tt(e)?{clientId:Je(e,["clientId","client_id"]),clientSecretConfigured:Eo(e,["clientSecretConfigured","client_secret_configured"]),rotatedAt:Je(e,["rotatedAt","rotated_at"])||void 0,scopesSuggested:Qg(e,["scopesSuggested","scopes_suggested"])}:{clientId:"",clientSecretConfigured:!1},Ks=(e,t)=>{for(const n of t){const o=e[n];if(typeof o=="boolean")return o}},Jg=e=>{const t=Ks(e,["pluginConnected","plugin_connected","connected","is_connected"]);if(t!==void 0)return t;for(const n of["plugin","developer_credentials","developerCredentials"]){const o=cn(e,[n]);if(!o)continue;const i=Ks(o,["connected","plugin_connected","is_connected"]);if(i!==void 0)return i;const s=Je(o,["clientId","client_id"]),c=Eo(o,["clientSecretConfigured","client_secret_configured"]);if(s)return c}},Zg=e=>{const t=en(e);if(!tt(t))return{};const n=cn(t,["members"]);return{myRole:Je(t,["myRole","my_role","role"])||(n?Je(n,["myRole","my_role","role"]):"")||void 0,pluginConnected:Jg(t)}},eh=e=>tt(e)?{clientId:Je(e,["clientId","client_id"]),secret:Je(e,["secret","clientSecret","client_secret"])}:{clientId:"",secret:""},th=e=>{if(!tt(e))return null;const t=Je(e,["event","type","key"]),n=Yg(t);if(!n)return null;const o=e.delta??e.change??e.trend,i=o==null?null:typeof o=="number"&&Number.isFinite(o)?o:Number.isFinite(Number(o))?Number(o):null;return{event:n,total:Ft(e,["total","count","value"],0),delta:i}},Ys=e=>{if(!tt(e))return null;const t=Je(e,["date","day","x"]);if(!t)return null;const n={date:t},o=e.event_counts??e.eventCounts;if(tt(o)){for(const[i,s]of Object.entries(o))typeof s=="number"&&Number.isFinite(s)&&(n[i]=s);return n}for(const[i,s]of Object.entries(e))i==="date"||i==="day"||i==="x"||i==="event_counts"||i==="eventCounts"||typeof s=="number"&&Number.isFinite(s)&&(n[i]=s);return n},nh=e=>{const t=en(e);return tt(t)?(Array.isArray(t.chart)?t.chart:Array.isArray(t.series)?t.series:Array.isArray(t.time_series)?t.time_series:Array.isArray(t.history)?t.history:[]).map(Ys).filter(n=>n!==null):[]},rh=e=>{if(!tt(e))return{current:0,limit:null};const t=Ft(e,["current","count","used","value","total"],0),n=br(e,["limit","max","quota","cap"]);return{current:t,limit:n===null?null:n}},dn=(e,t)=>{for(const n of t)if(n in e)return rh(e[n]);return{current:0,limit:null}},un={pluginInit:[Ke.PLUGIN_INIT,"plugin_init","pluginInit"],aiAssistant:["ai_assistant","aiAssistant","ai"],aiImage:[Ke.AI_IMAGE,"ai_image","ai_img","aiImg"],linkCheck:[Ke.LINK_CHECK,"link_check","linkCheck"],imageCheck:[Ke.IMAGE_CHECK,"image_check","imageCheck"],spamAssassin:[Ke.SPAM_ASSASSIN,"spam_assassin","spamAssassin","spam_check","spamCheck"]},So=e=>{const t=Vg(),n=en(e),o=tt(n)&&tt(n.usage)?n.usage:n;if(!tt(o))return t;const i=Ft(o,["operationsTotal","operations_total"],0),s=Ft(o,["operationsLast30d","operations_last_30d"],0),c=cn(o,["metrics","counters","limits","events","usage_by_event","usageByEvent"])??o;return{pluginInit:dn(c,un.pluginInit),aiAssistant:dn(c,un.aiAssistant),aiImage:dn(c,un.aiImage),linkCheck:dn(c,un.linkCheck),imageCheck:dn(c,un.imageCheck),spamAssassin:dn(c,un.spamAssassin),lastActivityAt:Je(o,["lastActivityAt","last_activity_at"])||void 0,operationsTotal:i>0?i:void 0,operationsLast30d:s>0?s:void 0}},Qs=(e,t)=>{const n=[{event:Ke.LINK_CHECK,total:e.linkCheck.current,delta:null},{event:Ke.IMAGE_CHECK,total:e.imageCheck.current,delta:null},{event:Ke.SPAM_ASSASSIN,total:e.spamAssassin.current,delta:null},{event:Ke.AI_IMAGE,total:e.aiImage.current,delta:null}],o=t?nh(t):[];return o.length>0?{cards:n,chart:o}:{cards:n,chart:[]}},oh=e=>{const t=en(e);if(!tt(t))return Qs(So(e),e);const n=Array.isArray(t.cards)?t.cards:Array.isArray(t.summary)?t.summary:[],o=Array.isArray(t.chart)?t.chart:Array.isArray(t.series)?t.series:[];return n.length>0||o.length>0?{cards:n.map(th).filter(i=>i!==null),chart:o.map(Ys).filter(i=>i!==null)}:Qs(So(t),t)},ih=e=>{if(!tt(e))return null;const t=Je(e,["id","payment_id"]);return t?{id:t,date:Je(e,["date","created_at","paid_at"]),amount:Ft(e,["amount","sum"],0),currency:Je(e,["currency"],"RUB"),status:Je(e,["status"],"unknown"),receiptUrl:Je(e,["receiptUrl","receipt_url","pdf_url"])||void 0}:null},sh=e=>{const t=en(e),n=tt(t)&&Array.isArray(t.payments)?t.payments:[];return{payments:n.map(ih).filter(o=>o!==null),page:tt(t)?Ft(t,["page"],1):1,perPage:tt(t)?Ft(t,["perPage","per_page"],20):20,total:tt(t)?Ft(t,["total"],n.length):n.length,totalPages:tt(t)?Ft(t,["totalPages","total_pages"],1):1}},ah=e=>{const t=en(e);if(!tt(t))return{viewerSeesBilling:!1};const n=cn(t,["endpoints"])??{},o=cn(t,["documentLinks","document_links"]),i=o?Object.fromEntries(Object.entries(o).filter(f=>typeof f[1]=="string")):void 0,s=br(t,["ownerUserId","owner_user_id"]),c=cn(t,["tariff","plan","subscription"]),d=Je(t,["planDescription","plan_description"])||(c?Je(c,["description","about","plan_description"]):"")||void 0,u=br(t,["planPrice","plan_price","price","amount"])??(c?br(c,["price","amount"]):null),p=Je(t,["planCurrency","plan_currency","currency"])||(c?Je(c,["currency"]):"")||void 0;return{viewerSeesBilling:Eo(t,["viewerSeesBilling","viewer_sees_billing"]),ownerUserId:s??void 0,planName:Je(t,["planName","plan_name"])||void 0,planDescription:d,planPrice:u??void 0,planCurrency:p||void 0,endpoints:{limitsStats:Je(n,["limitsStats","limits_stats"])||void 0,subscriptionMe:Je(n,["subscriptionMe","subscription_me"])||void 0,payments:Je(n,["payments"])||void 0},documentLinks:i&&Object.keys(i).length>0?i:void 0}},lh={myRole:"owner"},ch=()=>({...lh}),dh={clientId:"rust-awkward-bear",clientSecretConfigured:{}.REACT_APP_PLUGIN_SETTINGS_MOCK_CONNECTED!=="false"},Xs=()=>({...dh,clientSecretConfigured:{}.REACT_APP_PLUGIN_SETTINGS_MOCK_CONNECTED!=="false"}),Js=Object.values(Ke),uh={[Ke.PLUGIN_INIT]:42,[Ke.LINK_CHECK]:-15,[Ke.IMAGE_CHECK]:28,[Ke.SPAM_ASSASSIN]:9,[Ke.AI_IMAGE]:6,[Ke.AI_WRITE]:-11,[Ke.AI_REPHRASE]:4},ph=(e,t)=>{const n={date:e};return Js.forEach((o,i)=>{const s=Math.sin(t*.65+i*.9),c=t*(i%2===0?.35:.2),d=2+i;n[o]=Math.max(0,Math.round(d+s*4+c))}),n},mh=e=>Js.map(t=>({event:t,total:e.reduce((n,o)=>n+(typeof o[t]=="number"?o[t]:0),0),delta:uh[t]})),fh=({period:e,dateFrom:t,dateTo:n})=>{const o=(0,En.default)().startOf("day");if(e===Zt.WEEK)return{startDate:o.subtract(6,"day"),days:7};if(e===Zt.MONTH)return{startDate:o.subtract(29,"day"),days:30};if(e===Zt.CUSTOM&&t&&n){const i=(0,En.default)(t),s=(0,En.default)(n);return{startDate:i,days:Math.max(1,s.diff(i,"day")+1)}}return{startDate:o,days:1}},wo=(e={period:Zt.TODAY})=>{const{startDate:t,days:n}=fh(e),o=Array.from({length:n},(i,s)=>ph(t.add(s,"day").format("YYYY-MM-DD"),s));return{cards:mh(o),chart:o}},Eb=wo({period:Zt.WEEK}),gh={pluginInit:{current:0,limit:null},aiAssistant:{current:0,limit:null},aiImage:{current:42,limit:100},linkCheck:{current:128,limit:500},imageCheck:{current:64,limit:200},spamAssassin:{current:31,limit:150},lastActivityAt:"2026-05-02T12:00:00Z"},Zs={payments:[{id:"98765",date:"2026-05-12T10:15:00+00:00",amount:990,currency:"RUB",status:"success",receiptUrl:"https://receipts.example/98765.pdf"},{id:"98764",date:"2026-04-12T10:15:00+00:00",amount:990,currency:"RUB",status:"success"},{id:"98763",date:"2026-03-12T10:15:00+00:00",amount:990,currency:"RUB",status:"failed"}],page:1,perPage:20,total:3,totalPages:1},hh={viewerSeesBilling:!0,ownerUserId:1,planName:"Corporate",planDescription:"For fully addressing all necessary tasks in any field.",planPrice:3200,planCurrency:"RUB",endpoints:{limitsStats:"/wp-json/limits/v1/stats",subscriptionMe:"/wp-json/subscription/v2/me",payments:"/wp-json/projects/v1/billing-context/2581/payments"}},_h={info:{name:"EmailMaker Plugin Requests",schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:[]},yh=e=>e,vh=()=>!1,bh=()=>!1,Eh=e=>e,pn="ProjectPlugin",Sh=()=>({}).REACT_APP_PLUGIN_SETTINGS_USE_MOCK==="true",Vt=(e,t,n)=>e.error&&Sh()?{data:n(t)}:r.transformResponseFn(n)(e),wh=e=>yh(Xg(e)),kh=e=>Eh(ah(e)),Ch=({period:e,dateFrom:t,dateTo:n})=>{if(e===Zt.CUSTOM){const o={};return t&&(o.date_from=t),n&&(o.date_to=n),o}return{period:e??Zt.TODAY}},Er=r.createApi({reducerPath:"projectSettingsPluginApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api".replaceAll(/[\\/]$/g,"")}),tagTypes:[pn],endpoints:e=>({getPluginSummary:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Gg]).settings_summary_detail({projectId:t}).then(o=>Vt(o,ch(),Zg))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:o}]}),getPluginCredentials:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Vs]).developer_credentials_detail({projectId:t}).then(o=>Vt(o,Xs(),wh))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:`credentials-${o}`}]}),rotatePluginSecret:e.mutation({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Vs]).developer_credentials_rotate_secret_create({projectId:t}).then(o=>Vt(o,{clientId:Xs().clientId,secret:"mock-rotated-secret"},eh))},invalidatesTags:(t,n,{projectId:o})=>[{type:pn,id:`credentials-${o}`}]}),getPostmanCollection:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Wg]).developer_kit_postman_collection_list({extraQuery:{project_id:String(t)}}).then(o=>Vt(o,_h,i=>en(i)??i))}}),getPluginAnalytics:e.query({queryFn({projectId:t,period:n,dateFrom:o,dateTo:i},s){const c={period:n,dateFrom:o,dateTo:i};return vh()?Promise.resolve({data:wo(c)}):r.getClient(h.getContainer(s)).request({path:`/projects/v1/usage/${t}/timeseries`,method:"GET",query:Ch(c)}).then(d=>Vt(d,wo(c),oh))}}),getPluginBillingContext:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[Hg]).billing_context_detail({projectId:t}).then(o=>Vt(o,hh,kh))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:`billing-${o}`}]}),getPluginUsage:e.query({queryFn({projectId:t},n){return h.getApi(h.getContainer(n),[qg]).usage_detail({projectId:t}).then(o=>Vt(o,gh,So))}}),getPluginPayments:e.query({queryFn({projectId:t,page:n=1,perPage:o=20},i){return bh()?Promise.resolve({data:Zs}):r.getClient(h.getContainer(i)).request({path:`/projects/v1/billing-context/${t}/payments`,method:"GET",query:{page:String(n),per_page:String(o)}}).then(s=>Vt(s,Zs,sh))},providesTags:(t,n,{projectId:o})=>[{type:pn,id:`payments-${o}`}]})})}),{useGetPluginSummaryQuery:Sb,useGetPluginCredentialsQuery:wb,useRotatePluginSecretMutation:kb,useLazyGetPostmanCollectionQuery:Cb,useGetPluginAnalyticsQuery:Tb,useGetPluginBillingContextQuery:Ib,useGetPluginPaymentsQuery:Ab,useGetPluginUsageQuery:xb}=Er,ea="EmailRaw",Sr=r.createApi({reducerPath:"emailRawApi",tagTypes:[ea],baseQuery:r.fetchBaseQuery({baseUrl:"https://app.useblocks.io/api/wp-json/wp/v2/"}),endpoints:e=>({getEmailRaw:e.query({queryFn:function({emailId:t,secret_hash:n},o){return h.getApi(h.getContainer(o),[h.WpEmailApi]).email_detail({id:t},{extraQuery:{secret_hash:n}}).then(r.transformResponseFn(r.WpEmailToEmail))},providesTags:(t,n,o)=>[{type:ea,id:o}]})})}),{useGetEmailRawQuery:Pb}=Sr,wr=r.createApi({reducerPath:"yandexAuthApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({validateYandexToken:e.mutation({query:t=>({url:"/auth/yandex",method:"POST",body:t})})})}),{useValidateYandexTokenMutation:Rb}=wr,kr=r.createApi({reducerPath:"elamaAuthApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({validateElamaCode:e.mutation({query:t=>({url:"/auth/elama",method:"POST",body:t})})})}),{useValidateElamaCodeMutation:jb}=kr,Cr=r.createApi({reducerPath:"googleAuthApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({validateGoogleToken:e.mutation({query:t=>({url:"/auth/google",method:"POST",body:t})})})}),{useValidateGoogleTokenMutation:Ob}=Cr,ta=async e=>{const t=await e.text();let n=t;try{n=JSON.parse(t)}catch{n=t}return n},Th=(e,t,n)=>{if(!e)throw new Error(`Set ${n}`);return{url:`?proxy_url=${encodeURIComponent(e)}`,method:"POST",headers:{"Content-Type":"application/json"},body:t,responseHandler:ta}},Ih=(e,t,n)=>{if(!e)throw new Error(`Set ${n}`);return{url:`?proxy_url=${encodeURIComponent(e)}`,method:"POST",body:t,responseHandler:ta}},Tr=r.createApi({reducerPath:"requestPlaneApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({getRequest:e.mutation({query:t=>Ih("https://webhook.latenode.com/5868/prod/5c07527e-9d53-467a-a148-87220d46e9ae",t,"REACT_APP_PIPEDREAM_REQUEST_PLANE_SRC")}),getInvoiceRequest:e.mutation({query:t=>Th("https://webhook.latenode.com/5868/prod/5c07527e-9d53-467a-a148-87220d46e9ae",t,"REACT_APP_REQUEST_PLANE_WEBHOOK_URL")})})}),{useGetRequestMutation:Lb,useGetInvoiceRequestMutation:Mb}=Tr,Ir=r.createApi({reducerPath:"getCheckoutUrlApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({GetCheckoutUrl:e.mutation({query:t=>({url:`?proxy_url=${encodeURIComponent("https://webhook.latenode.com/5868/prod/5072387e-5ace-4ca7-9a25-2f952a7075af")}`,method:"POST",body:t})})})}),{useGetCheckoutUrlMutation:Nb}=Ir,ko=r.createApi({reducerPath:"recoverPasswordApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://app.useblocks.io/api/wp-json/bdpwr/v1/"}),endpoints:()=>({})}),Ar=r.createApi({reducerPath:"addUserToProjectApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/wp-json/user_to_project/v1/add_user"}),endpoints:e=>({addUserToProject:e.mutation({queryFn(t,n){return r.clientFromApi(n).userToProject.add_user_create(t,{type:h.ContentType.FormData})}})})}),{useAddUserToProjectMutation:Db}=Ar,xr=r.createApi({reducerPath:"recurrenceSubscriptionsOffApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({getCanselRecurrence:e.query({query:t=>({url:`?proxy_url=${encodeURIComponent(`https://webhook.latenode.com/5868/prod/38815aec-cb5d-4b40-8dcb-75e7453573a0?subscription_id=${t.sid}&user_id=${t.uid}`)}`})})})}),{useLazyGetCanselRecurrenceQuery:Fb,useGetCanselRecurrenceQuery:Bb}=xr,Pr=r.createApi({reducerPath:"recurrenceSubscriptionsOnApi",baseQuery:r.fetchBaseQuery({baseUrl:"https://px0.useblocks.io/"}),endpoints:e=>({getRecurrence:e.query({query:t=>({url:`?proxy_url=${encodeURIComponent(`https://webhook.latenode.com/5868/prod/7ac13d46-e4af-4dea-ab21-aab55415575b?subscription_id=${t.sid}&user_id=${t.uid}`)}`})})})}),{useLazyGetRecurrenceQuery:$b,useGetRecurrenceQuery:Ub}=Pr,Ah="https://app.useblocks.io/api/v2",Rr=r.createApi({reducerPath:"authApi",baseQuery:r.fetchBaseQueryApp({baseUrl:Ah,prepareHeaders:e=>{const t=r.api.get(r.APP_COOKIES.em_token);return t&&!e.has("authorization")&&e.set("authorization",`Bearer ${t}`),e}}),endpoints:e=>({login:e.mutation({query:t=>({url:"/auth/token",method:"POST",body:t})}),register:e.mutation({query:t=>({url:"/auth/register",method:"POST",body:t})}),refreshToken:e.mutation({query:t=>({url:"/auth/token/refresh",method:"POST",body:t})}),logout:e.mutation({query:()=>({url:"/auth/token",method:"DELETE"})}),getUser:e.query({query:()=>"/auth/user",transformResponse:t=>{const n=Array.isArray(t)?t[0]:t;return r.WpUserToUser(n)}}),changePassword:e.mutation({query:t=>({url:"/auth/password/change",method:"POST",body:t})}),resetPassword:e.mutation({query:t=>({url:"/auth/password/reset",method:"POST",body:t})}),resetPasswordConfirm:e.mutation({query:t=>({url:"/auth/password/reset/confirm",method:"POST",body:t})})})}),{useLoginMutation:zb,useRegisterMutation:Gb,useRefreshTokenMutation:Wb,useLogoutMutation:Hb,useGetUserQuery:qb,useLazyGetUserQuery:Vb,useChangePasswordMutation:Kb,useResetPasswordMutation:Yb,useResetPasswordConfirmMutation:Qb}=Rr;function na(e){return{id:e.id??0,name:e.name??"",children:(e.children??[]).map(na)}}function xh(e){return(e?.folders??[]).map(na)}function Ph(e){return{items:(e?.items??[]).flatMap(t=>t.id?[{kind:t.kind??"email",id:t.id,name:t.name??"",title:t.title??"",preheader:t.preheader??"",folderId:t.folder_id??0,hasAmp:t.has_amp??!1,previewImage:t.preview_image??"",updatedAt:t.updated_at??"",imported:t.imported??!1}]:[]),total:e?.total??0}}function Co(e){const t=e.status??"pending";return{id:e.id??"",status:t,outcome:e.outcome,total:e.total??0,imported:e.imported??0,warnings:e.warnings??0,failed:e.failed??0,finished:t==="done"||t==="failed",items:(e.items??[]).map(n=>({kind:n.kind??"email",stripoId:n.stripo_id??0,name:n.name??"",status:n.status??"failed",reason:n.reason,emailId:n.email_id})),createdAt:e.created_at??"",finishedAt:e.finished_at}}function Rh(e){return{selectors:e.map(t=>({kind:t.kind,...t.ids?.length?{ids:t.ids}:{},...t.all?{all:!0}:{},...t.folderId?{folder_id:t.folderId}:{},...t.rootOnly?{root_only:!0}:{},...t.search?{search:t.search}:{}}))}}var To="StripoItems",Io="StripoFolders",jr="StripoImportJob",mn=(e,t)=>{const n=r.v2ResultOf(e);return"error"in n?{error:n.error}:{data:t(n.data)}},Or=r.createApi({reducerPath:"stripoImportApi",tagTypes:[To,Io,jr],baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/v2"}),endpoints:e=>({saveStripoKey:e.mutation({async queryFn({projectId:t,apiKey:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoKeyUpdate({id:String(t)},{api_key:n}),()=>{})},invalidatesTags:[To,Io]}),getStripoFolders:e.query({async queryFn({projectId:t,kind:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoFoldersList({id:String(t),kind:n}),xh)},providesTags:[Io]}),getStripoItems:e.query({async queryFn({projectId:t,kind:n,folderId:o,rootOnly:i,search:s,page:c,limit:d},u){return mn(await r.getClientV2(h.getContainer(u)).projects.stripoItemsList({id:String(t),kind:n,...o?{folder_id:o}:{},...i?{root_only:!0}:{},...s?{search:s}:{},page:c,limit:d}),Ph)},providesTags:[To]}),startStripoImport:e.mutation({async queryFn({projectId:t,selectors:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoImportsCreate({id:String(t)},Rh(n)),Co)},invalidatesTags:[jr]}),getCurrentStripoImport:e.query({async queryFn(t,n){const o=await r.getClientV2(h.getContainer(n)).projects.stripoImportsCurrentList({id:String(t)});return o.status===204?{data:null}:mn(o,Co)},providesTags:[jr]}),getStripoImport:e.query({async queryFn({projectId:t,jobId:n},o){return mn(await r.getClientV2(h.getContainer(o)).projects.stripoImportsDetail({id:String(t),jobId:n}),Co)},providesTags:[jr]})})}),{useSaveStripoKeyMutation:Xb,useGetStripoFoldersQuery:Jb,useGetStripoItemsQuery:Zb,useLazyGetStripoItemsQuery:e0,useStartStripoImportMutation:t0,useGetCurrentStripoImportQuery:n0,useGetStripoImportQuery:r0}=Or,jh=r.createState({activeGroupsTags:[],activeProjectGroupsTags:[],groupsTemplateTotal:null,groupsTemplateProjectTotalPages:null,groupsTemplateProjectTotal:null}),Oh="projectSlice",Ao=r.createSlice({name:Oh,initialState:jh,reducers:{setActiveGroupsTags:(e,{payload:t})=>{e.activeGroupsTags=t,t.length&&(e.activeProjectGroupsTags=[])},setActiveProjectGroupsTags:(e,{payload:t})=>{e.activeProjectGroupsTags=t,t.length&&(e.activeGroupsTags=[])},resetAllTags:e=>{e.activeProjectGroupsTags=[],e.activeGroupsTags=[]}},extraReducers:e=>{e.addMatcher(r.emailsApi.endpoints.getTemplateEmails.matchFulfilled,(t,{payload:n,meta:o})=>{const{projectId:i}=o.arg.originalArgs;i?(t.groupsTemplateProjectTotal=+o.baseQueryMeta?.response.headers.get("X-WP-Total"),t.groupsTemplateProjectTotalPages=+o.baseQueryMeta?.response.headers.get("X-WP-TotalPages")):t.groupsTemplateTotal=+o.baseQueryMeta?.response.headers.get("X-WP-Total")})}}),{setActiveGroupsTags:o0,setActiveProjectGroupsTags:i0,resetAllTags:s0}=Ao.actions,Lh=r.createState({emailsTotal:0,elementsList:[],emailsTrashTotal:0,elementsTrashList:[],customFolders:{},elementsView:r.CARDS}),Mh="emailsPageSlice";function Nh(e){const t=e?.baseQueryMeta?.response;return Number(t?.headers?.get("X-WP-Total"))||0}function ra(e,t){const{emails:n,total:o,isSearch:i,page:s,tagOrFolderId:c}=t;if(t.status==="trash")!i&&o!==void 0&&(e.emailsTrashTotal=o),e.elementsTrashList=n;else if(c){const d=e.customFolders[c];e.customFolders={...e.customFolders,[c]:{list:n,page:s,total:o??d?.total??0}}}else o!==void 0&&(e.emailsTotal=o),e.elementsList=n}var xo=r.createSlice({name:Mh,initialState:Lh,reducers:{resetElementsList:e=>{e.elementsList=[]},syncElementsList:(e,{payload:t})=>{ra(e,t)},toggleElementsView:(e,t)=>{e.elementsView=t.payload},removeEmailFromList:(e,{payload:t})=>{const n=e.customFolders;t.folder!=="all"&&n[t.folder]?.list&&(n[t.folder]={...n[t.folder],list:n[t.folder].list.filter(o=>o.id!==t.emailId),total:n[t.folder].total-1},e.customFolders=n)}},extraReducers:e=>{e.addMatcher(r.emailsApi.endpoints.getEmails.matchFulfilled,(t,{meta:n,payload:o})=>{const i=n.arg.originalArgs;ra(t,{emails:o,total:Nh(n),status:i?.status,page:i?.page,isSearch:!!i?.name?.length,tagOrFolderId:i?.folderTag||i?.tags?.[0]})}),e.addMatcher(r.emailsApi.endpoints.getTemplateEmails.matchFulfilled,(t,{meta:n,payload:o})=>{const i=+n.baseQueryMeta?.response.headers.get("X-WP-Total")||0;t.elementsList=o,t.emailsTotal=i;const{projectGroup:s,projectId:c,tags:d}=n.arg.originalArgs;(s?.length&&c||d?.length||!d?.length&&!s?.length)&&(t.emailsTotal=i)}),e.addMatcher(r.emailsApi.endpoints.editEmail.matchFulfilled,(t,{payload:n})=>{t.elementsList.map(o=>o.id?.toString()===n.id?.toString()?Object.assign(o,{lock:n.lock,title:n.title,emailtags:n.emailtags}):o)})}}),{toggleElementsView:a0,resetElementsList:l0,syncElementsList:c0,removeEmailFromList:d0}=xo.actions,oa=r.combineReducers({[r.di.reducerPath]:r.di.reducer,[r.AiApi.reducerPath]:r.AiApi.reducer,[r.userSlice.name]:r.userSlice.reducer,[r.emailSlice.name]:r.emailSlice.reducer,[r.blockSlice.name]:r.blockSlice.reducer,[r.imageApi.reducerPath]:r.imageApi.reducer,[An.reducerPath]:An.reducer,[hr.reducerPath]:hr.reducer,[Ao.name]:Ao.reducer,[r.blocksApi.reducerPath]:r.blocksApi.reducer,[r.emailsApi.reducerPath]:r.emailsApi.reducer,[fr.reducerPath]:fr.reducer,[Xn.reducerPath]:Xn.reducer,[Jn.reducerPath]:Jn.reducer,[Zn.reducerPath]:Zn.reducer,[er.reducerPath]:er.reducer,[tr.reducerPath]:tr.reducer,[nr.reducerPath]:nr.reducer,[rr.reducerPath]:rr.reducer,[or.reducerPath]:or.reducer,[ir.reducerPath]:ir.reducer,[sr.reducerPath]:sr.reducer,[ar.reducerPath]:ar.reducer,[lr.reducerPath]:lr.reducer,[cr.reducerPath]:cr.reducer,[dr.reducerPath]:dr.reducer,[ur.reducerPath]:ur.reducer,[pr.reducerPath]:pr.reducer,[r.emailPageSlice.name]:r.emailPageSlice.reducer,[r.projectsApi.reducerPath]:r.projectsApi.reducer,[Pn.reducerPath]:Pn.reducer,[Qt.reducerPath]:Qt.reducer,[Rn.reducerPath]:Rn.reducer,[Er.reducerPath]:Er.reducer,[r.saveFileApi.reducerPath]:r.saveFileApi.reducer,[Sr.reducerPath]:Sr.reducer,[r.commentsApi.reducerPath]:r.commentsApi.reducer,[r.optimiseApi.reducerPath]:r.optimiseApi.reducer,[io.name]:io.reducer,[xo.name]:xo.reducer,[mr.reducerPath]:mr.reducer,[Cr.reducerPath]:Cr.reducer,[wr.reducerPath]:wr.reducer,[kr.reducerPath]:kr.reducer,[r.taxonomiesApi.reducerPath]:r.taxonomiesApi.reducer,[r.projectsPageSlice.name]:r.projectsPageSlice.reducer,[r.AiApiGenerator.reducerPath]:r.AiApiGenerator.reducer,[Tr.reducerPath]:Tr.reducer,[gr.reducerPath]:gr.reducer,[yr.reducerPath]:yr.reducer,[Gn.reducerPath]:Gn.reducer,[r.authorizationApi.reducerPath]:r.authorizationApi.reducer,[r.limitsApi.reducerPath]:r.limitsApi.reducer,[r.revisionHistorySlice.name]:r.revisionHistorySlice.reducer,[Ir.reducerPath]:Ir.reducer,[r.defaultModePanesSlice.name]:r.defaultModePanesSlice.reducer,[ko.reducerPath]:ko.reducer,[Ar.reducerPath]:Ar.reducer,[_r.reducerPath]:_r.reducer,[Pr.reducerPath]:Pr.reducer,[xr.reducerPath]:xr.reducer,[Rr.reducerPath]:Rr.reducer,[r.projectSettingsV2Api.reducerPath]:r.projectSettingsV2Api.reducer,[Or.reducerPath]:Or.reducer}),Dh=(e,t)=>t.type==="authorizationApi/resetApiState"?oa({[r.reducerPath]:e[r.reducerPath]},t):oa(e,t),ia=[r.AiApi,r.imageApi,hr,r.emailsApi,An,r.blocksApi,fr,Xn,Jn,Zn,er,tr,nr,rr,or,ir,sr,ar,lr,cr,dr,ur,pr,Sr,r.projectsApi,Pn,Qt,Rn,Er,r.commentsApi,r.optimiseApi,r.saveFileApi,mr,Cr,r.taxonomiesApi,wr,kr,r.AiApiGenerator,Tr,r.authorizationApi,r.limitsApi,gr,yr,Gn,Ir,ko,Rr,r.projectSettingsV2Api,Or,Ar,_r,Pr,xr];function Fh(e){let t={};if(e){const o=h.createIdentifier$1();h.DependencyResolver.inject(o,e),t={INJECTION:o}}const n=r.configureStore({reducer:Dh,middleware:o=>o({serializableCheck:!1}).concat(ia.map(i=>i.middleware)),preloadedState:t});return r.setupListeners(n.dispatch),n}var sa=h.createIdentifier$1("RtkApiRegistry");function Bh(e,t){e.inject(sa,new Map(t.map(n=>[n.reducerPath,n])))}function at(e,t){const n=e?.getInstance(sa)?.get(t);if(!n)throw new Error(`RTK api "${t}" is not in the container registry (provideRtkApiRegistry did not run)`);return n}function $h(e,t){let n={isCodeMode:void 0,direction:void 0};return r.provideCodeMode(e).watch(o=>{n.isCodeMode!==o.isCodeMode&&t.dispatch(r.setCodeMode(o.isCodeMode)),n.direction!==o.direction&&t.dispatch(r.switchCodeModeDirection(o.direction)),n={isCodeMode:o.isCodeMode,direction:o.direction}})}function Uh(e,t){const n=r.provideCurrentUser(e),o=r.authorizationApi.endpoints.getMe.select("");let i=n.get()?.profile;const s=()=>{const c=o(t.getState()).data;!c||c===i||(i=c,n.set({profile:c}))};return s(),{dispose:t.subscribe(s)}}var zh=h.createIdentifier$1("EmailSettingsPort");function Gh(e,t){e.inject(zh,{read:()=>r.selectEmailSettings(t.getState())??{},write:n=>{t.dispatch(r.setEmailSettings(n))},markAppearanceChanged:()=>{t.dispatch(r.markAppearanceNeedsUpdate())}})}var Wh="Invalid standaloneKey.",Hh="not implemented",u0=1,qh=h.createIdentifier$1("StandaloneMockGuard");function Po(){const e=new Error(Wh);return e.name="InvalidStandaloneKeyError",e}function Ro(e){return r.isStandaloneRuntime(h.getContainer(e))}function Vh(e){return e instanceof Error?e.name==="InvalidStandaloneKeyError"||e.message==="Invalid standaloneKey."||e.message==="not implemented":e===Hh}function aa(e){if(Ro(e))throw Po()}function Kh(e,t,n){return n instanceof Error&&n.name==="InvalidStandaloneKeyError"?n:Po()}var Yh=()=>()=>{throw Po()};function Qh(e){if(!e)throw new Error("DI container not found for standalone mock guard");e.inject(qh,1)}function Xh(e){return typeof e!="function"}var p0="[plugin-api-mock]";function la(){return!0}function Jh(e){try{if(e===null||typeof e!="object")return e;const t={};for(const n of Object.keys(e).slice(0,12)){const o=e[n];t[n]=typeof o=="string"&&o.length>120?`${o.slice(0,120)}…(${o.length})`:o}return t}catch{return"(unserializable arg)"}}function Zh(e,t){return n=>{const o=n.query,i=n.queryFn||((s,c,d,u)=>{if(!o)throw new Error("query not found EndpointDefinition");return u(o(s))});i&&(n.query=void 0,n.queryFn=async(s,c,d,u)=>{try{let p;const f=h.getContainer(c).getServices(e);for(let g=f.length-1;g>=0;g--){const y=f[g];if(p=p?await p(async m=>await y.execute(m),c):await y.execute(s),Xh(p))return{data:p,error:null}}if(p)p=await p(async(g,y=c,m=d,E=u)=>{aa(c);const k=await i(g,y,m,E);if(k.error)throw k.error;return k.data},c);else{aa(c),la();const g=await i(s,c,d,u);if(g.error)throw g.error;p=g.data}return{data:p,error:null}}catch(p){return Ro(c)&&Vh(p)?{error:Kh(t,Jh(s),p)}:(la(),{error:p})}})}}var ca=new Set;function it(e){return(t,n)=>{const o=Object.create(null),i=Object.keys(n),s=new h.Disposable;for(const c of i){const d=`api_listeners_flag_${t.reducerPath}/${c.toString()}`,u=h.createIdentifier$1(`api_listeners_${t.reducerPath}/${c.toString()}`);ca.has(d)||(o[c]=Zh(u,`${t.reducerPath}/${c.toString()}`),ca.add(d)),s.addDisposable(e.addService(u,{execute:n[c]}))}return Object.keys(o).length&&t.enhanceEndpoints({endpoints:o}),r.getDisposable(e).addDisposable(s),s}}function da(e,t){for(const n of Object.keys(t))try{t[n](e)}catch{}}function m0(e){return e}function ua(e,t){return e({body:t}).catch(()=>new Promise(n=>setTimeout(n,1e3)))}function e_(e){it(e)(at(e,"AiApi"),{sendMessage:({body:t})=>async(n,o)=>{const i=r.getEmitter(e,h.events.AI_TEXT_REQUEST_ID);if(!i.hasListeners())return ua(n,t);const s=t,c={message:s.message??s.context,locale:s.locale,entityId:s.entity_id,projectId:s.project_id!=null?String(s.project_id):void 0,subject:s.subject,preheader:s.preheader,textContent:s.textContent,context:s.context??s.connection,connection:s.connection,onProgress:(d,u)=>{r.getEmitter(e,h.events.AI_TEXT_PROGRESS_ID).fire({progress:Number.isFinite(d)?d:0,status:typeof u=="string"?u:void 0})},onStreamChunk:d=>{typeof d!="string"||!d||r.getEmitter(e,h.events.AI_TEXT_STREAM_ID).fire({partialHtml:d})},signal:o.signal};for(const d of i.getListeners([c])){const u=await d(c);if(u)return{status:200,_eventResult:!0,aiMessage:typeof u.message=="string"?u.message:"",aiHtml:typeof u.html=="string"?u.html:void 0}}return ua(n,t)},getDialog:t=>(n,o)=>Ro(o)?Promise.resolve({documents:[],totalCount:0}):n(t)})}function t_(e){const t=it(e),n=r.getEmitter(e,h.events.FILE_PROXY_EVENT_ID);t(at(e,"proxyApi"),{async getFile({url:o,tryFetch:i=!0,type:s}){return async c=>{const{requested:d}=r.getCurrentProject(e),u=(await n.fire({url:o,project:d})).filter(p=>p instanceof Blob)[0];if(u)switch(s){case"json":return JSON.parse(await u.text());case"text":return u.text();default:return u}else return c({url:o,tryFetch:i,type:s})}}})}function n_(e){it(e)(at(e,"tokenApi"),{tokenCreate(t){return n=>n(t)},tokenValidate(){return t=>t({})}})}function f0(e){return e}function r_(e){it(e)(at(e,"imageApi"),{sendAiImageRequest:function({body:t}){return async(n,o)=>{const i=r.getEmitter(e,h.events.AI_IMAGE_REQUEST_ID);if(!i.hasListeners()||t.request!=="create-image")return n({body:t});const s={prompt:t.message??"",size:t.size,entityId:t.entity_id,projectId:t.project_id!=null?String(t.project_id):void 0,onProgress:(c,d)=>{r.getEmitter(e,h.events.AI_IMAGE_PROGRESS_ID).fire({progress:Number.isFinite(c)?c:0,status:typeof d=="string"?d:void 0})},signal:o.signal};for(const c of i.getListeners([s])){const d=await c(s);if(d&&d.images?.length)return{data:{status:200,_eventResult:!0,task:{images:d.images}}}}return n({body:t})}},getAiImage(t){return n=>n(t)}})}async function pa(e,t,n,o,i){try{const s=(await e.fire({project:String(t),emailId:n})).filter(c=>c!=null);if(s.length)return s.flat()}catch{}return o(i)}function o_(e){const t=it(e),n=at(e,"blocksApi"),o=r.blocksDataSourceProvider(e),i=o.byForeignKey("project"),s=r.blockRevisionsDataSourceProvider(e);s.byForeignKey("parent");const{dispatch:c}=r.getStore(e),d=r.getDisposable(e);d.addDisposable(o.onChange(()=>c(n.util.invalidateTags(["Blocks"])))),d.addDisposable(o.onSave(({prev:f,patch:g,value:y})=>{const m=f?{...f,...g}:g;let E=r.mergeEntityPreservingMeta(f,g,y);return m&&E.html===m.html&&E.title===m.title&&(E={...E,renderGuid:m.renderGuid}),E},Number.MIN_VALUE));const u=r.getEmitter(e,r.READ_COMMON_BLOCKS_EVENT_ID),p=r.getEmitter(e,r.READ_TEMPLATE_BLOCKS_EVENT_ID);t(n,{async getBlocks(f){const g={};f.name&&(g.title=f.name),f.type&&(g.type=f.type);const y=f.projectId??await r.getBlocksProject(e);return await i.get(y,{filter:g,page:f.page,pageSize:f.pageSize,order:f.order,orderBy:f.orderby}).then(({data:m})=>m)},getBlocksSchema(){return f=>f(void 0)},getParentEmailBlocks(f){return async g=>{const y=r.getCurrentProject(e).requested||"";return pa(p,y,f.emailId||"",g,f)}},getTemplateBlocks(f){return async g=>{const y=r.getCurrentProject(e).requested||"";return pa(u,y,f.emailId||"",g,f)}},async getBlock(f){const g=r.getCurrentProject(e).card?.id;if(g!==void 0)return i.first(Number(g),{filter:{id:f}})},addBlock(f){return async g=>{const y=await o.create(f);return r.getAppConfig(e).preventSendDataToEM||g(y).catch(m=>{}),y}},editBlock({blockId:f,...g}){return o.update(f,g)},deleteBlock(f){return o.remove(typeof f=="object"?f.id:f)},addTag(f){return f},getDeletableTag([f,g]){return[]},autoSaveBlock({blockId:f,body:g}){return s.create({...g,parent:f})}})}function i_(e){const{emails:t,emailRevisions:n}=r.provideEmailDocuments(e),{dispatch:o}=r.getStore(e),i=r.getDisposable(e),s=it(e),c=at(e,"emailsApi");i.addDisposable(t.onChange(async()=>{o(c.util.invalidateTags(["Email"]))})),s(c,{getEmails:d=>[],getTemplateEmails:d=>[],async addEmail({source:d,...u}){const p=await t.create(u,{source:d});return p.renderGuid||(p.renderGuid=h.generateUUID()),p},editEmail(d){return async u=>{const{emailId:p,source:f,...g}=d;return r.isRevisionServiceEnabled(e)&&await u(d),t.update(p,g,{source:f})}},deleteEmail(d){return t.remove(typeof d=="object"?d.id:d)},addTag(){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},getDeletableTag([d,u]){return[]},autoSaveEmail({emailId:d,body:u}){return async p=>{r.isRevisionServiceEnabled(e)&&await p({emailId:d,body:u});const f=await n.create({...u,parent:d,modified:new Date().toString()});return f&&!f.html&&u.html?{...f,html:u.html}:f}}})}var s_="tmp",g0=h.createIdentifier$1();function a_(e){const t=it(e);if(!e.getInstance(h.DISPOSABLE_ID))throw new Error("Something was wrong");const n=r.getEmitter(e,h.events.UPLOAD_EVENT_ID),o=r.getEmitter(e,h.events.ON_SEND_TESTEMAIL_ID),i=r.getEmitter(e,h.events.ON_SEND_LIVEPREVIEW_ID);t(at(e,"saveFileApi"),{uploadImage(s){return async c=>{const{requested:d}=r.getCurrentProject(e),u=async()=>c({...s,user_id:String((await e.getInstanceAsync(h.APP_ID)).app_id)});if(s.folder===s_)return u();const p=await r.fireUploadImageEvent(n,{file:s.file,project:d});if(p.url)return[{file_url:p.url,project:d}];if(!r.shouldFallbackToBuiltInUpload(p,{isStandalone:r.isStandaloneRuntime(e)}))throw r.toUploadImageError(p);return u()}},sendTestEmail(s){return async c=>{const{requested:d}=r.getCurrentProject(e);(await o.fire({project:d,email_id:s.email_id,subject:s.subject,email:s.email,html:s.html,from_name:s.from_name})).some(u=>u===!1)&&await c({...s,user_id:String((await e.getInstanceAsync(h.APP_ID)).app_id)})}},async sendLivePreview(s){const{requested:c}=r.getCurrentProject(e);(await i.fire({project:c,id:s.email,subject:s.subject,html:s.content})).some(d=>d===!1)},sendShortLink(s){return c=>c(s)}})}function l_(e){it(e)(at(e,"emailRawApi"),{getEmailRaw({emailId:t,secret_hash:n}){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function Kt(e,t){for(var n=e<0?"-":"",o=Math.abs(e).toString();o.length<t;)o="0"+o;return n+o}function c_(e,t){var n,o;r.requiredArgs(1,arguments);var i=Ll(e);if(isNaN(i.getTime()))throw new RangeError("Invalid time value");var s=String((n=t?.format)!==null&&n!==void 0?n:"extended"),c=String((o=t?.representation)!==null&&o!==void 0?o:"complete");if(s!=="extended"&&s!=="basic")throw new RangeError("format must be 'extended' or 'basic'");if(c!=="date"&&c!=="time"&&c!=="complete")throw new RangeError("representation must be 'date', 'time', or 'complete'");var d="",u="",p=s==="extended"?"-":"",f=s==="extended"?":":"";if(c!=="time"){var g=Kt(i.getDate(),2),y=Kt(i.getMonth()+1,2),m=Kt(i.getFullYear(),4);d="".concat(m).concat(p).concat(y).concat(p).concat(g)}if(c!=="date"){var E=i.getTimezoneOffset();if(E!==0){var k=Math.abs(E),w=Kt(Math.floor(k/60),2),v=Kt(k%60,2),x=E<0?"+":"-";u="".concat(x).concat(w,":").concat(v)}else u="Z";var P=Kt(i.getHours(),2),K=Kt(i.getMinutes(),2),J=Kt(i.getSeconds(),2),N=d===""?"":"T",L=[P,K,J].join(f);d="".concat(d).concat(N).concat(L).concat(u)}return d}function d_(e){const t=it(e),n=at(e,"commentsApi"),o=r.commentsDataSourceProvider(e),i=o.byForeignKey("post"),{dispatch:s}=r.getStore(e);r.getDisposable(e).addDisposable(o.onChange(()=>s(n.util.invalidateTags(["Comments"])))),t(n,{getComments(c){return i.get(c).then(({data:d})=>d)},addComment({subjectId:c,author:d,parent:u,content:p,author_name:f,author_email:g,targetId:y}){const m={post:c,author:d,author_name:f,author_email:g,content:p,parent:u,target_id:y,date:c_(new Date),author_avatar_urls:{}};return o.create(m)},deleteComment(c){return o.remove(c)},editComment({commentId:c,...d}){return o.update(c,d)},deleteTarget(c){return o.update(c,{target_id:""})}})}function jo(e){return{id:String(e),name:"",myRole:"",members:[],invites:[],emailsCount:0,blocksCount:0,title:"",group:[],folder:[],blockfolder:[]}}function ma(e,t){return{project:Number(e),app_id:t?.app_id||0,app_config:t?.app_config||{},user:t?.user}}function u_(e,t){const n=jo(String(t)),o=r.getCurrentProject(e).card;return o&&String(o.id)===String(t)?Promise.resolve({...n,...o,id:String(t)}):Promise.resolve({...n,id:String(t)})}function p_(e){let t,n;const o=i=>((t!==i||!n)&&(t=i,n=u_(e,i)),n);it(e)(at(e,"projectsApi"),{getProjects(i={page:1}){return[]},getProject(i){return async s=>r.isStandaloneRuntime(e)?s(i):{...await o(i),id:String(i)}},addProject(i){throw new Error},async editProject({projectId:i,...s}){const c={...await o(i),...s,id:String(i)};return t=i,n=Promise.resolve(c),c},deleteProject(i){throw new Error},mutateProjectMembers(){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},addProjectMember(){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},getFrequentProjects(){return[]}})}function m_(e){let t={id:"0",username:"",email:"",password:"",code_editor:{},theme:"light",locale:r.getCurrentUser(e).profile?.locale,counters:{},avatar_urls:{},autosaves:!0};it(e)(at(e,"authorizationApi"),{getSchema:()=>n=>n({}),getMe:()=>t,editMe:n=>t={...t,...n},getSubscriptions:()=>[]})}function f_(e){it(e)(at(e,"notificationsApi"),{getNotifications(t){return[]},notificationShown({id:t,datetime:n}){throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function g_(e){it(e)(at(e,"addUserToProjectApi"),{addUserToProject:()=>{}})}function h_(e){r.injectEmailTermsResolver(e,{resolve:async()=>{}}),it(e)(at(e,"taxonomiesApi"),{getTerms:()=>[],getStandardGroups:()=>[],addTerm:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},editTerm:t=>({id:t.id,name:t.name,parent:0,count:0}),deleteTerm:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function __(e){it(e)(at(e,"projectSettingsV2Api"),{getProjectIntegrations:()=>({}),getProjectWebhook:()=>"",getProjectStorage:()=>({}),getProjectTestRecipients:()=>[],getIntegrationCredentials:()=>({}),putProjectIntegration:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},deleteProjectIntegration:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},putProjectWebhook:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},putProjectSettings:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},putProjectTestRecipients:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}function y_(e){it(e)(at(e,"stripoImportApi"),{getStripoFolders:()=>[],getStripoItems:()=>({items:[],total:0}),getCurrentStripoImport:()=>null,getStripoImport:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},saveStripoKey:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)},startStripoImport:()=>{throw new Error(h.NOT_IMPLEMENTED_IN_PLUGIN)}})}var fa={addUserToProjectApiMock:g_,AiApiMock:e_,authorizationApiMock:m_,blocksApiMock:o_,commentsApiMock:d_,emailsApiMock:i_,emailRawApiMock:l_,imageApiMock:r_,notificationsApiMock:f_,projectsApiMock:p_,projectSettingsV2ApiMock:__,proxyApiMock:t_,saveFileApiMock:a_,stripoImportApiMock:y_,taxonomiesApiMock:h_,tokenApiMock:n_},Oo=r.createApi({reducerPath:"tokenApi",baseQuery:r.fetchBaseQueryApp({baseUrl:"https://app.useblocks.io/api/wp-json/jwt-auth/v1/"}),endpoints:e=>({tokenCreate:e.mutation({queryFn(t,n){return r.clientFromApi(n).jwtAuth.token_create({body:t,type:h.ContentType.Json})}}),tokenValidate:e.mutation({queryFn(t,n){return r.clientFromApi(n).jwtAuth.token_validate_create({type:h.ContentType.Json})}})})}),{useTokenCreateMutation:h0,useTokenValidateMutation:_0}=Oo;function Lo(){const e=new Map;for(const t of ia)e.set(t.reducerPath,t);return e.set(Oo.reducerPath,Oo),[...e.values()]}function v_(e,t){const n=Object.keys(t.endpoints);n.length&&e(t,Object.fromEntries(n.map(o=>[o,Yh])))}function b_(e){Qh(e);const t=it(e);for(const n of Lo())v_(t,n)}function E_(e){if(!e)return;const t=h.decodeJwt(e)?.data,n=t?.data?.scope??t?.scope;return(Array.isArray(n)?n.flatMap(o=>typeof o=="string"?o.split(/\s+/):[]):typeof n=="string"?n.split(/\s+/):[]).find(o=>/^project_\d+$/.test(o))?.replace(/^project_/,"")||void 0}var S_={AiApi:new Set(["sendMessage","getDialog"]),imageApi:new Set(["sendAiImageRequest","getAiImage","getAiImageSSE"])};function w_(e){return r.getAppConfig(h.getContainer(e))}function k_(e){return e?.backendProxy!==void 0&&e?.backendProxyPolicy?.proxyAi===!0}function C_(e){return k_(w_(e))}function T_(e,t,n,o){return S_[t]?.has(n)?i=>C_(e)?s=>s(i):o(i):o}function I_(e){const t=it(e);return((n,o)=>{if(!n||typeof n.reducerPath!="string")return new h.Disposable;const i=Object.fromEntries(Object.entries(o??{}).map(([s,c])=>[s,typeof c=="function"?T_(e,n.reducerPath,s,c):c]));return t(n,i)})}function A_(e){const t=`blocks_${h.generateUUID().replaceAll("-","")}`,n=document.createElement("script");return n.type="text/javascript",n.text=`window.${t}(function(module, exports, require) { ${e}; })`,new Promise((o,i)=>{window[t]=function(s){const c={exports:{}},d=()=>{};s(c,c.exports,d),o(c.exports)},document.head.appendChild(n)}).finally(()=>{n.remove(),delete window[t]})}async function ga(e){const t=h.getContainer(e),n=t?.getInstance(h.STANDALONE_PROJECT_ID),o=n?void 0:await t?.getInstanceAsync(h.APP_ID).catch(()=>{}),i=n||(o?.project!==void 0?String(o.project):void 0);i&&t&&r.setCurrentProjectCard(t,jo(i))}async function x_(e,t){try{const n=function(d){const u=e.getInstance(h.STANDALONE_PROJECT_ID),p=u?ma(u,d):d;e.injectFactory(h.APP_ID,async()=>p)},o=I_(e),i=await r.readZipFromBase64(t),s=i.key&&r.zipEntryToText(i.key);if(typeof s!="string")return;const c=await A_(s);if(typeof c!="object"||c===null||typeof c.execute!="function")return;c.execute(n,o,Lo())}catch{}}async function ha(e,t){b_(h.getContainer(e)),await x_(h.getContainer(e),t),da(h.getContainer(e),fa)}var P_=zn(async e=>{const t=Fh(e);e.inject(h.STORE_ID,t),Bh(e,Lo()),Gh(e,t),r.getDisposable(e).addDisposable(Uh(e,t)),r.getDisposable(e).addDisposable($h(e,t));const n=h.getContainer(t);n&&(e.inject(h.MESSAGE_SERVICE_ID,r.getMessageService(n)),e.inject(r.CURRENT_PROJECT_ID,r.provideCurrentProject(n)));const o=e.getInstance(h.SECURITY_MODULE_ID);return o?(await ha(t,o),await ga(t)):da(h.getContainer(t),fa),{instance:{}}}),_a=["historyEnabled","commentsEnabled","aiAssistentEnabled","livePreviewEnabled","sendTestEnabled","sharePreviewEnabled","webversionEnabled","optimizeSpamAssassinEnabled","exportWebHookEnabled","aiLayoutConverterEnabled","elementAIimageEnabled","elementAItextEnabled","revisionService"];function R_(e){const t={...e};for(const n of _a)t[n]=!1;return t}function j_(e){const t={...e};for(const n of _a)n in t&&typeof t[n]=="boolean"&&(t[n]=!1);return t}function O_(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,o]of Object.entries(e))!o||typeof o!="object"||Array.isArray(o)||(t[n]=j_(o));return Object.keys(t).length>0?t:void 0}function Mo(e){const t=R_(e),n=O_(e.advancedConfigs),o={...t};return n?o.advancedConfigs=n:delete o.advancedConfigs,o}var y0=1,L_=2592e6;function ya(){return"useblocks".trim()||void 0}function M_(e){return{schemaVersion:1,savedAt:Date.now(),project:e.project,app_id:e.app_id,app_config:Mo(ba(e.app_config))}}function va(e){return{...e,app_config:ba(e.app_config)}}function ba(e){if(!e||typeof e!="object"||Array.isArray(e))return{};try{if(typeof structuredClone=="function")return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return{}}}async function N_(e){const t=ya();t&&await G_(t,M_(e))}async function D_(e=Date.now()){const t=ya();if(t)return W_(t,e)}function F_(e,t=Date.now()){return e.savedAt>t?!1:t-e.savedAt<=L_}function Ea(e){if(!e||typeof e!="object")return!1;const t=e,n=typeof t.project=="number"&&Number.isFinite(t.project)||typeof t.project=="string"&&t.project.trim()!=="";return t.schemaVersion===1&&typeof t.savedAt=="number"&&Number.isFinite(t.savedAt)&&n&&typeof t.app_id=="number"&&Number.isFinite(t.app_id)&&t.app_config!=null&&typeof t.app_config=="object"&&!Array.isArray(t.app_config)}var jt="snapshots",B_=1;function $_(){return`${"useblocks".trim()||"plugin"}-plugin-deferred-config`}function Lr(){return new Promise((e,t)=>{if(typeof indexedDB>"u"){t(new Error("indexedDB is not available"));return}const n=indexedDB.open($_(),B_);n.onerror=()=>t(n.error||new Error("indexedDB open failed")),n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(jt)||o.createObjectStore(jt)},n.onsuccess=()=>e(n.result)})}function U_(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error||new Error("indexedDB request failed"))})}function z_(){return{async get(e){const t=await Lr();try{const n=await U_(t.transaction(jt,"readonly").objectStore(jt).get(e));return n===void 0?void 0:n}finally{t.close()}},async put(e,t){const n=await Lr();try{const o=n.transaction(jt,"readwrite");o.objectStore(jt).put(t,e),await new Promise((i,s)=>{o.oncomplete=()=>i(),o.onerror=()=>s(o.error||new Error("indexedDB write failed")),o.onabort=()=>s(o.error||new Error("indexedDB write aborted"))})}finally{n.close()}},async delete(e){const t=await Lr();try{const n=t.transaction(jt,"readwrite");n.objectStore(jt).delete(e),await new Promise((o,i)=>{n.oncomplete=()=>o(),n.onerror=()=>i(n.error||new Error("indexedDB delete failed")),n.onabort=()=>i(n.error||new Error("indexedDB delete aborted"))})}finally{t.close()}},async clear(){const e=await Lr();try{const t=e.transaction(jt,"readwrite");t.objectStore(jt).clear(),await new Promise((n,o)=>{t.oncomplete=()=>n(),t.onerror=()=>o(t.error||new Error("indexedDB clear failed")),t.onabort=()=>o(t.error||new Error("indexedDB clear aborted"))})}finally{e.close()}}}}var Sa,No;function Do(){return Sa||(No||(No=z_()),No)}function wa(e){Do().delete(e).catch(()=>{})}async function G_(e,t){if(Ea(t))try{await Do().put(e,va(t))}catch{}}async function W_(e,t=Date.now()){try{const n=await Do().get(e);if(n===void 0)return;if(!Ea(n)){wa(e);return}if(!F_(n,t)){wa(e);return}return va(n)}catch{return}}function H_(e,t){if(e.getInstance(h.STANDALONE_FILE_PROXY_REGISTERED_ID))return;e.inject(h.STANDALONE_FILE_PROXY_REGISTERED_ID,!0);const n=h.getEvent(e,h.events.FILE_PROXY_EVENT_ID);t.addDisposable(n(async({url:o})=>(await fetch(o)).blob(),Number.MIN_VALUE))}function ka(e){try{return E_(e)||void 0}catch{return}}async function q_(e,t,n){if(!e)return;let o;try{const i=await e(t,n,void 0);o=String(i||"").trim()}catch{return}if(o)return{token:o,serverProjectId:ka(o)}}function V_(e){if(e==null)return;const t=String(e).trim();return/^\d+$/.test(t)?t:void 0}function K_(e){const t=String(e.getInstance(h.JWT_TOKEN_ID)||"").trim();if(t)return ka(t)}function Ca(e,t,n){e.inject(h.APP_ID,void 0),e.inject(h.APP_ID,Promise.resolve(ma(t,n)))}function Y_(e){return{app_id:e.app_id,app_config:Mo(e.app_config)}}async function Ta(){const e=await D_();return e?Y_(e):{app_config:Mo({})}}function Q_(e,t){e.getInstance(h.STANDALONE_ACTIVATED_ID)||(e.inject(h.SECURITY_MODULE_ID,void 0),e.inject(h.STANDALONE_BOOTSTRAP_TOKEN_ID,void 0),e.inject(h.STANDALONE_PROJECT_ID,void 0),t&&e.inject(h.APP_ID,void 0),e.inject(h.STANDALONE_FILE_PROXY_REGISTERED_ID,void 0))}async function Ia(e){const{container:t,store:n,standaloneKey:o,project:i,reason:s,getAuthToken:c,user:d}=e,u=e.disposable||t.getInstance(h.DISPOSABLE_ID);if(t.getInstance(h.STANDALONE_ACTIVATED_ID))return;const p=await q_(c,d,i),f=V_(i),g=p?.serverProjectId??K_(t)??(p?void 0:f);t.inject(h.SECURITY_MODULE_ID,o);let y=!1;try{if(p&&(t.inject(h.STANDALONE_BOOTSTRAP_TOKEN_ID,Promise.resolve(p.token)),c&&h.recreateTokenProvider(t,c,d,i)),g){const m=await Ta();t.inject(h.STANDALONE_PROJECT_ID,g),Ca(t,g,m),y=!0,r.setCurrentProjectCard(t,jo(g))}if(await ha(n,o),y=!0,!g){await ga(n);const m=t.getInstance(h.STANDALONE_PROJECT_ID);if(m)Ca(t,m,await Ta()),y=!0;else if(t.getInstance(h.APP_ID)!==void 0)try{(await t.getInstanceAsync(h.APP_ID))?.project==null}catch{}}u&&H_(t,u),t.inject(h.STANDALONE_ACTIVATED_ID,!0)}catch(m){throw Q_(t,y),m}}async function X_(e,t,n,o){const i=o?.attemptTimeout??h.isFailoverEnabled(n),s=h.isFailoverEnabled(n)?h.getOrderedOriginCandidates(n):h.getOriginChain(n).length>0?[h.getActiveBaseUrl(n)]:[];if(s.length===0)throw new Error("[apiOriginFailover] no API base URL configured");const c=e.startsWith("/")?e:`/${e}`;let d,u;for(let p=0;p<s.length;p++){const f=s[p],g=p===s.length-1,y=i?h.beginFailoverAttempt(t.signal):void 0;try{const m=await fetch(`${f}${c}`,{...t,...y?{signal:y.signal}:{}});if(!m.ok&&h.shouldFailoverResponse(m.status)){if(d=m,!g){h.reportOriginFailure(f,n);continue}break}return m.ok&&h.reportOriginSuccess(f,n),m}catch(m){const E=y?.timeoutError();if(!E&&!h.shouldFailoverError(m))throw m;u=E||m,g||h.reportOriginFailure(f,n)}finally{y?.done()}}if(h.isFailoverEnabled(n)&&h.abandonStickyOrigin(),d)return d;throw u instanceof Error?u:new Error("[apiOriginFailover] fetch chain failed")}function J_(e,t){const n=String(t.baseUrl||"").trim();if(n)return h.resolveExplicitApiBaseUrl(n);const o=e.getInstance(h.REST_CLIENT_FACTORY_ID),i=String(o?.getOptions()?.baseUrl||"").trim();return h.resolveExplicitApiBaseUrl(i||void 0)}async function Z_(e,t){if(t.getAuthToken)try{const n=await t.getAuthToken(t.user,t.project,void 0);if(String(n||"").trim())return!0}catch{if(!t.jwtAuth)return!1}if(t.jwtAuth)try{if(String(e.getInstance(h.JWT_TOKEN_ID)||"").trim())return!0;const n=J_(e,t);if(!n)return!1;const o=await X_("/jwt-auth/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.jwtAuth)},n,{attemptTimeout:!0});if(!o.ok)return!1;const i=await o.json();return i.token?(e.inject(h.JWT_ERROR_ID,void 0),e.inject(h.JWT_TOKEN_ID,i.token),!0):!1}catch{return!1}return!1}async function ey(e){try{if(e.getInstance(h.APP_ID)===void 0)return!1;const t=await ny(e.getInstanceAsync(h.APP_ID));return t!=null&&t.project!=null?t:!1}catch{return!1}}function ty(){return h.getFailoverAttemptTimeoutMs()*Math.max(1,h.getOriginChain().length)}function ny(e){const t=ty();return new Promise((n,o)=>{const i=setTimeout(()=>{n(void 0)},t);e.then(s=>{clearTimeout(i),n(s)},s=>{clearTimeout(i),o(s)})})}function Aa(e){return String(e.standaloneKey||"").trim()||void 0}function ry(e){return e.standaloneOnAuthFailure===!0?!0:e.config?.standaloneOnAuthFailure===!0}function oy(e){return ry(e)?!!Aa(e):!1}var iy=zn(async e=>{const t=e.getInstance(h.DISPOSABLE_ID),n=()=>e.getInstanceAsync(h.STORE_ID);return{async setOptions(o){if(!oy(o)){e.getInstance(h.STANDALONE_ACTIVATED_ID);return}const i=Aa(o);if(!i||e.getInstance(h.STANDALONE_ACTIVATED_ID))return;const s=await n(),c=!!(o.getAuthToken||o.jwtAuth),d=c?await Z_(e,o):!0;if(c&&!d){await Ia({container:e,store:s,standaloneKey:i,project:o.project,getAuthToken:o.getAuthToken,user:o.user,disposable:t,reason:"auth pipeline failed"});return}const u=await ey(e);if(u){await N_(u).catch(()=>{});return}await Ia({container:e,store:s,standaloneKey:i,project:o.project,getAuthToken:o.getAuthToken,user:o.user,disposable:t,reason:"app_init failed"})}}}),sy=h.defineMixin(e=>{let t;const n=r.getDisposable(e),o=h.getEvent(e,h.events.ON_DOCUMENT_SESSION_CHANGE);n.addDisposable(o(({history:s})=>{t=s}));const i=()=>t?Ni(t):void 0;return{instance:{undoRedoService:{undo:()=>i()?.undo(),redo:()=>i()?.redo(),clear:()=>i()?.clear(),getPast:s=>i()?.getPast(s)??[],getFuture:s=>i()?.getFuture(s)??[],canUndo:()=>i()?.canUndo()??!1,canRedo:()=>i()?.canRedo()??!1,createSnapshot:()=>i()?.createSnapshot(),restoreSnapshot:s=>i()?.restoreSnapshot(s)}}}});function ay(e){return{font_size:e.fontSize,font_family:e.fontFamily,tab_size:e.tabSize,word_wrap:e.wordWrap,minimap:e.minimap,insert_spaces:e.insertSpaces}}function ly(e){return{fontSize:e.fontSize,fontFamily:e.fontFamily,tabSize:e.tabSize,wordWrap:e.wordWrap!=="off",minimap:e.minimap?.enabled,insertSpaces:e.insertSpaces}}async function xa(e){const t=r.getCurrentUser(e).profile;if(t)return t;const n=e.getInstance(h.STORE_ID);if(n)return(await n.dispatch(r.authorizationApi.endpoints.getMe.initiate("",{forceRefetch:!0}))).data}function cy(e){const t=r.resolveTemplateDirectivesConfig(e);if(!(Object.keys(t.output).length>0||Object.keys(t.editor).length>0))return fs();const n=new Set(Object.keys(t.output).filter(i=>t.output[i]==="html-comment")),o=new Set(Object.keys(t.output));return{isConfigured:()=>!0,toEditorForm:i=>r.mapper.normalizeToPolicy(i,t.editor),toOutputForm:i=>r.mapper.normalizeToPolicy(i,t.output),keepWrappedOnOutput:n,editorPolicy:t.editor,warnAboutUnconfiguredInput:ms(o)}}function Pa(e){const t=r.getCodeMode(e);return{...Mr(e),editor:ly(r.getEditorOptions(e)),codeModeDirection:t.isCodeMode?t.direction:"none"}}function Mr(e){return e.getInstance(h.CONFIG_SOURCE_ID)?.get()??{}}function Fo(e){return e.getInstance(h.CONFIG_SOURCE_ID)?.layers()??{base:{},profile:{},serverSide:{},user:{},local:{},advancedConfigs:{}}}var dy=bo(e=>{const t=r.getDisposable(e),n=Ct(r.getEvent(e,h.events.ON_LIMIT_ID)),o=t.addDisposable(new kt(n)),i=Ct(r.getEvent(e,h.events.READ_LOCALE)),s=t.addDisposable(new kt(i)),c=Ct(r.getEvent(e,h.events.ON_TRANSLATE_ID)),d=t.addDisposable(new kt(c)),u=r.getEmitter(e,h.CONFIG_CHANGED_EVENT_ID),p=async()=>{try{return e.getInstance(h.APP_ID)===void 0?{}:(await e.getInstanceAsync(h.APP_ID))?.app_config||{}}catch{return{}}},f=Bs(),g=Bs();let y,m=!1,E;const k=async()=>{const A=Pa(e);if(!m){E=h.deepClone(A),m=!0;return}E!==void 0&&h.deepEqual(E,A)||(E=h.deepClone(A),await u.fire(A))},w=A=>{if(typeof A=="number")return String(A);if(typeof A=="string")return A},v=A=>{if(A!==void 0){const O=r.provideCurrentProject(e);O.set({...O.get(),requested:String(A)})}},x=async(A,O)=>{if(!A){const Z=await xa(e);return y=w(Z?.id),{didReset:!1}}const z=await xa(e),B=A.id!==void 0?w(A.id):w(z?.id),U=y!==void 0?String(y):void 0,de=B!==void 0?String(B):void 0,me=U!==void 0&&de!==void 0&&U!==de,H={...z,...r.filterUndefined(A),id:B};if(A.id===void 0&&!z?.id&&delete H.id,r.provideCurrentUser(e).set({profile:H}),me&&O){const Z=e.getInstance(h.INSTANCE_ID);if(Z?.reset)return await Z.reset(O),{didReset:!0}}return y=de,{didReset:!1}},P=A=>{const O=e.getInstance(h.CONFIG_SOURCE_ID);O?.setAdvancedConfigs({...A.advancedConfigs,...A.user?.advancedConfigs}),O?.replace(A.user,"user"),O?.replace(A.serverSide,"server")},K=async()=>{await e.getInstance(h.CONFIG_SOURCE_ID)?.ready(),r.getRevisionServiceFlag(e).set(Mr(e).revisionService===!0);const{codeModeDirection:A,editor:O}=Mr(e);O&&r.applyEditorOptions(e,ay(O)),A!==void 0&&(A==="none"?r.setCodeMode$1(e,!1):(r.setCodeMode$1(e,!0),r.setCodeModeDirection(e,A)))},J=async A=>{P(A),await K()};let N;const L=f.decorate(async({config:A={},project:O,user:z,advancedConfigs:B},U)=>{e.getInstance(h.CONFIG_SOURCE_ID)?.replace(await p(),"server"),await K(),e.inject(h.TEMPLATE_DIRECTIVES_ID,cy(Mr(e).templateDirectives)),v(O),U&&"commonStyles"in U&&r.setDefaultCommonStyles(e,U.commonStyles===void 0?void 0:U.commonStyles);const{didReset:de}=await x(z,U)});return{setOptions:g.decorate(async A=>{const{config:O={},project:z,user:B,advancedConfigs:U,handleReadLocale:de,handleLimitUsage:me,handleTranslate:H,storageProvider:Z}=A;e.inject(h.STORAGE_PROVIDER_ID,Z),s.setListener(de),o.setListener(me),d.setListener(H),await L({config:O,project:z,user:B,advancedConfigs:U},A).catch(De=>{}),await k(),N&&N.dispose(),N=new h.Disposable}),instance:{setConfig:g.decorate(async A=>{const O=A,{commonStyles:z,...B}=O;"commonStyles"in O&&r.setDefaultCommonStyles(e,z===void 0?void 0:z),await J({advancedConfigs:Fo(e).advancedConfigs,serverSide:await p(),user:B}),await k()}),getConfig:()=>Pa(e),updateConfig:g.decorate(async A=>{const O=A,{commonStyles:z,...B}=O;"commonStyles"in O&&r.setDefaultCommonStyles(e,z===void 0?void 0:z),await J({advancedConfigs:Fo(e).advancedConfigs,serverSide:await p(),user:{...Fo(e).user,...B}}),await k()}),handleReadLocale:i,handleLimitUsage:n,handleTranslate:c}}}),Nr;function Bo(){return Nr===void 0&&(Nr=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/4916b3a1.js")),void 0,{}.url).catch(e=>{throw Nr=void 0,e})),Nr}var Ra;function uy(){return Ra??=(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/e47dcbb0.js")).then(e=>zt.__toESM(e.require_core())),void 0,{}.url),Ra}function py(e){const t=[0],n=[];let o=0;for(;o<e.length;){const i=e.charCodeAt(o);i===10||i===13?(n.push(o-t[t.length-1]),o+=i===13&&e.charCodeAt(o+1)===10?2:1,t.push(o)):o+=1}return n.push(e.length-t[t.length-1]),{starts:t,lengths:n}}function ja({starts:e,lengths:t},n,o){const i=Math.min(Math.max(n,1),e.length)-1;return e[i]+Math.min(Math.max(o,1),t[i]+1)-1}var my={error:8,warning:4,info:2};function fy(e,t){const n=e.evidence!==""?e.col+e.evidence.length:t.lengths[e.line-1]??e.col+1;return{severity:my[e.type]??8,message:e.message,startLineNumber:e.line,startColumn:e.col,endLineNumber:e.line,endColumn:n,startOffset:ja(t,e.line,e.col),endOffset:ja(t,e.line,n)}}async function gy(e){const{HTMLHint:t}=await uy(),n=py(e);return t.verify(e,r.EMAIL_CODE_RULESET).map(o=>fy(o,n))}var hy=class extends h.Disposable{_container;_dataSources;_currentEmail;_blockMetaWrites=Promise.resolve();constructor(e){super(),this._container=e,this._dataSources=r.getDataSources(e),this.addDisposable(h.getEvent(e,h.events.ON_EMAIL_CHANGED_ID)(t=>{this._currentEmail=t}))}async getBlocks(){const e=await this._readProjectBlocks();return await this._blockMetaWrites,(await this._dataSources.blocks.cache.values()).filter(t=>t.project===e).map(t=>Og(t,this._container))}async _readProjectBlocks(){const e=await r.getBlocksProject(this._container);return await this._dataSources.blocks.byForeignKey("project").get(e),e}async getComments(){const{cache:e}=this._dataSources.comments,t=await this.getEmailSnapshot();return(await e.values()).filter(n=>n.post===t.id).map(n=>Lg(n,this._container))}async getEmailRevisions(){const{cache:e}=this._dataSources.emailRevisions,t=await this.getEmailSnapshot();return(await e.values()).filter(n=>n.parent===t.id).map(n=>Mg(n,this._container))}async getEmailSnapshot(){return Up(r.getOpenEmail(this._container,this._currentEmail),this._container)}async getEmail(e=!0){return this.compile(e)}async compileEmail(e=!0){return this.compile(e)}async compile(e){const{compileEmail:t}=await Bo();return t(await this.getEmailSnapshot(),e,on(this._container).keepWrappedOnOutput)}setEmailMeta(e){const t=r.getOpenDocument(this._container);if(!t)return;const n=t.get().attributes.meta;r.writeEmailAttributes(t,{meta:r.applyMetaPatch({meta:n},e).meta});const o=t.get().serverId;o!=null&&this._dataSources.emails.cache.addOrUpdate(o,i=>i&&r.applyMetaPatch(i,e))}setBlockMeta(e,t){const n=async()=>{await this._readProjectBlocks();const{cache:o}=this._dataSources.blocks;await o.getIfPresent(e)&&await o.addOrUpdate(e,i=>i&&r.applyMetaPatch(i,t))};this._blockMetaWrites=this._blockMetaWrites.then(n).catch(()=>{})}getCodeErrors(){const e=r.getCodeErrors(this._container);return e.length>0?e:void 0}validateCode(){return Promise.resolve(gy(r.getOpenEmail(this._container,this._currentEmail).html??""))}};function Oa(){Bo().catch(()=>{})}function _y(e){const t=r.provideHeadlessMode(e).watch(n=>{n&&Oa()});e.getInstance(h.DISPOSABLE_ID)?.addDisposable(t),Ht(e).whenVisible(()=>{Xt(Oa)})}var yy=h.createIdentifier$1("EmailOperationsController");function La(e){return e.getOrCreateInstance(yy,()=>{const t=new hy(e);return e.getInstance(h.DISPOSABLE_ID)?.addDisposable(t),t})}function vy(e){La(e),_y(e)}function by(e){const t=La(e);return{getEmailSnapshot:()=>t.getEmailSnapshot(),getEmail:()=>t.getEmail(),async compileEmail(n,o=!0){if(!n)return t.compileEmail(o);const{compileEmail:i}=await Bo();return i(n,o,on(e).keepWrappedOnOutput)},validateCode:()=>t.validateCode(),getCodeErrors:()=>t.getCodeErrors(),getBlocks:()=>t.getBlocks(),getComments:()=>t.getComments(),getEmailRevisions:()=>t.getEmailRevisions(),setEmailMeta:n=>t.setEmailMeta(n),setBlockMeta:(n,o)=>t.setBlockMeta(n,o)}}var Ey=h.defineMixin(e=>{const t=e.getInstance(h.DISPOSABLE_ID),n=h.getEvent(e,h.events.UPLOAD_EVENT_ID),o=h.getEvent(e,h.events.FILE_PROXY_EVENT_ID),i=h.getEmitter(e,h.events.PROXY_URL_EVENT_ID).event,s=Ct(n),c=Ct(i),d=Ct(o),u=t.addDisposable(new kt(s)),p=t.addDisposable(new kt(d)),f=t.addDisposable(new kt(c));return{setOptions(g){u.setListener(g.handleLoadImage),p.setListener(g.handleFileProxy),f.setListener(g.handleUrlProxy)},instance:{handleLoadImage:s,handleFileProxy:d,handleUrlProxy:c}}}),Sy=h.defineMixin(e=>{const t=e.getInstance(h.DISPOSABLE_ID),n=h.getEvent(e,h.events.AI_TEXT_REQUEST_ID),o=h.getEvent(e,h.events.AI_IMAGE_REQUEST_ID),i=Ct(n),s=Ct(o),c=t.addDisposable(new kt(i)),d=t.addDisposable(new kt(s));return{setOptions(u){c.setListener(u.handleAITextRequest),d.setListener(u.handleAIImageRequest)},instance:{handleAITextRequest:i,handleAIImageRequest:s}}}),wy=class extends Error{cycle;constructor(e){super(`[units] цикл в зависимостях: ${e.join(" → ")}`),this.cycle=e}};function ky(e){const t=new Map;for(const n of e)for(const o of n.provides??[]){const i=t.get(o)??[];i.push(n),t.set(o,i)}return t}function Cy(e,t){const n=[];for(const o of e.awaits?.services??[])for(const i of t.get(o)??[])i!==e&&n.push(i);return n}function Ty(e){const t=ky(e),n=[],o=new Set,i=[],s=new Set,c=d=>{if(!o.has(d)){if(s.has(d)){const u=i.indexOf(d);throw new wy([...i.slice(u),d].map(p=>p.name))}s.add(d),i.push(d);for(const u of Cy(d,t))c(u);i.pop(),s.delete(d),o.add(d),n.push(d)}};for(const d of e)c(d);return n}var Iy="author,slug,date,modified,title,acf.html,id,parent,date_gmt",Ay="author,slug,date,modified,modified_gmt,title,acf.html,id,parent",xy=20,$o=[h.WpEblockApi];function Ma(e){return typeof e=="string"&&e?`${e.replace(/Z$/,"")}Z`:void 0}function Py(e){return{async readRevisions(t,n=1){const o=await h.getApi(e,$o).eblock_revisions_list({parent:t,per_page:xy,page:n},{extraQuery:{_fields:Iy}}),i=(o?.data??[]).map(c=>r.WpBlockRevisionToBlockRevision(c)),s=Number(o?.headers?.get("X-WP-TotalPages"));return{revisions:i,page:n,hasMore:Number.isFinite(s)&&n<s}},async readAutosave(t){const n=h.getApi(e,$o),[o,i]=await Promise.all([n.eblock_autosaves_list({id:t},{extraQuery:{_fields:Ay}}),n.eblock_detail({id:t},{extraQuery:{_fields:"modified_gmt"}})]),s=(o?.data??[]).map(d=>{const u=d,p=r.WpBlockRevisionToBlockRevision(u),f=Ma(u.modified_gmt);return f?{...p,modified:f}:p}),c=Date.parse(Ma(i?.data?.modified_gmt)??"");return r.autosaveStateFromSlots(s,Number.isFinite(c)?c:void 0)},async saveAutosave(t,n){const o=n,i=o.global_block&&o.html?r.injectEmBlockIdIntoBlockHtml(o.html,t):o.html??"";r.writePendingData(t,{sentAt:Date.now(),html:i,common_styles:""});const s=await h.getApi(e,$o).eblock_autosaves_create({id:t},r.BlockAutoSaveToWpBlockAutoSave({title:o.title,html:i,project:o.project,excerpt:new Date().toISOString()}),{type:h.ContentType.FormData});return r.WpBlockRevisionToBlockRevision(s?.data)}}}var Ry="author,slug,date,modified,title,meta,acf.html,acf.common_styles,id,parent,date_gmt",jy="author,slug,date,modified,modified_gmt,title,meta,acf.html,acf.common_styles,id,parent";function Na(e){return typeof e=="string"&&e?`${e.replace(/Z$/,"")}Z`:void 0}var Oy=20,Uo=[h.WpEmailApi];function Ly(e){return{async readRevisions(t,n=1){const o=await h.getApi(e,Uo).email_revisions_list({parent:t,per_page:Oy,page:n},{extraQuery:{_fields:Ry}}),i=(o?.data??[]).map(c=>r.WpEmailRevisionToEmailRevision(c)),s=Number(o?.headers?.get("X-WP-TotalPages"));return{revisions:i,page:n,hasMore:Number.isFinite(s)&&n<s}},async readAutosave(t){const n=h.getApi(e,Uo),[o,i]=await Promise.all([n.email_autosaves_list({id:t},{extraQuery:{_fields:jy}}),n.email_detail({id:t},{extraQuery:{_fields:"modified_gmt"}})]),s=(o?.data??[]).map(d=>{const u=d,p=r.WpEmailRevisionToEmailRevision(u),f=Na(u.modified_gmt);return f?{...p,modified:f}:p}),c=Date.parse(Na(i?.data?.modified_gmt)??"");return r.autosaveStateFromSlots(s,Number.isFinite(c)?c:void 0)},async saveAutosave(t,n){const o=await h.getApi(e,Uo).email_autosaves_create({id:t},r.EmailAutoSaveToWpEmailAutoSave({...n,excerpt:new Date().toISOString()}),{type:h.ContentType.FormData});return r.WpEmailRevisionToEmailRevision(o?.data)}}}var Da=["_embedded","id","author","title","meta","emailtags","folder","group","modified","date","type","parent","date_gmt","acf.description","acf.html","acf.common_styles","acf.is_template","acf.lock","acf.parent_email","acf.project","acf.secret_hash","acf.subject","acf.utm_parameters"].join(","),zo=[h.WpEmailApi],Fa=e=>r.EmailToWpEmail(e);function My(e){return{async readEmail(t){const n=await h.getApi(e,zo).email_detail({id:r.toNumberSafe(t)},{extraQuery:{_embed:"wp:term",_fields:Da}});if(!n)throw new r.EmailOpenFailedError("unavailable");if(n.ok===!1)throw r.openFailureFromResponse(n);return n.data?r.WpEmailToEmail(n.data):null},async createEmail(t){const n={status:"publish",...Fa(t)},o=await h.getApi(e,zo).email_create(n,{type:h.ContentType.Json});return r.WpEmailToEmail(o?.data)},async updateEmail(t,n){const o=await h.getApi(e,zo).email_partial_update({id:t},Fa(n),{type:h.ContentType.Json,extraQuery:{_embed:"wp:term",_fields:Da}});return r.WpEmailToEmail(o?.data)}}}function Ny(e){r.injectRestEmailPortFactories(e,{email:My,history:Ly,blockHistory:Py})}var Go=20,Dy=({source:e,emailtags:t,group:n,tags:o,...i})=>i;function Fy({revisions:e,revisionsByBlock:t}){const n=async(o,i)=>(t.clear(),await t.get(o,{page:i}),(await e.cache.values()??[]).filter(s=>String(s?.parent)===String(o)));return{async readRevisions(o,i=1){const s=await n(o,i);return{revisions:s.slice(Go*(i-1),Go*i),page:i,hasMore:s.length>Go*i}},async readAutosave(o){return r.autosaveStateFromRevisions(await n(o,1))},async saveAutosave(o,i){const s=Dy(i);return await e.create({...s,parent:o,modified:new Date().toString()})}}}var Ba=h.createIdentifier$1("blockDocuments.provided");function By(e){if(e.getInstance(Ba))return;e.inject(Ba,!0);const t=r.blockRevisionsDataSourceProvider(e);r.injectBlockHistoryPort(e,Fy({revisions:t,revisionsByBlock:t.byForeignKey("parent")}))}var $y=zt.__commonJSMin(((e,t)=>{(function(n){if(typeof window>"u")return;var o=0,i,s=!1,c=!1,d=7,u="[iFrameSizer]",p=u.length,f=null,g=window.requestAnimationFrame,y=Object.freeze({max:1,scroll:1,bodyScroll:1,documentElementScroll:1}),m={},E=null,k=Object.freeze({autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,license:"1jqr0si6pnt",log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,mouseEvents:!0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",onClose:function(){return!0},onClosed:function(){},onInit:function(){},onMessage:function(){O("onMessage function not defined")},onMouseEnter:function(){},onMouseLeave:function(){},onResized:function(){},onScroll:function(){return!0}});function w(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function v(C,T,R){C.addEventListener(T,R,!1)}function x(C,T,R){C.removeEventListener(T,R,!1)}function P(){for(var C=["moz","webkit","o","ms"],T=0;T<C.length&&!g;T+=1)g=window[C[T]+"RequestAnimationFrame"];g?g=g.bind(window):L("setup","RequestAnimationFrame not supported")}function K(C){var T="Host page: "+C;return window.top!==window.self&&(T=window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+C:"Nested host page: "+C),T}function J(C){return u+"["+K(C)+"]"}function N(C){return m[C]?m[C].log:s}function L(C,T){z("log",C,T,N(C))}function A(C,T){z("info",C,T,N(C))}function O(C,T){z("warn",C,T,!0)}function z(C,T,R,D){D===!0&&window.console}function B(C){function T(){function $(){et(oe),Z(ee),Ge("onResized",oe)}S("Height"),S("Width"),be($,oe,"init")}function R(){var $=Xe.slice(p).split(":"),le=$[1]?parseInt($[1],10):0,xe=m[$[0]]&&m[$[0]].iframe,Se=getComputedStyle(xe);return{iframe:xe,id:$[0],height:le+D(Se)+I(Se),width:$[2],type:$[3]}}function D($){return $.boxSizing!=="border-box"?0:($.paddingTop?parseInt($.paddingTop,10):0)+($.paddingBottom?parseInt($.paddingBottom,10):0)}function I($){return $.boxSizing!=="border-box"?0:($.borderTopWidth?parseInt($.borderTopWidth,10):0)+($.borderBottomWidth?parseInt($.borderBottomWidth,10):0)}function S($){var le=Number(m[ee]["max"+$]),xe=Number(m[ee]["min"+$]),Se=$.toLowerCase(),Me=Number(oe[Se]);L(ee,"Checking "+Se+" is in range "+xe+"-"+le),Me<xe&&(Me=xe,L(ee,"Set "+Se+" to min value")),Me>le&&(Me=le,L(ee,"Set "+Se+" to max value")),oe[Se]=""+Me}function ae(){function $(){function Se(){var We=0,Be=!1;for(L(ee,"Checking connection is from allowed list of origins: "+xe);We<xe.length;We++)if(xe[We]===le){Be=!0;break}return Be}function Me(){var We=m[ee]&&m[ee].remoteHost;return L(ee,"Checking connection is from: "+We),le===We}return xe.constructor===Array?Se():Me()}var le=C.origin,xe=m[ee]&&m[ee].checkOrigin;if(xe&&""+le!="null"&&!$())throw new Error("Unexpected message received from: "+le+" for "+oe.iframe.id+". Message was: "+C.data+". This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.");return!0}function we(){return u===(""+Xe).slice(0,p)&&Xe.slice(p).split(":")[0]in m}function Ye(){var $=oe.type in{true:1,false:1,undefined:1};return $&&L(ee,"Ignoring init message from meta parent page"),$}function Qe($){return Xe.slice(Xe.indexOf(":")+d+$)}function ze($){L(ee,"onMessage passed: {iframe: "+oe.iframe.id+", message: "+$+"}"),Ge("onMessage",{iframe:oe.iframe,message:JSON.parse($)}),L(ee,"--")}function Ze(){var $=document.body.getBoundingClientRect(),le=oe.iframe.getBoundingClientRect();return JSON.stringify({iframeHeight:le.height,iframeWidth:le.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(le.top-$.top,10),offsetLeft:parseInt(le.left-$.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,documentHeight:document.documentElement.clientHeight,documentWidth:document.documentElement.clientWidth,windowHeight:window.innerHeight,windowWidth:window.innerWidth})}function pt($,le){function xe(){fe("Send Page Info","pageInfo:"+Ze(),$,le)}Te(xe,32,le)}function bt(){function $(Me,We){function Be(){m[Se]?pt(m[Se].iframe,Se):le()}["scroll","resize"].forEach(function(ot){L(Se,Me+ot+" listener for sendPageInfo"),We(window,ot,Be)})}function le(){$("Remove ",x)}function xe(){$("Add ",v)}var Se=ee;xe(),m[Se]&&(m[Se].stopPageInfo=le)}function ft(){m[ee]&&m[ee].stopPageInfo&&(m[ee].stopPageInfo(),delete m[ee].stopPageInfo)}function lt(){var $=!0;return oe.iframe===null&&(O(ee,"IFrame ("+oe.id+") not found"),$=!1),$}function G($){var le=$.getBoundingClientRect();return H(ee),{x:Math.floor(Number(le.left)+Number(f.x)),y:Math.floor(Number(le.top)+Number(f.y))}}function V($){function le(){f=We,te(),L(ee,"--")}function xe(){return{x:Number(oe.width)+Me.x,y:Number(oe.height)+Me.y}}function Se(){window.parentIFrame?window.parentIFrame["scrollTo"+($?"Offset":"")](We.x,We.y):O(ee,"Unable to scroll to requested position, window.parentIFrame not found")}var Me=$?G(oe.iframe):{x:0,y:0},We=xe();L(ee,"Reposition requested from iFrame (offset x:"+Me.x+" y:"+Me.y+")"),window.top===window.self?le():Se()}function te(){Ge("onScroll",f)===!1?De():Z(ee)}function ue($){function le(){var Be=G(We);L(ee,"Moving to in page link (#"+Se+") at x: "+Be.x+" y: "+Be.y),f={x:Be.x,y:Be.y},te(),L(ee,"--")}function xe(){window.parentIFrame?window.parentIFrame.moveToAnchor(Se):L(ee,"In page link #"+Se+" not found and window.parentIFrame not found")}var Se=$.split("#")[1]||"",Me=decodeURIComponent(Se),We=document.getElementById(Me)||document.getElementsByName(Me)[0];We?le():window.top===window.self?L(ee,"In page link #"+Se+" not found"):xe()}function he($){var le={};if(Number(oe.width)===0&&Number(oe.height)===0){var xe=Qe(9).split(":");le={x:xe[1],y:xe[0]}}else le={x:oe.width,y:oe.height};Ge($,{iframe:oe.iframe,screenX:Number(le.x),screenY:Number(le.y),type:oe.type})}function Ge($,le){return U(ee,$,le)}function qe(){switch(m[ee]&&m[ee].firstRun&&Le(),oe.type){case"close":me(oe.iframe);break;case"message":ze(Qe(6));break;case"mouseenter":he("onMouseEnter");break;case"mouseleave":he("onMouseLeave");break;case"autoResize":m[ee].autoResize=JSON.parse(Qe(9));break;case"scrollTo":V(!1);break;case"scrollToOffset":V(!0);break;case"pageInfo":pt(m[ee]&&m[ee].iframe,ee),bt();break;case"pageInfoStop":ft();break;case"inPageLink":ue(Qe(9));break;case"reset":ve(oe);break;case"init":T(),Ge("onInit",oe.iframe);break;default:Number(oe.width)===0&&Number(oe.height)===0?O("Unsupported message received ("+oe.type+"), this is likely due to the iframe containing a later version of iframe-resizer than the parent page"):T()}}function st($){var le=!0;return m[$]||(le=!1,O(oe.type+" No settings for "+$+". Message was: "+Xe)),le}function Bt(){for(var $ in m)fe("iFrame requested init",Y($),m[$].iframe,$)}function Le(){m[ee]&&(m[ee].firstRun=!1)}var Xe=C.data,oe={},ee=null;Xe==="[iFrameResizerChild]Ready"?Bt():we()?(oe=R(),ee=oe.id,m[ee]&&(m[ee].loaded=!0),!Ye()&&st(ee)&&(L(ee,"Received: "+Xe),lt()&&ae()&&qe())):A(ee,"Ignored: "+Xe)}function U(C,T,R){var D=null,I=null;if(m[C])if(D=m[C][T],typeof D=="function")I=D(R);else throw new TypeError(T+" on iFrame["+C+"] is not a function");return I}function de(C){var T=C.id;delete m[T]}function me(C){var T=C.id;if(U(T,"onClose",T)===!1){L(T,"Close iframe cancelled by onClose event");return}L(T,"Removing iFrame: "+T);try{C.parentNode&&C.parentNode.removeChild(C)}catch(R){O(R)}U(T,"onClosed",T),L(T,"--"),de(C),i&&(i.disconnect(),i=null)}function H(C){f===null&&(f={x:window.pageXOffset===n?document.documentElement.scrollLeft:window.pageXOffset,y:window.pageYOffset===n?document.documentElement.scrollTop:window.pageYOffset},L(C,"Get page position: "+f.x+","+f.y))}function Z(C){f!==null&&(window.scrollTo(f.x,f.y),L(C,"Set page position: "+f.x+","+f.y),De())}function De(){f=null}function ve(C){function T(){et(C),fe("reset","reset",C.iframe,C.id)}L(C.id,"Size reset requested by "+(C.type==="init"?"host page":"iFrame")),H(C.id),be(T,C,"reset")}function et(C){function T(S){if(!C.id){L("undefined","messageData id not set");return}C.iframe.style[S]=C[S]+"px",L(C.id,"IFrame ("+I+") "+S+" set to "+C[S]+"px")}function R(S){!c&&C[S]==="0"&&(c=!0,L(I,"Hidden iFrame detected, creating visibility listener"),Fe())}function D(S){T(S),R(S)}var I=C.iframe.id;m[I]&&(m[I].sizeHeight&&D("height"),m[I].sizeWidth&&D("width"))}function be(C,T,R){R!==T.type&&g&&!window.jasmine?(L(T.id,"Requesting animation frame"),g(C)):C()}function fe(C,T,R,D,I){function S(){var ze=m[D]&&m[D].targetOrigin;L(D,"["+C+"] Sending msg to iframe["+D+"] ("+T+") targetOrigin: "+ze),R.contentWindow.postMessage(u+T,ze)}function ae(){O(D,"["+C+"] IFrame("+D+") not found")}function we(){R&&"contentWindow"in R&&R.contentWindow!==null?S():ae()}function Ye(){function ze(){m[D]&&!m[D].loaded&&!Qe&&(Qe=!0,O(D,"IFrame has not responded within "+m[D].warningTimeout/1e3+" seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ignored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning."))}I&&m[D]&&m[D].warningTimeout&&(m[D].msgTimeout=setTimeout(ze,m[D].warningTimeout))}var Qe=!1;D=D||R.id,m[D]&&(we(),Ye())}function Y(C){return C+":"+m[C].bodyMarginV1+":"+m[C].sizeWidth+":"+m[C].log+":"+m[C].interval+":"+m[C].enablePublicMethods+":"+m[C].autoResize+":"+m[C].bodyMargin+":"+m[C].heightCalculationMethod+":"+m[C].bodyBackground+":"+m[C].bodyPadding+":"+m[C].tolerance+":"+m[C].inPageLinks+":"+m[C].resizeFrom+":"+m[C].widthCalculationMethod+":"+m[C].mouseEvents}function pe(C){return typeof C=="number"}function ie(C,T){function R(){function V(ue){var he=m[G][ue];he!==1/0&&he!==0&&(C.style[ue]=pe(he)?he+"px":he,L(G,"Set "+ue+" = "+C.style[ue]))}function te(ue){if(m[G]["min"+ue]>m[G]["max"+ue])throw new Error("Value for min"+ue+" can not be greater than max"+ue)}te("Height"),te("Width"),V("maxHeight"),V("minHeight"),V("maxWidth"),V("minWidth")}function D(){var V=T&&T.id||k.id+o++;return document.getElementById(V)!==null&&(V+=o++),V}function I(V){if(typeof V!="string")throw new TypeError("Invaild id for iFrame. Expected String");return V===""&&(C.id=V=D(),s=(T||{}).log,L(V,"Added missing iframe ID: "+V+" ("+C.src+")")),V}function S(){switch(L(G,"IFrame scrolling "+(m[G]&&m[G].scrolling?"enabled":"disabled")+" for "+G),C.style.overflow=(m[G]&&m[G].scrolling)===!1?"hidden":"auto",m[G]&&m[G].scrolling){case"omit":break;case!0:C.scrolling="yes";break;case!1:C.scrolling="no";break;default:C.scrolling=m[G]?m[G].scrolling:"no"}}function ae(){(typeof(m[G]&&m[G].bodyMargin)=="number"||(m[G]&&m[G].bodyMargin)==="0")&&(m[G].bodyMarginV1=m[G].bodyMargin,m[G].bodyMargin=""+m[G].bodyMargin+"px")}function we(){var V=m[G]&&m[G].firstRun,te=m[G]&&m[G].heightCalculationMethod in y;!V&&te&&ve({iframe:C,height:0,width:0,type:"init"})}function Ye(){m[G]&&(m[G].iframe.iFrameResizer={close:me.bind(null,m[G].iframe),removeListeners:de.bind(null,m[G].iframe),resize:fe.bind(null,"Window resize","resize",m[G].iframe),moveToAnchor:function(V){fe("Move to anchor","moveToAnchor:"+V,m[G].iframe,G)},sendMessage:function(V){V=JSON.stringify(V),fe("Send Message","message:"+V,m[G].iframe,G)}})}function Qe(V){function te(){fe("iFrame.onload",V,C,n,!0),we()}function ue(Ge){if(!C.parentNode)return null;var qe=new Ge(function(st){st.forEach(function(Bt){Array.prototype.slice.call(Bt.removedNodes).forEach(function(Le){Le===C&&me(C)})})});return qe.observe(C.parentNode,{childList:!0}),qe}var he=w();he&&(i=ue(he)),v(C,"load",te),fe("init",V,C,n,!0)}function ze(V){if(typeof V!="object")throw new TypeError("Options is not an object")}function Ze(V){for(var te in k)Object.prototype.hasOwnProperty.call(k,te)&&(m[G][te]=Object.prototype.hasOwnProperty.call(V,te)?V[te]:k[te])}function pt(V){return V===""||V.match(/^(about:blank|javascript:|file:\/\/)/)!==null?"*":V}function bt(V){var te=V.split("Callback");if(te.length===2){var ue="on"+te[0].charAt(0).toUpperCase()+te[0].slice(1);this[ue]=this[V],delete this[V],O(G,"Deprecated: '"+V+"' has been renamed '"+ue+"'. The old method will be removed in the next major version.")}}function ft(V){V=V||{},m[G]=Object.create(null),m[G].iframe=C,m[G].firstRun=!0,m[G].remoteHost=C.src&&C.src.split("/").slice(0,3).join("/"),ze(V),Object.keys(V).forEach(bt,V),Ze(V),m[G]&&(m[G].targetOrigin=m[G].checkOrigin===!0?pt(m[G].remoteHost):"*")}function lt(){return G in m&&"iFrameResizer"in C}var G=I(C.id);lt()?O(G,"Ignored iFrame, already setup."):(ft(T),S(),R(),ae(),Qe(Y(G)),Ye())}function se(C,T){E===null&&(E=setTimeout(function(){E=null,C()},T))}var Ae={};function Te(C,T,R){Ae[R]||(Ae[R]=setTimeout(function(){Ae[R]=null,C()},T))}function Fe(){function C(){function I(S){function ae(Ye){return(m[S]&&m[S].iframe.style[Ye])==="0px"}function we(Ye){return Ye.offsetParent!==null}m[S]&&we(m[S].iframe)&&(ae("height")||ae("width"))&&fe("Visibility change","resize",m[S].iframe,S)}Object.keys(m).forEach(function(S){I(S)})}function T(I){L("window","Mutation observed: "+I[0].target+" "+I[0].type),se(C,16)}function R(){var I=document.querySelector("body");new D(T).observe(I,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0})}var D=w();D&&R()}function X(C){function T(){Ie("Window "+C,"resize")}L("window","Trigger event: "+C),se(T,16)}function Ee(){function C(){Ie("Tab Visible","resize")}document.visibilityState!=="hidden"&&(L("document","Trigger event: Visibility change"),se(C,16))}function Ie(C,T){function R(D){return m[D]&&m[D].resizeFrom==="parent"&&m[D].autoResize&&!m[D].firstRun}Object.keys(m).forEach(function(D){R(D)&&fe(C,T,m[D].iframe,D)})}function ge(){v(window,"message",B),v(window,"resize",function(){X("resize")}),v(document,"visibilitychange",Ee),v(document,"-webkit-visibilitychange",Ee)}function Re(){function C(D,I){function S(){if(I.tagName){if(I.tagName.toUpperCase()!=="IFRAME")throw new TypeError("Expected <IFRAME> tag, found <"+I.tagName+">")}else throw new TypeError("Object is not a valid DOM element")}I&&(S(),ie(I,D),R.push(I))}function T(D){D&&D.enablePublicMethods&&O("enablePublicMethods option has been removed, public methods are now always available in the iFrame")}var R;return P(),ge(),function(I,S){switch(R=[],T(I),typeof S){case"undefined":case"string":Array.prototype.forEach.call(document.querySelectorAll(S||"iframe"),C.bind(n,I));break;case"object":C(I,S);break;default:throw new TypeError("Unexpected data type ("+typeof S+")")}return R}}function Ue(C){C.fn?C.fn.iFrameResize||(C.fn.iFrameResize=function(R){function D(I,S){ie(S,R)}return this.filter("iframe").each(D).end()}):A("","Unable to bind to jQuery, it is not fully loaded.")}window.jQuery!==n&&Ue(window.jQuery),typeof define=="function"&&define.amd?define([],Re):typeof t=="object"&&typeof t.exports=="object"&&(t.exports=Re()),window.iFrameResize=window.iFrameResize||Re()})()})),Uy=zt.__toESM($y()),zy={checkOrigin:!1,minHeight:600,scrolling:!1};function Gy(e){const t=()=>e.iFrameResizer;return(0,Uy.default)(zy,e),{resize:()=>t()?.resize?.(),dispose:()=>t()?.removeListeners?.()}}function Wy(e){e.inject(Mi,Gy)}function Hy(e){const t=r.getMessageService(e),n=e.getInstance(r.LOCALE_SERVICE_ID);if(!n)return;let o="";const i=()=>{const d=n.snapshot(),u=d.id??"";if(!t.isInited()||u===o)return;const p=r.createI18n(d.catalog),f=y=>p.__(y),g=r.SANDBOX_TRANSLATIONS_MAP(f);o=u,t.send(r.EVENT_TYPES.SANDBOX_TRANSLATIONS,{name:u,data:g})},s=t.onInit(()=>{o="",i()}),c=n.state.watch(i);e.getInstance(h.DISPOSABLE_ID)?.addDispose(()=>{s.dispose(),c.dispose()})}function qy(e){const t=e?.content?.templateId;return t==null||t===""?void 0:String(t)}function Vy(e){e.getInstance(h.OPTIONS_SOURCE_ID)?.watch(t=>{const n=qy(t);n!==void 0&&Fg(e,n)})}var Wo={en_US:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/c00a8e02.js")).then(e=>e.en_US_exports),void 0,{}.url),ru_RU:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/8fb0fe48.js")),void 0,{}.url),uk_UA:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/9a70cc1e.js")),void 0,{}.url),es_ES:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/5bf994b4.js")),void 0,{}.url),pt_BR:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/a15ab67d.js")),void 0,{}.url),de_DE:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/ffb36e93.js")),void 0,{}.url),fr_FR:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/364dcebf.js")),void 0,{}.url),it_IT:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/dfddbd68.js")),void 0,{}.url),pl_PL:()=>(0,Ve.__vitePreload)(()=>Promise.resolve().then(()=>ye("./static/core/f3eda1c7.js")),void 0,{}.url)};async function Ky(e){const t=Wo[e];if(!t){const n=Wo.en_US;return n?(await n()).default:void 0}return(await t()).default}var v0=Object.keys(Wo),Yy=e=>e==="uk"?"uk_UA":e;function Qy(e){e.getInstance(r.LOCALE_SERVICE_ID)?.useAntdLoader(t=>Ky(Yy(t)))}function Xy(e){}function $a(e,t,n){let o=!1;const i=e.watch(s=>{o||!t(s)||(o=!0,n())});o&&i.dispose()}function Jy(e,t){const n=e.getInstance(h.CONFIG_SOURCE_ID);n&&$a(n,o=>!!o?.codeEnabled||!!o?.codeSideEnabled,()=>{tv(e,()=>{nv(e,()=>{ev(e,()=>{Ht(e).whenVisible(()=>{Xt(()=>{Zy(t).catch(()=>{})})})})})})})}async function Zy(e){await e()}function ev(e,t){const n=e.getInstance(Ns);if(!n){Xt(t);return}const o=()=>{if(n.pipeline.filledGeneration()!==void 0){t();return}Xt(o)};Xt(o)}function tv(e,t){const n=e.getInstance(r.EMAIL_DOCUMENTS_ID);if(!n)return;if(n.current()){t();return}let o=!1;const i=n.subscribe(()=>{o||!n.current()||(o=!0,t())});o&&i()}function nv(e,t){const n=e.getInstance(h.OPTIONS_SOURCE_ID);n&&$a(n,o=>!!o?.element,t)}function rv(e){Jy(e,tu)}var Ua=h.createIdentifier$1("NotificationService");function za(e,t="success"){return typeof e=="string"&&(e={message:e}),r.filterUndefined({type:e.type||t,data:e.data,innerException:e.innerException,title:e.message,description:e.description,actions:e.btn,onClose:e.onClose,duration:e.duration,icon:e.icon,placement:e.placement,style:e.style,closeIcon:e.closeIcon,props:e.props,role:e.role})}var ov="bottomRight";function Ho(e,t){return typeof e=="string"||typeof e=="object"?za(e,t):e}var iv=class extends h.Disposable{send;onNotify;onError;onSuccess;constructor(e,t,n){super(),this.send=n,this.onNotify=Ct(t,c=>c,c=>Ho(c)),this.onError=Ct(h.filter(t,c=>c.type==="error"),c=>c,c=>Ho(c,"error")),this.onSuccess=Ct(h.filter(t,c=>c.type==="success"),c=>c,c=>Ho(c));const o=this.addDisposable(new kt(this.onNotify)),i=this.addDisposable(new kt(this.onError)),s=this.addDisposable(new kt(this.onSuccess));this.addDisposable(e.watch(({handleNotify:c,handleError:d,handleSuccess:u})=>{o.setListener(c),i.setListener(d),s.setListener(u)}))}notify(e){this.send({placement:ov,...za(e)})}};function sv(e){e.injectFactory(Ua,()=>{const t=new iv(e.getInstance(h.OPTIONS_SOURCE_ID),h.getEvent(e,h.events.ON_NOTIFICATION),n=>{r.executeCommand(e,r.NOTIFY_COMMAND_ID,n)});return e.getInstance(h.DISPOSABLE_ID)?.addDisposable(t),t},!0)}function av(e){const t=r.getEmailDocuments(e),n=i=>{e.getInstance(h.STORE_ID)?.dispatch(r.taxonomiesApi.util.invalidateTags([{type:"folder",id:i}]))},o=t.onSaved(i=>{i.created&&n("folder")});e.getInstance(h.DISPOSABLE_ID)?.addDispose(o)}function b0(e){return e}var lv=[{name:"rest.legacySections",provides:[h.REST_CLIENT_ID],setup:h.provideLegacyRestSections},{name:"canvas.resizer",provides:[Mi],setup:Wy},{name:"canvas.sandboxLocale",awaits:{services:[r.LOCALE_SERVICE_ID]},setup:Hy},{name:"locale.brandCatalog",awaits:{services:[r.LOCALE_SERVICE_ID]},setup:Xy},{name:"email.restPorts",provides:[r.REST_EMAIL_PORTS_ID],setup:Ny},{name:"block.historyPort",setup:By},{name:"email.templatePrefetch",setup:Vy},{name:"locale.antd",awaits:{services:[r.LOCALE_SERVICE_ID]},setup:Qy},{name:"save.listsFollow",setup:av},{name:"monaco.prewarm",awaits:{services:[h.CONFIG_SOURCE_ID]},setup:rv},{name:"notifications",provides:[Ua],setup:sv},{name:"email.operations",setup:vy}],cv=h.defineMixin(e=>{for(const t of Ty(lv))t.setup(e);return{instance:by(e)}}),dv=h.combineMixins([cv,P_,iy,dy,Ey,Sy,jg,sy,$s,Us]);async function uv(e){const t=new Map;typeof e=="object"&&(e=e.code);const{amp2html:n,html2amp:o}=await(0,Ve.__vitePreload)(async()=>{const{amp2html:c,html2amp:d}=await Promise.resolve().then(()=>ye("./static/core/30f16e98.js"));return{amp2html:c,html2amp:d}},void 0,{}.url),i=await yt.changeHtml(e,async c=>{await yt.replaceImagesInDocument(c.document,d=>r.mapper.getEscapedText(d)!==d?d:r.toAbsoluteUrl(d),t);for(const d of c.document.querySelectorAll(".em-amp-show-disabled"))d.remove();c.handleRender(async({contentDocument:d,managedNodeController:u})=>{await o(d,{mappedTags:{script:"___script"},commit:()=>u.commit()})})},[800]),s=await yt.changeHtml(e,async c=>{await yt.replaceImagesInDocument(c.document,d=>r.mapper.getEscapedText(d)!==d?d:r.toAbsoluteUrl(d),t);for(const d of c.document.querySelectorAll(".em-amp-show-only"))d.remove();await n(c.document,{mappedTags:{script:"___script"}})},[800]);return{code:e,html:s,ampHtml:i}}async function pv(){const{installDiagnostics:e}=await(0,Ve.__vitePreload)(async()=>{const{installDiagnostics:t}=await Promise.resolve().then(()=>ye("./static/core/199dc589.js"));return{installDiagnostics:t}},void 0,{}.url);return e()}async function mv(e,t){const{initDevTools:n}=await(0,Ve.__vitePreload)(async()=>{const{initDevTools:o}=await Promise.resolve().then(()=>ye("./static/core/52fbc985.js"));return{initDevTools:o}},void 0,{}.url);n(e,t)}var fv="1.1.85-dev.4";nn.asyncMixins=dv,nn.initDevTools=mv,nn.installDiagnostics=pv,nn.parseAMP=uv,nn.version=fv});