1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DashboardView-DFKNlqEN.js","assets/@mui/system-B6wAwYdQ.js","assets/app-design-system-DtaKcdW2.js","assets/@mui/material-BYB1fIha.js","assets/libphonenumber-js-FniRj3IU.js","assets/aws-amplify-6dlz1eh8.js","assets/app-design-system--HTi4z_T.css","assets/app-foundation-kKDrgwPr.js","assets/@mui/x-date-pickers-pro-BtcfQAzC.js","assets/apexcharts-CMCMsJKb.js","assets/@mui/x-data-grid-pro-CSWJl3TV.js","assets/@react-awesome-query-builder/mui-DqHwnbb5.js","assets/echarts-BxdhZ3Bo.js","assets/react-leaflet-Bjtm3UlO.js","assets/xlsx-DFH0qU2H.js","assets/@tshepomgaga/aws-sfn-graph-DB1I8jVl.js"])))=>i.map(i=>d[i]); 2import{q as m,g as dt,t as a,_ as Ln,ae as Ot,C as mm,ap as gi,r as SD,aq as Gz,R as Ne,af as bs,ar as xn,m as sh,P as gm,aj as A,ad as Yz,x as Wl,b as Kz,as as Qz,at as Jz,d as gj,ao as Xz}from"./@mui/system-B6wAwYdQ.js";import{ao as jD,q as be,f as T,aA as yi,aB as ml,aC as Zz,m as He,h as I,a2 as Se,I as Ie,a1 as dr,s as rt,v as De,y as Bn,S as $,a as re,aq as tt,C as Ze,D as yt,b as vt,c as Ct,aD as Yt,J as vn,aE as lo,r as fe,aF as Fv,a3 as kD,a4 as Kt,g as Re,ad as $v,i as Ve,aG as Ue,F as Qe,a6 as _n,A as gl,ap as wt,x as Zn,z as St,aH as ED,a5 as as,aw as Nh,ar as et,w as Dn,ae as ut,ag as _D,aj as eB,ax as tB,aI as nB,aJ as TD,P as Br,a7 as rB,ak as sn,E as Ki,aK as Ya,H as bn,G as $e,aL as xl,aM as zv,ay as sB,d as un,aN as ys,aO as Mt,am as iB,o as Bv,aP as Mb,aQ as Ka,aR as Qa,aS as Ja,az as ID,p as xm,aT as DD,k as Uv,aU as xj,T as Vv,e as AD,aV as Wv,aW as Xa,_ as aB,$ as oB,a0 as lB,aX as MD,at as bj,M as cB,L as dB,n as uB,av as td}from"./@mui/material-BYB1fIha.js";import{q as pB,u as hB,l as We,e as RD,v as ND,M as bm,w as es,x as ct,y as Hv,A as OD,B as fB,C as mB,N as gB,D as xB,L as Nt,H as bB,E as bl,F as iu,G as vs,I as au,r as Pt,p as Lt,J as ym,K as yB,O as Dt,P as vB,Q as yl,W as CB,R as PD,T as wB,V as LD,X as SB,Y as FD,Z as $D,$ as jB,a0 as kB,a1 as EB,a2 as co,a3 as uo,a4 as _B,z as U,a5 as vm,a6 as zD,a7 as qv,a8 as Gv,a9 as ca,aa as Md,ab as BD,ac as Jt,ad as TB,ae as mt,af as fs,ag as Tn,U as Rd,ah as UD,ai as IB,aj as VD,ak as DB,al as Kn,am as WD,n as AB,an as vl,ao as MB,ap as Cl,aq as RB,ar as wl,as as Yv,at as yj,au as vj,av as NB,aw as ms,ax as OB,ay as Cj,az as HD,aA as PB,aB as qD,aC as LB,aD as GD,aE as FB,aF as Kv,aG as $B,aH as zB,aI as BB,aJ as UB,aK as VB,aL as WB,aM as HB,aN as qB,aO as GB,aP as YB,aQ as KB,aR as QB,aS as JB,aT as XB,aU as ZB,aV as eU,aW as tU,aX as nU,aY as wj,aZ as rU,a_ as sU,a$ as iU,b0 as Fs,b1 as Sl,b2 as nl,b3 as Qv,b4 as Si,b5 as YD,b6 as ou,b7 as Xr,h as KD,b8 as lu,b9 as er,ba as aU,bb as oU,bc as lU,bd as Rb,be as QD,bf as Sj,bg as jj,bh as pd,bi as kj,bj as JD,bk as cU,bl as cu,bm as XD,bn as Za,bo as po,bp as ZD,bq as eA,br as dU,bs as Cm,bt as uU,bu as tA,bv as pU,bw as hU,bx as nA,by as fU,bz as mU,bA as Jv,bB as gU,bC as Oh,bD as xU,bE as Ph,bF as bU,bG as rA,bH as du,bI as yU,bJ as vU,bK as Xv,bL as sA,bM as xt,bN as iA,bO as Zv,bP as eC,bQ as tC,bR as aA,bS as CU,bT as uu,bU as wU,bV as oA,bW as SU,bX as jU,bY as kU,bZ as EU,b_ as lA,b$ as _U,c0 as TU,c1 as cA,c2 as IU,c3 as DU,c4 as AU,c5 as MU,c6 as dA,c7 as uA,c8 as nC,c9 as RU,ca as rC,cb as pA,cc as Lh,k as NU,cd as OU,ce as PU,cf as LU,cg as FU,ch as $U,ci as zU,cj as hA,ck as fA,cl as BU,cm as UU,_ as Bs,a as Fh,cn as VU,co as WU,cp as rp,cq as HU,cr as sC,cs as iC,ct as qU,cu as GU,cv as YU,cw as KU,cx as QU,cy as ns,cz as Nb,cA as JU,cB as XU}from"./app-design-system-DtaKcdW2.js";import{z as ZU,h as e5,B as t5,D as n5,E as r5,F as s5,G as i5,I as a5,J as o5,K as l5,L as mA,_ as c5,M as jl,P as kl,Q as Ej,S as _j,T as d5,V as u5}from"./aws-amplify-6dlz1eh8.js";import{w as p5,i as gA,a as aC,p as pu,b as oC,c as h5,d as f5,e as Ob,f as xA,g as Oi,u as bA,h as Tj,j as m5,k as g5,l as x5,m as b5,n as y5,o as v5,q as C5,r as w5,s as S5,t as j5,v as k5,x as pe,y as yA,z as E5,A as _5,B as lC,C as T5,D as cC,P as I5,E as D5,F as A5,G as M5,H as Nd,I as R5,J as N5,K as vA,L as CA,M as O5,N as P5,O as L5,Q as F5,R as $5,S as Qs,T as wm,U as dC,V as wA,W as SA,X as jA,Y as uC,Z as z5,_ as B5,$ as U5,a0 as kA,a1 as hu,a2 as Ig,a3 as V5,a4 as W5,a5 as H5,a6 as q5,a7 as G5,a8 as fu,a9 as EA,aa as Y5,ab as K5,ac as pC,ad as _A,ae as Q5,af as Sm,ag as J5,ah as X5,ai as Z5,aj as eV,ak as tV,al as nV,am as rV,an as sV,ao as iV,ap as TA,aq as aV,ar as oV,as as lV,at as cV,au as dV,av as IA,aw as DA,ax as AA,ay as hC,az as MA,aA as uV,aB as pV,aC as hV,aD as fV,aE as RA,aF as NA,aG as OA,aH as mV,aI as gV,aJ as xV,aK as bV,aL as yV,aM as vV,aN as CV,aO as wV,aP as SV,aQ as jV,aR as fC,aS as mu,aT as kV,aU as EV,aV as _V,aW as TV,aX as PA,aY as IV,aZ as DV,a_ as AV,a$ as mC,b0 as LA,b1 as MV,b2 as RV,b3 as NV,b4 as OV,b5 as PV,b6 as LV,b7 as FV,b8 as $V,b9 as gu,ba as zV,bb as FA,bc as BV,bd as UV,be as $A,bf as VV,bg as gC,bh as WV,bi as HV,bj as qV,bk as GV,bl as YV,bm as KV,bn as QV,bo as JV,bp as zA,bq as XV,br as ZV,bs as Ij,bt as e3,bu as Pb,bv as BA,bw as t3,bx as
2n3,by as r3,bz as s3,bA as UA,bB as i3,bC as a3,bD as o3,bE as VA,bF as l3,bG as c3,bH as d3,bI as u3,bJ as p3,bK as wa,bL as WA,bM as h3,bN as HA,bO as qA,bP as f3,bQ as GA,bR as m3,bS as g3,bT as xC,bU as x3,bV as YA,bW as KA,bX as b3,bY as y3,bZ as bC,b_ as QA,b$ as v3,c0 as C3,c1 as w3,c2 as JA,c3 as S3,c4 as j3,c5 as XA,c6 as k3,c7 as E3,c8 as _3,c9 as T3,ca as I3,cb as D3,cc as A3,cd as M3,ce as R3,cf as N3,cg as O3,ch as P3,ci as L3,cj as jm,ck as F3,cl as $3,cm as z3,cn as B3,co as U3,cp as V3,cq as W3,cr as ZA,cs as eM,ct as H3,cu as q3,cv as G3,cw as Y3,cx as K3,cy as Q3,cz as J3,cA as X3,cB as tM,cC as Z3,cD as nM,cE as eW,cF as tW,cG as nW,cH as rW,cI as sW,cJ as iW,cK as $a,cL as aW,cM as Qi,cN as oW,cO as yC,cP as lW,cQ as cW,cR as dW,cS as uW,cT as pW,cU as hW,cV as fW,cW as mW,cX as gW}from"./app-foundation-kKDrgwPr.js";import{b as xW,c as bW,L as xu,d as yW,S as vW,D as eo}from"./@mui/x-date-pickers-pro-BtcfQAzC.js";import{r as CW}from"./apexcharts-CMCMsJKb.js";import{D as Mn,u as zn,G as km,a as vC,g as xe,b as rl,c as rM,d as Dg,e as Em,f as _m,h as wW,i as Dj,j as CC,k as SW,l as sM}from"./@mui/x-data-grid-pro-CSWJl3TV.js";import{A as wC,D as iM,_ as aM,a as jW,M as qr,Q as kW,B as EW,U as Sa}from"./@react-awesome-query-builder/mui-DqHwnbb5.js";import{e as _W,A as TW,C as IW,a as DW,b as AW,S as MW,M as RW,P as NW,c as OW,d as PW,f as LW,g as FW,h as $W,i as zW,j as BW,k as UW,l as VW,m as WW,n as HW,o as qW,p as GW,q as YW,r as KW,s as QW,t as JW,u as XW,v as ZW,w as eH,x as tH,y as nH,z as rH,B as sH,D as Aj,E as iH,F as aH,G as oH,H as lH,I as cH,J as dH,K as uH,L as pH,N as hH,O as fH,Q as mH,R as gH,T as xH,U as bH,V as yH,W as vH,X as CH,Y as wH,Z as Tm,_ as SH,$ as jH,a0 as kH,a1 as EH,a2 as _H,a3 as TH,a4 as oM,a5 as SC,a6 as jC,a7 as IH,a8 as lM,a9 as DH}from"./echarts-BxdhZ3Bo.js";import{M as AH,T as MH,C as RH,a as NH,u as OH}from"./react-leaflet-Bjtm3UlO.js";import{r as PH,u as Mj}from"./xlsx-DFH0qU2H.js";import{p as kC,A as cM}from"./libphonenumber-js-FniRj3IU.js";import{s as LH}from"./@tshepomgaga/aws-sfn-graph-DB1I8jVl.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();const Hl=(e="")=>`https://${e}assets.marketingevolution.com/images/logos/MEVO_logo.png`,ql=(e="")=>`https://${e}assets.marketingevolution.com/images/logos/MEVO_logo_white.png`,Gl="https://assets.marketingevolution.com/images/favicon/mevo/favicon.ico",Yl="Mevo",Rj="https://assets.marketingevolution.com/images/favicon/plusco/favicon.ico",Lb="https://assets.marketingevolution.com/images/logos/pluscompany/plus_aios_logo.png",$h="https://assets.marketingevolution.com/images/logos/pluscompany/plus_aios_logo_white.png",Fb="AIOS",FH=e=>{switch(e){case"local.marketingevolution.com":case"dev-app.marketingevolution.com":return{companyLogo:Hl("dev-"),companyLogoDark:ql("dev-"),companyName:Yl,faviconUrl:Gl,isPluscoDomain:!1};case"dev-app2.marketingevolution.com":return{companyLogo:Lb,companyLogoDark:$h,companyName:Fb,faviconUrl:Rj,isPluscoDomain:!0};case"test-app.marketingevolution.com":return{companyLogo:Hl("testing-"),companyLogoDark:ql("testing-"),companyName:Yl,faviconUrl:Gl,isPluscoDomain:!1};case"stage-app.marketingevolution.com":return{companyLogo:Hl("staging-"),companyLogoDark:ql("staging-"),companyName:Yl,faviconUrl:Gl,isPluscoDomain:!1};case"app-au.marketingevolution.com":return{companyLogo:Hl(),companyLogoDark:ql(),companyName:Yl,faviconUrl:Gl,isPluscoDomain:!1};case"dev-aios.pluscompany.com":case"test-aios.pluscompany.com":case"aios.pluscompany.com":return{companyLogo:Lb,companyLogoDark:$h,companyName:Fb,faviconUrl:Rj,isPluscoDomain:!0};default:return{companyLogo:Hl(),companyLogoDark:ql(),companyName:Yl,faviconUrl:Gl,isPluscoDomain:!1}}},hs=pB({appId:"mevo",constantsMap:hB("mevo"),getProviderInfo:FH}),Nj=async e=>o5({...e,options:{...e.options,clientMetadata:{...e.options?.clientMetadata,authSource:"password"}}}),dM=async e=>{await r5(e)},Oj=async e=>s5(e),sl=async e=>e5(e),EC=async()=>ZU(),Ag=async e=>a5(e),$H=async e=>{await i5(e)},zH=e=>typeof e=="string"?e:void 0,uM=async e=>{if(e.tokens?.idToken){const{payload:s}=e.tokens.idToken;if(zH(s.is_federated)==="1")return{hasVerifiedContact:!0,emailVerified:!0,phoneVerified:!1}}const t=await n5(),n=t.email_verified==="true",r=t.phone_number_verified==="true";return{hasVerifiedContact:n||r,emailVerified:n,phoneVerified:r}},BH=async e=>{await t5(e)},$b={NotAuthorizedException:"NotAuthorizedException",UserNotFoundException:"UserNotFoundException",UserNotConfirmedException:"UserNotConfirmedException",PasswordResetRequiredException:"PasswordResetRequiredException",InvalidPasswordException:"InvalidPasswordException",CodeMismatchException:"CodeMismatchException",ExpiredCodeException:"ExpiredCodeException",LimitExceededException:"LimitExceededException",TooManyRequestsException:"TooManyRequestsException"},Kl={NotAuthorizedException:"Incorrect username or password",UserNotFoundException:"User not found",UserNotConfirmedException:"User is not confirmed",PasswordResetRequiredException:"Password reset required",PasswordExpired:"Your password has expired and must be reset",InvalidPasswordException:"Invalid password",CodeMismatchException:"Invalid verification code",ExpiredCodeException:"Verification code has expired",LimitExceededException:"Too many attempts. Please try again later",TooManyRequestsException:"Too many requests. Please try again later",NetworkError:"Network error. Please check your connection",UnknownError:"An unexpected error occurred"},UH="PASSWORD_EXPIRED",VH=e=>e instanceof l5,WH=e=>{if(e instanceof Error){const t=e.message.toLowerCase();return t.includes("network")||t.includes("fetch")||t.includes("connection")||t.includes("timeout")||e.name==="NetworkError"||e.name==="TypeError"}return!1},HH=e=>{const t=e.name;return $b[t]??"UnknownError"},qH=e=>{if(e instanceof Error&&e.message.includes(UH))return{code:"PasswordExpired",message:Kl.PasswordExpired,originalError:e};if(VH(e)){const t=HH(e);return{code:t,message:Kl[t],originalError:e}}if(e instanceof Error&&e.name in $b){const t=$b[e.name]??"UnknownError";return{code:t,message:Kl[t],originalError:e}}return WH(e)?{code:"NetworkError",message:Kl.NetworkError,originalError:e}:{code:"UnknownError",message:Kl.UnknownError,originalError:e}},pM=(e,t,n=!1)=>
2{if(e.length===0||t.length===0)return!1;const r=new Set(t);return n?e.every(s=>r.has(s)):e.some(s=>r.has(s))},ih="CognitoIdentityServiceProvider",GH=3e4,YH=e=>{const t=e.split(".")[1];if(!t)throw new Error("Invalid JWT format");let n=t.replace(/-/g,"+").replace(/_/g,"/");const r=n.length%4;r&&(n+="=".repeat(4-r));const s=decodeURIComponent(atob(n).split("").map(o=>`%${o.charCodeAt(0).toString(16).padStart(2,"0")}`).join("")),i=JSON.parse(s);if(typeof i!="object"||i===null)throw new Error("Invalid JWT payload");return Object.entries(i).reduce((o,[l,c])=>(o[l]=c,o),{})},KH=(e,t,n)=>{const r=`${ih}.${e}`,s=`${r}.${t}`;localStorage.setItem(`${r}.LastAuthUser`,t),localStorage.setItem(`${s}.accessToken`,n.access_token),localStorage.setItem(`${s}.idToken`,n.id_token),n.refresh_token?localStorage.setItem(`${s}.refreshToken`,n.refresh_token):localStorage.removeItem(`${s}.refreshToken`),localStorage.setItem(`${s}.clockDrift`,"0"),localStorage.setItem(`${r}.oauthSignIn`,"true,false"),localStorage.setItem(`${s}.oauthMetadata`,JSON.stringify({oauthSignIn:!0}))},QH=async e=>{const{code:t,clientId:n,domain:r,redirectUri:s}=e,i=`https://${r}/oauth2/token`,o=new URLSearchParams({grant_type:"authorization_code",code:t,client_id:n,redirect_uri:s});try{const l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:AbortSignal.timeout(GH)});if(!l.ok)return!1;const c=await l.json(),d=f=>typeof f!="object"||f===null||!Object.prototype.hasOwnProperty.call(f,"error")?!1:typeof Object.getOwnPropertyDescriptor(f,"error")?.value=="string",u=f=>{if(typeof f!="object"||f===null||!Object.prototype.hasOwnProperty.call(f,"access_token")||!Object.prototype.hasOwnProperty.call(f,"id_token"))return!1;const g=Object.getOwnPropertyDescriptor(f,"access_token")?.value,x=Object.getOwnPropertyDescriptor(f,"id_token")?.value;return typeof g=="string"&&typeof x=="string"};if(d(c)||!u(c))return We(new Error(`exchangeCodeForTokens: unexpected token response - ${JSON.stringify(c)}`)),!1;const p=YH(c.access_token),h=typeof p.username=="string"?p.username:typeof p.sub=="string"?p.sub:`user_${Date.now()}`;return KH(n,h,c),localStorage.removeItem(`${ih}.${n}.inflightOAuth`),localStorage.removeItem(`${ih}.${n}.oauthState`),localStorage.removeItem(`${ih}.${n}.oauthPKCE`),!0}catch(l){return We(l),!1}},JH=e=>typeof e=="object"&&e!==null&&"tokens"in e,XH=async e=>{try{let t;return e?JH(e)?t=e:t=await sl():t=await sl(),(await uM(t)).hasVerifiedContact}catch(t){return We(t),!1}},ZH=async e=>{try{return await Nj(e)}catch(t){if(RD(t).name==="UserAlreadyAuthenticatedException")return await dM(),Nj(e);throw t}},e4=e=>{const{onAuthComplete:t,setUserState:n,parseUser:r,isMounted:s}=e,i=async()=>{const f=await EC(),g=await sl();if(!(await uM(g)).hasVerifiedContact)throw new Error("Your account does not have a verified contact method. Please contact your administrator.");if(s()){const b=r({username:f.username,userId:f.userId,signInDetails:f.signInDetails,session:g});n({fullAuthObj:{user:f,session:g},validatedUser:b,verified:!0}),t()}},o=async f=>{const{isSignedIn:g,nextStep:x}=f;switch(x.signInStep){case"CONFIRM_SIGN_IN_WITH_SMS_CODE":case"CONFIRM_SIGN_IN_WITH_TOTP_CODE":case"CONFIRM_SIGN_UP":return"mfaNeeded";case"CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED":return"newPassword";case"CONTINUE_SIGN_IN_WITH_MFA_SETUP_SELECTION":case"CONTINUE_SIGN_IN_WITH_TOTP_SETUP":return"registerPhone";case"RESET_PASSWORD":return"forgotPassword"}return(g||x.signInStep==="DONE")&&await i(),null},l=async(f,g)=>{try{const x=await ZH({username:f,password:g});if(s()&&!x.isSignedIn&&n({fullAuthObj:null,validatedUser:null}),x.nextStep?.signInStep==="RESET_PASSWORD"){try{await Ag({username:f})}catch(b){We(b)}return"forgotPassword"}return await o(x)}catch(x){n({verified:!1});const b=qH(x);if(We(x),b.code==="NotAuthorizedException"||b.code==="UserNotFoundException")return{type:"error",message:"Incorrect username or password"};if(b.code==="PasswordExpired"||b.code==="PasswordResetRequiredException"){try{await Ag({username:f})}catch(y){We(y)}return"forgotPassword"}return b.code==="UserNotConfirmedException"?"mfaNeeded":"error"}};return{onSignIn:l,onConfirmMfa:async f=>{try{const g=await Oj({challengeResponse:f});return(g.isSignedIn||g.nextStep.signInStep==="DONE")&&await i(),g.nextStep.signInStep==="CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED"?"newPassword":null}catch(g){return n({validatedUser:null}),We(g),"error"}},onForgotPasswordRequest:async f=>{try{await Ag({username:f})}catch(g){We(g)}return"success"},onForgotPasswordSubmit:async(f,g,x)=>{try{return await $H({username:g,confirmationCode:f,newPassword:x}),await l(g,x)}catch(b){const y=RD(b);return We(y),{type:"error",message:y.message}}},onNewPasswordSubmit:async(f,g)=>{try{const x=await Oj({challengeResponse:f,options:{userAttributes:{phone_number:g}}});return await o(x)}catch(x){return We(x),"error"}},onRegisterPhone:async f=>"success",getUserFlowPath:o}};var t4=Object.create,hM=Object.defineProperty,n4=Object.getOwnPropertyDescriptor,r4=Object.getOwnPropertyNames,s4=Object.getPrototypeOf,i4=Object.prototype.hasOwnProperty,a4=(e,t)=>
2()=>(t||e((t={exports:{}}).exports,t),t.exports),o4=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of r4(t))!i4.call(e,s)&&s!==n&&hM(e,s,{get:()=>t[s],enumerable:!(r=n4(t,s))||r.enumerable});return e},l4=(e,t,n)=>(n=e!=null?t4(s4(e)):{},o4(!e||!e.__esModule?hM(n,"default",{value:e,enumerable:!0}):n,e)),c4=a4((e,t)=>{(function(n,r){typeof e=="object"&&typeof t<"u"?r(e):typeof define=="function"&&define.amd?define(["exports"],r):(n=typeof globalThis<"u"?globalThis:n||self,r(n.fastUniqueNumbers={}))})(e,function(n){var r=function(f){return function(g){var x=f(g);return g.add(x),x}},s=function(f){return function(g,x){return f.set(g,x),x}},i=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,l=o*2,c=function(f,g){return function(x){var b=g.get(x),y=b===void 0?x.size:b<l?b+1:0;if(!x.has(y))return f(x,y);if(x.size<o){for(;x.has(y);)y=Math.floor(Math.random()*l);return f(x,y)}if(x.size>i)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;x.has(y);)y=Math.floor(Math.random()*i);return f(x,y)}},d=new WeakMap,u=s(d),p=c(u,d),h=r(p);n.addUniqueNumber=h,n.generateUniqueNumber=p})});l4(c4());var fi=(typeof window>"u"?"undefined":typeof window)=="object",us={setTimeout:fi?setTimeout.bind(window):setTimeout,clearTimeout:fi?clearTimeout.bind(window):clearTimeout,setInterval:fi?setInterval.bind(window):setInterval,clearInterval:fi?clearInterval.bind(window):clearInterval};function d4(e){us.setTimeout=e.setTimeout,us.clearTimeout=e.clearTimeout,us.setInterval=e.setInterval,us.clearInterval=e.clearInterval}var Eo={},u4=class{name;closed=!1;mc=new MessageChannel;constructor(t){this.name=t,Eo[t]=Eo[t]||[],Eo[t].push(this),this.mc.port1.start(),this.mc.port2.start(),this.onStorage=this.onStorage.bind(this),window.addEventListener("storage",this.onStorage)}onStorage(t){if(t.storageArea!==window.localStorage||t.key.substring(0,this.name.length)!==this.name||t.newValue===null)return;let n=JSON.parse(t.newValue);this.mc.port2.postMessage(n)}postMessage(t){if(this.closed)throw new Error("InvalidStateError");let n=JSON.stringify(t),r=`${this.name}:${String(Date.now())}${String(Math.random())}`;window.localStorage.setItem(r,n),us.setTimeout(()=>{window.localStorage.removeItem(r)},500),Eo[this.name].forEach(s=>{s!==this&&s.mc.port2.postMessage(JSON.parse(n))})}close(){if(this.closed)return;this.closed=!0,this.mc.port1.close(),this.mc.port2.close(),window.removeEventListener("storage",this.onStorage);let t=Eo[this.name].indexOf(this);Eo[this.name].splice(t,1)}get onmessage(){return this.mc.port1.onmessage}set onmessage(t){this.mc.port1.onmessage=t}get onmessageerror(){return this.mc.port1.onmessageerror}set onmessageerror(t){this.mc.port1.onmessageerror=t}addEventListener(t,n){return this.mc.port1.addEventListener(t,n)}removeEventListener(t,n){return this.mc.port1.removeEventListener(t,n)}dispatchEvent(t){return this.mc.port1.dispatchEvent(t)}},p4=typeof window>"u"?void 0:typeof window.BroadcastChannel=="function"?window.BroadcastChannel:u4;function h4(e=0){return new Promise(t=>us.setTimeout(t,e))}function fM(){return Math.random().toString(36).substring(2)}var f4=class{options;channel;token=fM();isLeader=!1;isDead=!1;isApplying=!1;reApply=!1;intervals=[];listeners=[];deferred;constructor(t,n){this.channel=t,this.options=n,this.apply=this.apply.bind(this),this.awaitLeadership=this.awaitLeadership.bind(this),this.sendAction=this.sendAction.bind(this)}async apply(){if(this.isLeader||this.isDead)return!1;if(this.isApplying)return this.reApply=!0,!1;this.isApplying=!0;let t=!1,n=r=>{let{token:s,action:i}=r.data;s!==this.token&&(i===0&&s>this.token&&(t=!0),i===1&&(t=!0))};this.channel.addEventListener("message",n);try{return this.sendAction(0),await h4(this.options.responseTime),this.channel.removeEventListener("message",n),this.isApplying=!1,t?this.reApply?this.apply():!1:(this.assumeLead(),!0)}catch{return!1}}awaitLeadership(){if(this.isLeader)return Promise.resolve();let t=!1,n=null;return new Promise(r=>{let s=()=>{if(t)return;t=!0;try{us.clearInterval(n)}catch{}let o=this.intervals.indexOf(n);o>=0&&this.intervals.splice(o,1),this.channel.removeEventListener("message",i),r()};n=us.setInterval(()=>{this.apply().then(()=>{this.isLeader&&s()})},this.options.fallbackInterval),this.intervals.push(n);let i=o=>{let{action:l}=o.data;l===2&&this.apply().then(()=>{this.isLeader&&s()})};this.channel.addEventListener("message",i)})}sendAction(t){this.channel.postMessage({action:t,token:this.token})}assumeLead(){this.isLeader=!0;let t=n=>{let{action:r}=n.data;r===0&&this.sendAction(1)};return this.channel.addEventListener("message",t),this.listeners.push(t),this.sendAction(1)}waitForLeadership(){return this.deferred?this.deferred:(this.deferred=this.awaitLeadership(),this.deferred)}close(){if(!this.isDead){this.isDead=!0,this.isLeader=!1,this.sendAction(2);
2try{this.listeners.forEach(t=>this.channel.removeEventListener("message",t)),this.intervals.forEach(t=>us.clearInterval(t))}catch{}}}},m4=class{channel;options;elector;token=fM();registry=new Map;allIdle=!1;isLastActive=!1;constructor(t){let{channelName:n}=t;if(this.options=t,this.channel=new p4(n),this.registry.set(this.token,1),t.leaderElection){let r={fallbackInterval:2e3,responseTime:100};this.elector=new f4(this.channel,r),this.elector.waitForLeadership()}this.channel.addEventListener("message",r=>{let{action:s,token:i,data:o}=r.data;switch(s){case 3:this.registry.set(i,2);break;case 4:this.registry.delete(i);break;case 5:this.idle(i);break;case 6:this.active(i);break;case 7:this.prompt(i);break;case 8:this.start(i);break;case 9:this.reset(i);break;case 10:this.activate(i);break;case 11:this.pause(i);break;case 12:this.resume(i);break;case 13:this.options.onMessage(o);break}}),this.send(3)}get isLeader(){if(!this.elector)throw new Error('â Leader election is not enabled. To Enable it set the "leaderElection" property to true.');return this.elector.isLeader}prompt(t=this.token){this.registry.set(t,0);let n=[...this.registry.values()].every(r=>r===0);t===this.token&&this.send(7),n&&this.options.onPrompt()}idle(t=this.token){this.registry.set(t,2);let n=[...this.registry.values()].every(r=>r===2);t===this.token&&this.send(5),!this.allIdle&&n&&(this.allIdle=!0,this.options.onIdle())}active(t=this.token){this.allIdle=!1,this.registry.set(t,1);let n=[...this.registry.values()].some(r=>r===1);t===this.token&&this.send(6),n&&this.options.onActive(),this.isLastActive=t===this.token}start(t=this.token){this.allIdle=!1,this.registry.set(t,1),t===this.token?this.send(8):this.options.start(!0),this.isLastActive=t===this.token}reset(t=this.token){this.allIdle=!1,this.registry.set(t,1),t===this.token?this.send(9):this.options.reset(!0),this.isLastActive=t===this.token}activate(t=this.token){this.allIdle=!1,this.registry.set(t,1),t===this.token?this.send(10):this.options.activate(!0),this.isLastActive=t===this.token}pause(t=this.token){t===this.token?this.send(11):this.options.pause(!0)}resume(t=this.token){t===this.token?this.send(12):this.options.resume(!0)}message(t){try{this.channel.postMessage({action:13,token:this.token,data:t})}catch{}}send(t){try{this.channel.postMessage({action:t,token:this.token})}catch{}}close(){this.options.leaderElection&&this.elector.close(),this.send(4),this.channel.close()}},g4=fi?document:null,x4=["mousemove","keydown","wheel","DOMMouseScroll","mousewheel","mousedown","touchstart","touchmove","MSPointerDown","MSPointerMove","visibilitychange","focus"];function b4(e,t){let n;function r(...s){n&&clearTimeout(n),n=setTimeout(()=>{e(...s),n=null},t)}return r.cancel=function(){clearTimeout(n)},r}function Mg(e,t){let n=0;return function(...r){let s=new Date().getTime();if(!(s-n<t))return n=s,e(...r)}}var Nn=()=>Date.now(),_o=2147483647;function y4({timeout:e=1e3*60*20,promptTimeout:t=0,promptBeforeIdle:n=0,element:r=g4,events:s=x4,timers:i=void 0,immediateEvents:o=[],onPresenceChange:l=()=>{},onPrompt:c=()=>{},onIdle:d=()=>{},onActive:u=()=>{},onAction:p=()=>{},onMessage:h=()=>{},debounce:f=0,throttle:g=0,eventsThrottle:x=200,startOnMount:b=!0,startManually:y=!1,stopOnIdle:v=!1,crossTab:C=!1,name:w="idle-timer",syncTimers:S=0,leaderElection:E=!1,disabled:k=!1}={}){let j=m.useRef(Nn()),_=m.useRef(Nn()),D=m.useRef(null),M=m.useRef(null),N=m.useRef(0),O=m.useRef(0),R=m.useRef(0),L=m.useRef(0),P=m.useRef(!1),F=m.useRef(!1),z=m.useRef(!1),B=m.useRef(!0),W=m.useRef(!1),H=m.useRef(null),V=m.useRef(null),G=m.useRef(e),X=m.useRef(0);m.useEffect(()=>{if(t&&console.warn("â ï¸ IdleTimer -- The `promptTimeout` property has been deprecated in favor of `promptBeforeIdle`. It will be removed in the next major release."),n&&t)throw new Error("â Both promptTimeout and promptBeforeIdle can not be set. The promptTimeout property will be deprecated
2in a future version.");if(e>=_o)throw new Error(`â The value for the timeout property must fit in a 32 bit signed integer, ${_o}.`);if(t>=_o)throw new Error(`â The value for the promptTimeout property must fit in a 32 bit signed integer, ${_o}.`);if(n>=_o)throw new Error(`â The value for the promptBeforeIdle property must fit in a 32 bit signed integer, ${_o}.`);if(n>=e)throw new Error(`â The value for the promptBeforeIdle property must be less than the timeout property, ${e}.`);if(n?(G.current=e-n,X.current=n):(G.current=e,X.current=t),!B.current){if(y||k)return;P.current&&(ae.current(null,Rr),V.current&&V.current.active()),at()}},[e,t,n,y,k]);let K=m.useRef(v);m.useEffect(()=>{K.current=v},[v]);let ie=m.useRef(o),le=m.useRef(r),ce=m.useRef([...new Set([...s,...o]).values()]),J=m.useRef(k);m.useEffect(()=>{J.current=k,!B.current&&(k?Ht():y||at())},[k]);let he=m.useRef(l);m.useEffect(()=>{he.current=l},[l]);let ne=m.useRef(c);m.useEffect(()=>{ne.current=c},[c]);let Y=m.useRef(d);m.useEffect(()=>{Y.current=d},[d]);let ae=m.useRef(u);m.useEffect(()=>{ae.current=u},[u]);let je=m.useRef(p);m.useEffect(()=>{je.current=p},[p]);let me=m.useRef(h);m.useEffect(()=>{me.current=h},[h]);let ve=m.useMemo(()=>{let Ae=(jr,np)=>je.current(jr,np);return f>0?b4(Ae,f):g>0?Mg(Ae,g):Ae},[g,f]),Me=m.useRef();m.useEffect(()=>{C&&S&&(Me.current=Mg(()=>{V.current.active()},S))},[C,S]);let q=()=>{H.current!==null&&(us.clearTimeout(H.current),H.current=null)},Q=(Ae,jr=!0)=>{q(),H.current=us.setTimeout(oe,Ae||G.current),jr&&(M.current=Nn())},ee=Ae=>{!F.current&&!P.current&&(ne.current(Ae,Rr),he.current({type:"active",prompted:!0},Rr)),L.current=0,R.current=Nn(),F.current=!0,Q(X.current,!1)},Ce=()=>{q(),P.current||(Y.current(null,Rr),he.current({type:"idle"},Rr)),P.current=!0,D.current=Nn(),K.current?Le():F.current&&(R.current=0,F.current=!1)},se=Ae=>{q(),(P.current||F.current)&&(ae.current(Ae,Rr),he.current({type:"active",prompted:!1},Rr)),F.current=!1,R.current=0,P.current=!1,N.current+=Nn()-D.current,O.current+=Nn()-D.current,ke(),Q()},oe=Ae=>{if(!P.current){ve.cancel&&ve.cancel();let jr=Nn()-M.current;if(!(G.current+X.current<jr)&&X.current>0&&!F.current){V.current?V.current.prompt():ee(Ae);return}V.current?V.current.idle():Ce();return}V.current?V.current.active():se(Ae)},te=Ae=>{if(!b&&!M.current&&(M.current=Nn(),ae.current(null,Rr)),ve(Ae,Rr),F.current)return;if(q(),!P.current&&ie.current.includes(Ae.type)){oe(Ae);return}let jr=Nn()-M.current;if(P.current&&!v||!P.current&&jr>=G.current){oe(Ae);return}z.current=!1,L.current=0,R.current=0,Q(),C&&S&&Me.current()},de=m.useRef(te);m.useEffect(()=>{let Ae=W.current;Ae&&Le(),x>0?de.current=Mg(te,x):de.current=te,Ae&&ke()},[x,g,f,je,C,S]);let ke=()=>{fi&&le.current&&(W.current||(ce.current.forEach(Ae=>{le.current.addEventListener(Ae,de.current,{capture:!0,passive:!0})}),W.current=!0))},Le=(Ae=!1)=>{fi&&le.current&&(W.current||Ae)&&(ce.current.forEach(jr=>{le.current.removeEventListener(jr,de.current,{capture:!0})}),W.current=!1)},at=m.useCallback(Ae=>J.current?!1:(q(),ke(),P.current=!1,F.current=!1,z.current=!1,L.current=0,R.current=0,V.current&&!Ae&&V.current.start(),Q(),!0),[H,P,J,G,V]),Wt=m.useCallback(Ae=>J.current?!1:(q(),ke(),_.current=Nn(),N.current+=Nn()-D.current,O.current+=Nn()-D.current,N.current=0,P.current=!1,F.current=!1,z.current=!1,L.current=0,R.current=0,V.current&&!Ae&&V.current.reset(),y||Q(),!0),[H,P,G,y,J,V]),zt=m.useCallback(Ae=>J.current?!1:(q(),ke(),(P.current||F.current)&&se(),P.current=!1,F.current=!1,z.current=!1,L.current=0,R.current=0,_.current=Nn(),V.current&&!Ae&&V.current.activate(),Q(),!0),[H,P,F,J,G,V]),Ht=m.useCallback((Ae=!1)=>J.current||z.current?!1:(L.current=Vn(),z.current=!0,Le(),q(),V.current&&!Ae&&V.current.pause(),!0),[H,J,V]),Oe=m.useCallback((Ae=!1)=>J.current||!z.current?!1:(z.current=!1,F.current||ke(),P.current||Q(L.current),R.current&&(R.current=Nn()),V.current&&!Ae&&V.current.resume(),!0),[H,G,J,L,V]),Pe=m.useCallback((Ae,jr)=>(V.current?(jr&&me.current(Ae,Rr),V.current.message(Ae)):jr&&me.current(Ae,Rr),!0),[h]),Fe=m.useCallback(()=>P.current,[P]),pt=m.useCallback(()=>F.current,[F]),_t=m.useCallback(()=>V.current?V.current.isLeader:null,[V]),Rn=m.useCallback(()=>V.current?V.current.isLastActive:null,[V]),ot=m.useCallback(()=>V.current?V.current.token:null,[V]),Vn=m.useCallback(()=>
2{if(z.current)return L.current;let Ae=L.current?L.current:X.current+G.current,jr=M.current?Nn()-M.current:0,np=Math.floor(Ae-jr);return np<0?0:Math.abs(np)},[G,X,F,L,M]),Cn=m.useCallback(()=>Math.round(Nn()-_.current),[_]),Sr=m.useCallback(()=>Math.round(Nn()-j.current),[j]),_i=m.useCallback(()=>D.current?new Date(D.current):null,[D]),Ti=m.useCallback(()=>M.current?new Date(M.current):null,[M]),ep=m.useCallback(()=>P.current?Math.round(Nn()-D.current+N.current):Math.round(N.current),[D,N]),tp=m.useCallback(()=>P.current?Math.round(Nn()-D.current+O.current):Math.round(O.current),[D,O]),Hz=m.useCallback(()=>{let Ae=Math.round(Cn()-ep());return Ae>=0?Ae:0},[D,N]),qz=m.useCallback(()=>{let Ae=Math.round(Sr()-tp());return Ae>=0?Ae:0},[D,N]);m.useEffect(()=>{if(f>0&&g>0)throw new Error("â onAction can either be throttled or debounced, not both.");i&&d4(i);let Ae=()=>{V.current&&V.current.close(),ve.cancel&&ve.cancel(),q(),Le(!0)};return fi&&window.addEventListener("beforeunload",Ae),()=>{fi&&window.removeEventListener("beforeunload",Ae),V.current&&V.current.close(),ve.cancel&&ve.cancel(),q(),Le(!0)}},[]),m.useEffect(()=>{V.current&&V.current.close(),C?V.current=new m4({channelName:w,leaderElection:E,onPrompt:()=>{ee()},onIdle:()=>{Ce()},onActive:()=>{se()},onMessage:Ae=>{me.current(Ae,Rr)},start:at,reset:Wt,activate:zt,pause:Ht,resume:Oe}):V.current=null},[C,w,E,ne,Y,ae,me,at,Wt,Ht,Oe]),m.useEffect(()=>{B.current||(q(),Le(!0)),!(y||k)&&(b?at():ke())},[y,b,k,B]),m.useEffect(()=>{if(!B.current){let Ae=[...new Set([...s,...o]).values()];if(Le(),ce.current=Ae,le.current=r,ie.current=o,y||k)return;b?at():ke()}},[r,JSON.stringify(s),JSON.stringify(o),B,k,y,b]),m.useEffect(()=>{B.current&&(B.current=!1)},[B]);let Rr={message:Pe,start:at,reset:Wt,activate:zt,pause:Ht,resume:Oe,isIdle:Fe,isPrompted:pt,isLeader:_t,isLastActiveTab:Rn,getTabId:ot,getRemainingTime:Vn,getElapsedTime:Cn,getTotalElapsedTime:Sr,getLastIdleTime:_i,getLastActiveTime:Ti,getIdleTime:ep,getTotalIdleTime:tp,getActiveTime:Hz,getTotalActiveTime:qz,setOnPresenceChange:Ae=>{l=Ae,he.current=Ae},setOnPrompt:Ae=>{c=Ae,ne.current=Ae},setOnIdle:Ae=>{d=Ae,Y.current=Ae},setOnActive:Ae=>{u=Ae,ae.current=Ae},setOnAction:Ae=>{p=Ae,je.current=Ae},setOnMessage:Ae=>{h=Ae,me.current=Ae}};return Rr}var v4=m.createContext(null);v4.Consumer;const C4=1e3,w4=36e5,S4=18e5,j4=250,k4=e=>{const{signOut:t,resetStoreState:n,fetchAuthSession:r,idleTimeoutMs:s=w4,sessionCheckIntervalMs:i=S4}=e,o=async()=>{const d=t();n(),await d},l=async()=>{try{const d=await r();if(!d?.tokens){await o();return}const u=d.tokens.accessToken?.payload?.exp??0,p=typeof u=="number"?u:0,h=new Date(p*C4).getTime()-Date.now();h<=i?setTimeout(o,Math.max(h,0)):setTimeout(l,i)}catch{await o()}};return{checkSession:l,signUserOut:o,useSessionSetup:()=>{y4({timeout:s,onIdle:o,debounce:j4}),m.useEffect(()=>{l()},[])}}},Pj=typeof window<"u"?window.location.href:"",E4=typeof window<"u"?window.location.search:"",_4=new URLSearchParams(E4),T4=_4.get("code"),I4=typeof window<"u"?window.location.pathname:"",D4=e=>{const{oauthConfig:t,checkForSignedInUser:n,setUserState:r,navigate:s,loginRoute:i,setUserLoading:o}=e;return{checkForSsoAuth:()=>{const d=I4||"";let u=T4;if(!u&&Pj.includes("code=")){const f=Pj.match(/[?&]code=([^&]*)/i);f?.[1]&&(u=decodeURIComponent(f[1]))}const p=/^\/oauth2\/idpresponse$/i.test(d);return{isSsoFlow:!!u||p,code:u,isIdpResponsePath:p}},handleSsoAuthentication:async d=>{try{if(o?.(!0),!await QH({code:d,clientId:t.clientId,domain:t.domain,redirectUri:t.redirectUri}))throw new Error("Token exchange failed");if(!await n(!0))throw new Error("User verification failed after SSO")}catch(u){We(u),r({fullAuthObj:null,validatedUser:null,verified:!1}),o?.(!1),s(i)}}}};function A4(e){e()}let mM=A4;const M4=e=>mM=e,R4=()=>mM,Lj=Symbol.for("react-redux-context"),Fj=typeof globalThis<"u"?globalThis:{};function N4(){var e;if(!m.createContext)return{};const t=(e=Fj[Lj])!=null?e:Fj[Lj]=new Map;let n=t.get(m.createContext);return n||(n=m.createContext(null),t.set(m.createContext,n)),n}const na=N4();function _C(e=na){return function(){return m.useContext(e)}}const gM=_C(),O4=()=>{throw new Error("uSES not initialized!")};let xM=O4;const P4=e=>{xM=e},L4=(e,t)=>
2e===t;function F4(e=na){const t=e===na?gM:_C(e);return function(r,s={}){const{equalityFn:i=L4,stabilityCheck:o=void 0,noopCheck:l=void 0}=typeof s=="function"?{equalityFn:s}:s,{store:c,subscription:d,getServerState:u,stabilityCheck:p,noopCheck:h}=t();m.useRef(!0);const f=m.useCallback({[r.name](x){return r(x)}}[r.name],[r,p,o]),g=xM(d.addNestedSub,c.getState,u||c.getState,f,i);return m.useDebugValue(g),g}}const $4=F4();function z4(){const e=R4();let t=null,n=null;return{clear(){t=null,n=null},notify(){e(()=>{let r=t;for(;r;)r.callback(),r=r.next})},get(){let r=[],s=t;for(;s;)r.push(s),s=s.next;return r},subscribe(r){let s=!0,i=n={callback:r,next:null,prev:n};return i.prev?i.prev.next=i:t=i,function(){!s||t===null||(s=!1,i.next?i.next.prev=i.prev:n=i.prev,i.prev?i.prev.next=i.next:t=i.next)}}}}const $j={notify(){},get:()=>[]};function B4(e,t){let n,r=$j,s=0,i=!1;function o(x){u();const b=r.subscribe(x);let y=!1;return()=>{y||(y=!0,b(),p())}}function l(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function u(){s++,n||(n=e.subscribe(c),r=z4())}function p(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=$j)}function h(){i||(i=!0,u())}function f(){i&&(i=!1,p())}const g={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:h,tryUnsubscribe:f,getListeners:()=>r};return g}const U4=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",V4=U4?m.useLayoutEffect:m.useEffect;function W4({store:e,context:t,children:n,serverState:r,stabilityCheck:s="once",noopCheck:i="once"}){const o=m.useMemo(()=>{const d=B4(e);return{store:e,subscription:d,getServerState:r?()=>r:void 0,stabilityCheck:s,noopCheck:i}},[e,r,s,i]),l=m.useMemo(()=>e.getState(),[e]);V4(()=>{const{subscription:d}=o;return d.onStateChange=d.notifyNestedSubs,d.trySubscribe(),l!==e.getState()&&d.notifyNestedSubs(),()=>{d.tryUnsubscribe(),d.onStateChange=void 0}},[o,l]);const c=t||na;return m.createElement(c.Provider,{value:o},n)}function bM(e=na){const t=e===na?gM:_C(e);return function(){const{store:r}=t();return r}}const H4=bM();function q4(e=na){const t=e===na?H4:bM(e);return function(){return t().dispatch}}const G4=q4();P4(p5.useSyncExternalStoreWithSelector);M4(jD.unstable_batchedUpdates);const Y4=G4,sp=$4,K4=()=>({addFavicon:n=>{if(!n)return;const r=document.createElement("link");r.id="providerFavicon",r.type="image/x-icon",r.rel="shortcut icon",r.href=n,document.head.appendChild(r)},addTitle:n=>{if(!n)return;const r=document.createElement("title");r.id="providerTitle",r.textContent=n,document.head.appendChild(r)}}),Pr=e=>e?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:"",Im=e=>e.split(" ").map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" "),yM=e=>`Are you sure you want to save ${e} edit${e>1?"s":""} made?`,vM=e=>ND(`${e}`,{lower:!0,replacement:""}).replace(/\W/g,""),Q4=e=>{const t=/[^\x00-\x7F]/,n=e.match(t);return n&&n.length>0?n[0]:null},J4=e=>/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e),X4=(e="")=>e?String(e).replace(/[<>:;=]/g,""):"",TC=e=>e?e.toLowerCase().replace(/[\W_]+/g,""):"";var ah={exports:{}},Z4=ah.exports,zj;function eq(){return zj||(zj=1,(function(e,t){(function(n,r){e.exports=r()})(Z4,(function(){var n=1e3,r=6e4,s=36e5,i="millisecond",o="second",l="minute",c="hour",d="day",u="week",p="month",h="quarter",f="year",g="date",x="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,v={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(R){var L=["th","st","nd","rd"],P=R%100;return"["+R+(L[(P-20)%10]||L[P]||L[0])+"]"}},C=function(R,L,P){var F=String(R);return!F||F.length>=L?R:""+Array(L+1-F.length).join(P)+R},w={s:C,z:function(R){var L=-R.utcOffset(),P=Math.abs(L),F=Math.floor(P/60),z=P%60;return(L<=0?"+":"-")+C(F,2,"0")+":"+C(z,2,"0")},m:function R(L,P){if(L.date()<P.date())return-R(P,L);var F=12*(P.year()-L.year())+(P.month()-L.month()),z=L.clone().add(F,p),B=P-z<0,W=L.clone().add(F+(B?-1:1),p);return+(-(F+(P-z)/(B?z-W:W-z))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:p,y:f,w:u,d,D:g,h:c,m:l,s:o,ms:i,Q:h}[R]||String(R||"").toLowerCase().replace(/s$/,"")},u:function(R){return R===void 0}},S="en",E={};E[S]=v;var k="$isDayjsObject",j=function(R){return R instanceof N||!(!R||!R[k])},_=function R(L,P,F){var z;if(!L)return S;if(typeof L=="string"){var B=L.toLowerCase();E[B]&&(z=B),P&&(E[B]=P,z=B);var W=L.split("-");if(!z&&W.length>1)return R(W[0])}else{var H=L.name;E[H]=L,z=H}return!F&&z&&(S=z),z||!F&&S},D=function(R,L){if(j(R))return R.clone();var P=typeof L=="object"?L:{};return P.date=R,P.args=arguments,new N(P)},M=w;M.l=_,M.i=j,M.w=function(R,L){return D(R,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var N=(function(){function R(P){this.$L=_(P.locale,null,!0),this.parse(P),this.$x=this.$x||P.x||{},this[k]=!0}var L=R.prototype;return L.parse=function(P){this.$d=(function(F){var z=F.date,B=F.utc;if(z===null)return new Date(NaN);if(M.u(z))return new Date;if(z instanceof Date)return new Date(z);if(typeof z=="string"&&!/Z$/i.test(z)){var W=z.match(b);if(W){var H=W[2]-1||0,V=(W[7]||"0").substring(0,3);return B?new Date(Date.UTC(W[1],H,W[3]||1,W[4]||0,W[5]||0,W[6]||0,V)):new Date(W[1],H,W[3]||1,W[4]||0,W[5]||0,W[6]||0,V)}}return new Date(z)})(P),this.init()},L.init=function(){var P=this.$d;this.$y=P.getFullYear(),this.$M=P.getMonth(),this.$D=P.getDate(),this.$W=P.getDay(),this.$H=P.getHours(),this.$m=P.getMinutes(),this.$s=P.getSeconds(),this.$ms=P.getMilliseconds()},L.$utils=function(){return M},L.isValid=function(){return this.$d.toString()!==x},L.isSame=function(P,F){var z=D(P);return this.startOf(F)<=z&&z<=this.endOf(F)},L.isAfter=function(P,F){return D(P)<this.startOf(F)},L.isBefore=function(P,F){return this.endOf(F)<D(P)},L.$g=function(P,F,z){return M.u(P)?this[F]:this.set(z,P)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(P,F){var z=this,B=!!M.u(F)||F,W=M.p(P),H=function(J,he){var ne=M.w(z.$u?Date.UTC(z.$y,he,J):new Date(z.$y,he,J),z);return B?ne:ne.endOf(d)},V=function(J,he){return M.w(z.toDate()[J].apply(z.toDate("s"),(B?[0,0,0,0]:[23,59,59,999]).slice(he)),z)},G=this.$W,X=this.$M,K=this.$D,ie="set"+(this.$u?"UTC":"");
2switch(W){case f:return B?H(1,0):H(31,11);case p:return B?H(1,X):H(0,X+1);case u:var le=this.$locale().weekStart||0,ce=(G<le?G+7:G)-le;return H(B?K-ce:K+(6-ce),X);case d:case g:return V(ie+"Hours",0);case c:return V(ie+"Minutes",1);case l:return V(ie+"Seconds",2);case o:return V(ie+"Milliseconds",3);default:return this.clone()}},L.endOf=function(P){return this.startOf(P,!1)},L.$set=function(P,F){var z,B=M.p(P),W="set"+(this.$u?"UTC":""),H=(z={},z[d]=W+"Date",z[g]=W+"Date",z[p]=W+"Month",z[f]=W+"FullYear",z[c]=W+"Hours",z[l]=W+"Minutes",z[o]=W+"Seconds",z[i]=W+"Milliseconds",z)[B],V=B===d?this.$D+(F-this.$W):F;if(B===p||B===f){var G=this.clone().set(g,1);G.$d[H](V),G.init(),this.$d=G.set(g,Math.min(this.$D,G.daysInMonth())).$d}else H&&this.$d[H](V);return this.init(),this},L.set=function(P,F){return this.clone().$set(P,F)},L.get=function(P){return this[M.p(P)]()},L.add=function(P,F){var z,B=this;P=Number(P);var W=M.p(F),H=function(X){var K=D(B);return M.w(K.date(K.date()+Math.round(X*P)),B)};if(W===p)return this.set(p,this.$M+P);if(W===f)return this.set(f,this.$y+P);if(W===d)return H(1);if(W===u)return H(7);var V=(z={},z[l]=r,z[c]=s,z[o]=n,z)[W]||1,G=this.$d.getTime()+P*V;return M.w(G,this)},L.subtract=function(P,F){return this.add(-1*P,F)},L.format=function(P){var F=this,z=this.$locale();if(!this.isValid())return z.invalidDate||x;var B=P||"YYYY-MM-DDTHH:mm:ssZ",W=M.z(this),H=this.$H,V=this.$m,G=this.$M,X=z.weekdays,K=z.months,ie=z.meridiem,le=function(he,ne,Y,ae){return he&&(he[ne]||he(F,B))||Y[ne].slice(0,ae)},ce=function(he){return M.s(H%12||12,he,"0")},J=ie||function(he,ne,Y){var ae=he<12?"AM":"PM";return Y?ae.toLowerCase():ae};return B.replace(y,(function(he,ne){return ne||(function(Y){switch(Y){case"YY":return String(F.$y).slice(-2);case"YYYY":return M.s(F.$y,4,"0");case"M":return G+1;case"MM":return M.s(G+1,2,"0");case"MMM":return le(z.monthsShort,G,K,3);case"MMMM":return le(K,G);case"D":return F.$D;case"DD":return M.s(F.$D,2,"0");case"d":return String(F.$W);case"dd":return le(z.weekdaysMin,F.$W,X,2);case"ddd":return le(z.weekdaysShort,F.$W,X,3);case"dddd":return X[F.$W];case"H":return String(H);case"HH":return M.s(H,2,"0");case"h":return ce(1);case"hh":return ce(2);case"a":return J(H,V,!0);case"A":return J(H,V,!1);case"m":return String(V);case"mm":return M.s(V,2,"0");case"s":return String(F.$s);case"ss":return M.s(F.$s,2,"0");case"SSS":return M.s(F.$ms,3,"0");case"Z":return W}return null})(he)||W.replace(":","")}))},L.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},L.diff=function(P,F,z){var B,W=this,H=M.p(F),V=D(P),G=(V.utcOffset()-this.utcOffset())*r,X=this-V,K=function(){return M.m(W,V)};switch(H){case f:B=K()/12;break;case p:B=K();break;case h:B=K()/3;break;case u:B=(X-G)/6048e5;break;case d:B=(X-G)/864e5;break;case c:B=X/s;break;case l:B=X/r;break;case o:B=X/n;break;default:B=X}return z?B:M.a(B)},L.daysInMonth=function(){return this.endOf(p).$D},L.$locale=function(){return E[this.$L]},L.locale=function(P,F){if(!P)return this.$L;var z=this.clone(),B=_(P,F,!0);return B&&(z.$L=B),z},L.clone=function(){return M.w(this.$d,this)},L.toDate=function(){return new Date(this.valueOf())},L.toJSON=function(){return this.isValid()?this.toISOString():null},L.toISOString=function(){return this.$d.toISOString()},L.toString=function(){return this.$d.toUTCString()},R})(),O=N.prototype;return D.prototype=O,[["$ms",i],["$s",o],["$m",l],["$H",c],["$W",d],["$M",p],["$y",f],["$D",g]].forEach((function(R){O[R[1]]=function(L){return this.$g(L,R[0],R[1])}})),D.extend=function(R,L){return R.$i||(R(L,N,D),R.$i=!0),D},D.locale=_,D.isDayjs=j,D.unix=function(R){return D(1e3*R)},D.en=E[S],D.Ls=E,D.p={},D}))})(ah)),ah.exports}var tq=eq();const Z=dt(tq);var oh={exports:{}},nq=oh.exports,Bj;function rq(){return Bj||(Bj=1,(function(e,t){(function(n,r){e.exports=r()})(nq,(function(){return function(n,r,s){n=n||{};var i=r.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function l(d,u,p,h){return i.fromToBase(d,u,p,h)}s.en.relativeTime=o,i.fromToBase=function(d,u,p,h,f){for(var g,x,b,y=p.$locale().relativeTime||o,v=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],C=v.length,w=0;w<C;w+=1){var S=v[w];S.d&&(g=h?s(d).diff(p,S.d,!0):p.diff(d,S.d,!0));var E=(n.rounding||Math.round)(Math.abs(g));if(b=g>0,E<=S.r||!S.r){E<=1&&w>0&&(S=v[w-1]);var k=y[S.l];f&&(E=f(""+E)),x=typeof k=="string"?k.replace("%d",E):k(E,u,S.l,b);break}}if(u)return x;var j=b?y.future:y.past;return typeof j=="function"?j(x):j.replace("%s",x)}
2,i.to=function(d,u){return l(d,u,this,!0)},i.from=function(d,u){return l(d,u,this)};var c=function(d){return d.$u?s.utc():s()};i.toNow=function(d){return this.to(c(this),d)},i.fromNow=function(d){return this.from(c(this),d)}}}))})(oh)),oh.exports}var sq=rq();const iq=dt(sq);var lh={exports:{}},aq=lh.exports,Uj;function oq(){return Uj||(Uj=1,(function(e,t){(function(n,r){e.exports=r()})(aq,(function(){var n="minute",r=/[+-]\d\d(?::?\d\d)?/g,s=/([+-]|\d\d)/g;return function(i,o,l){var c=o.prototype;l.utc=function(x){var b={date:x,utc:!0,args:arguments};return new o(b)},c.utc=function(x){var b=l(this.toDate(),{locale:this.$L,utc:!0});return x?b.add(this.utcOffset(),n):b},c.local=function(){return l(this.toDate(),{locale:this.$L,utc:!1})};var d=c.parse;c.parse=function(x){x.utc&&(this.$u=!0),this.$utils().u(x.$offset)||(this.$offset=x.$offset),d.call(this,x)};var u=c.init;c.init=function(){if(this.$u){var x=this.$d;this.$y=x.getUTCFullYear(),this.$M=x.getUTCMonth(),this.$D=x.getUTCDate(),this.$W=x.getUTCDay(),this.$H=x.getUTCHours(),this.$m=x.getUTCMinutes(),this.$s=x.getUTCSeconds(),this.$ms=x.getUTCMilliseconds()}else u.call(this)};var p=c.utcOffset;c.utcOffset=function(x,b){var y=this.$utils().u;if(y(x))return this.$u?0:y(this.$offset)?p.call(this):this.$offset;if(typeof x=="string"&&(x=(function(S){S===void 0&&(S="");var E=S.match(r);if(!E)return null;var k=(""+E[0]).match(s)||["-",0,0],j=k[0],_=60*+k[1]+ +k[2];return _===0?0:j==="+"?_:-_})(x),x===null))return this;var v=Math.abs(x)<=16?60*x:x,C=this;if(b)return C.$offset=v,C.$u=x===0,C;if(x!==0){var w=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(C=this.local().add(v+w,n)).$offset=v,C.$x.$localOffset=w}else C=this.utc();return C};var h=c.format;c.format=function(x){var b=x||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return h.call(this,b)},c.valueOf=function(){var x=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*x},c.isUTC=function(){return!!this.$u},c.toISOString=function(){return this.toDate().toISOString()},c.toString=function(){return this.toDate().toUTCString()};var f=c.toDate;c.toDate=function(x){return x==="s"&&this.$offset?l(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():f.call(this)};var g=c.diff;c.diff=function(x,b,y){if(x&&this.$u===x.$u)return g.call(this,x,b,y);var v=this.local(),C=l(x).local();return g.call(v,C,b,y)}}}))})(lh)),lh.exports}var lq=oq();const El=dt(lq);Z.extend(iq);Z.extend(El);const ch=e=>Z.utc(e).local(),CM=e=>ch(e).fromNow();var cq=(...e)=>{const t=h5(...e),n=Object.assign((...r)=>{const s=t(...r),i=(o,...l)=>s(oC(o)?f5(o):o,...l);return Object.assign(i,s),i},{withTypes:()=>n});return n};cq(Ob);var dq=e=>e&&typeof e.match=="function";function wr(e,t){function n(...r){if(t){let s=t(...r);if(!s)throw new Error(Dr(0));return{type:e,payload:s.payload,..."meta"in s&&{meta:s.meta},..."error"in s&&{error:s.error}}}return{type:e,payload:r[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=r=>gA(r)&&r.type===e,n}function Vj(e){return aC(e)?pu(e,()=>{}):e}function Wj(e,t,n){if(e.has(t)){let s=e.get(t);return n.update&&(s=n.update(s,t,e),e.set(t,s)),s}if(!n.insert)throw new Error(Dr(10));const r=n.insert(t,e);return e.set(t,r),r}var nd="RTK_autoBatch",Ql=()=>e=>({payload:e,meta:{[nd]:!0}});function wM(e){const t={},n=[];let r;const s={addCase(i,o){const l=typeof i=="string"?i:i.type;if(!l)throw new Error(Dr(28));if(l in t)throw new Error(Dr(29));return t[l]=o,s},addMatcher(i,o){return n.push({matcher:i,reducer:o}),s},addDefaultCase(i){return r=i,s}};return e(s),[t,n,r]}function uq(e){return typeof e=="function"}function pq(e,t){let[n,r,s]=wM(t),i;if(uq(e))i=()=>Vj(e());else{const l=Vj(e);i=()=>l}function o(l=i(),c){let d=[n[c.type],...r.filter(({matcher:u})=>u(c)).map(({reducer:u})=>u)];return d.filter(u=>!!u).length===0&&(d=[s]),d.reduce((u,p)=>{if(p)if(oC(u)){const f=p(u,c);return f===void 0?u:f}else{if(aC(u))return pu(u,h=>p(h,c));{const h=p(u,c);if(h===void 0){if(u===null)return u;throw new Error(Dr(9))}return h}}return u},l)}return o.getInitialState=i,o}var hq="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",IC=(e=21)=>{let t="",n=e;for(;n--;)t+=hq[Math.random()*64|0];return t},SM=(e,t)=>dq(e)?e.match(t):e(t);function vi(...e){return t=>e.some(n=>SM(n,t))}function hd(...e){return t=>e.every(n=>SM(n,t))}function Dm(e,t){if(!e||!e.meta)return!1;const n=typeof e.meta.requestId=="string",r=t.indexOf(e.meta.requestStatus)>-1;return n&&r}function bu(e){return typeof e[0]=="function"&&"pending"in e[0]&&"fulfilled"in e[0]&&"rejected"in e[0]}function DC(...e){return e.length===0?t=>
2Dm(t,["pending"]):bu(e)?t=>{const n=e.map(s=>s.pending);return vi(...n)(t)}:DC()(e[0])}function il(...e){return e.length===0?t=>Dm(t,["rejected"]):bu(e)?t=>{const n=e.map(s=>s.rejected);return vi(...n)(t)}:il()(e[0])}function Am(...e){const t=n=>n&&n.meta&&n.meta.rejectedWithValue;return e.length===0?n=>hd(il(...e),t)(n):bu(e)?n=>hd(il(...e),t)(n):Am()(e[0])}function ra(...e){return e.length===0?t=>Dm(t,["fulfilled"]):bu(e)?t=>{const n=e.map(s=>s.fulfilled);return vi(...n)(t)}:ra()(e[0])}function zb(...e){return e.length===0?t=>Dm(t,["pending","fulfilled","rejected"]):bu(e)?t=>{const n=[];for(const s of e)n.push(s.pending,s.rejected,s.fulfilled);return vi(...n)(t)}:zb()(e[0])}var fq=["name","message","stack","code"],Rg=class{constructor(e,t){this.payload=e,this.meta=t}_type},Hj=class{constructor(e,t){this.payload=e,this.meta=t}_type},mq=e=>{if(typeof e=="object"&&e!==null){const t={};for(const n of fq)typeof e[n]=="string"&&(t[n]=e[n]);return t}return{message:String(e)}},qj=(()=>{function e(t,n,r){const s=wr(t+"/fulfilled",(c,d,u,p)=>({payload:c,meta:{...p||{},arg:u,requestId:d,requestStatus:"fulfilled"}})),i=wr(t+"/pending",(c,d,u)=>({payload:void 0,meta:{...u||{},arg:d,requestId:c,requestStatus:"pending"}})),o=wr(t+"/rejected",(c,d,u,p,h)=>({payload:p,error:(r&&r.serializeError||mq)(c||"Rejected"),meta:{...h||{},arg:u,requestId:d,rejectedWithValue:!!p,requestStatus:"rejected",aborted:c?.name==="AbortError",condition:c?.name==="ConditionError"}}));function l(c){return(d,u,p)=>{const h=r?.idGenerator?r.idGenerator(c):IC(),f=new AbortController;let g,x;function b(v){x=v,f.abort()}const y=(async function(){let v;try{let w=r?.condition?.(c,{getState:u,extra:p});if(xq(w)&&(w=await w),w===!1||f.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const S=new Promise((E,k)=>{g=()=>{k({name:"AbortError",message:x||"Aborted"})},f.signal.addEventListener("abort",g)});d(i(h,c,r?.getPendingMeta?.({requestId:h,arg:c},{getState:u,extra:p}))),v=await Promise.race([S,Promise.resolve(n(c,{dispatch:d,getState:u,extra:p,requestId:h,signal:f.signal,abort:b,rejectWithValue:(E,k)=>new Rg(E,k),fulfillWithValue:(E,k)=>new Hj(E,k)})).then(E=>{if(E instanceof Rg)throw E;return E instanceof Hj?s(E.payload,h,c,E.meta):s(E,h,c)})])}catch(w){v=w instanceof Rg?o(null,h,c,w.payload,w.meta):o(w,h,c)}finally{g&&f.signal.removeEventListener("abort",g)}return r&&!r.dispatchConditionRejection&&o.match(v)&&v.meta.condition||d(v),v})();return Object.assign(y,{abort:b,requestId:h,arg:c,unwrap(){return y.then(gq)}})}}return Object.assign(l,{pending:i,rejected:o,fulfilled:s,settled:vi(o,s),typePrefix:t})}return e.withTypes=()=>e,e})();function gq(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}function xq(e){return e!==null&&typeof e=="object"&&typeof e.then=="function"}var bq=Symbol.for("rtk-slice-createasyncthunk");function yq(e,t){return`${e}/${t}`}function vq({creators:e}={}){const t=e?.asyncThunk?.[bq];return function(r){const{name:s,reducerPath:i=s}=r;if(!s)throw new Error(Dr(11));const o=(typeof r.reducers=="function"?r.reducers(wq()):r.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},d={addCase(v,C){const w=typeof v=="string"?v:v.type;if(!w)throw new Error(Dr(12));if(w in c.sliceCaseReducersByType)throw new Error(Dr(13));return c.sliceCaseReducersByType[w]=C,d},addMatcher(v,C){return c.sliceMatchers.push({matcher:v,reducer:C}),d},exposeAction(v,C){return c.actionCreators[v]=C,d},exposeCaseReducer(v,C){return c.sliceCaseReducersByName[v]=C,d}};l.forEach(v=>{const C=o[v],w={reducerName:v,type:yq(s,v),createNotation:typeof r.reducers=="function"};jq(C)?Eq(w,C,d,t):Sq(w,C,d)});function u(){const[v={},C=[],w=void 0]=typeof r.extraReducers=="function"?wM(r.extraReducers):[r.extraReducers],S={...v,...c.sliceCaseReducersByType};return pq(r.initialState,E=>{for(let k in S)E.addCase(k,S[k]);for(let k of c.sliceMatchers)E.addMatcher(k.matcher,k.reducer);for(let k of C)E.addMatcher(k.matcher,k.reducer);w&&E.addDefaultCase(w)})}const p=v=>v,h=new Map;let f;function g(v,C){return f||(f=u()),f(v,C)}function x(){return f||(f=u()),f.getInitialState()}function b(v,C=!1){function w(E){let k=E[v];return typeof k>
2"u"&&C&&(k=x()),k}function S(E=p){const k=Wj(h,C,{insert:()=>new WeakMap});return Wj(k,E,{insert:()=>{const j={};for(const[_,D]of Object.entries(r.selectors??{}))j[_]=Cq(D,E,x,C);return j}})}return{reducerPath:v,getSelectors:S,get selectors(){return S(w)},selectSlice:w}}const y={name:s,reducer:g,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:x,...b(i),injectInto(v,{reducerPath:C,...w}={}){const S=C??i;return v.inject({reducerPath:S,reducer:g},w),{...y,...b(S,!0)}}};return y}}function Cq(e,t,n,r){function s(i,...o){let l=t(i);return typeof l>"u"&&r&&(l=n()),e(l,...o)}return s.unwrapped=e,s}var To=vq();function wq(){function e(t,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...n}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...n){return t(...n)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:n}},asyncThunk:e}}function Sq({type:e,reducerName:t,createNotation:n},r,s){let i,o;if("reducer"in r){if(n&&!kq(r))throw new Error(Dr(17));i=r.reducer,o=r.prepare}else i=r;s.addCase(e,i).exposeCaseReducer(t,i).exposeAction(t,o?wr(e,o):wr(e))}function jq(e){return e._reducerDefinitionType==="asyncThunk"}function kq(e){return e._reducerDefinitionType==="reducerWithPrepare"}function Eq({type:e,reducerName:t},n,r,s){if(!s)throw new Error(Dr(18));const{payloadCreator:i,fulfilled:o,pending:l,rejected:c,settled:d,options:u}=n,p=s(e,i,u);r.exposeAction(t,p),o&&r.addCase(p.fulfilled,o),l&&r.addCase(p.pending,l),c&&r.addCase(p.rejected,c),d&&r.addMatcher(p.settled,d),r.exposeCaseReducer(t,{fulfilled:o||ip,pending:l||ip,rejected:c||ip,settled:d||ip})}function ip(){}var _q=(e,t)=>{if(typeof e!="function")throw new Error(Dr(32))},AC="listenerMiddleware",Tq=e=>{let{type:t,actionCreator:n,matcher:r,predicate:s,effect:i}=e;if(t)s=wr(t).match;else if(n)t=n.type,s=n.match;else if(r)s=r;else if(!s)throw new Error(Dr(21));return _q(i),{predicate:s,type:t,effect:i}},Iq=Object.assign(e=>{const{type:t,predicate:n,effect:r}=Tq(e);return{id:IC(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(Dr(22))}}},{withTypes:()=>Iq}),Dq=Object.assign(wr(`${AC}/add`),{withTypes:()=>Dq});wr(`${AC}/removeAll`);var Aq=Object.assign(wr(`${AC}/remove`),{withTypes:()=>Aq});function Dr(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const Mq=e=>{const t=xA.endpoints.engagements.select(e),n=Tj.getInitialState(),r=Oi(t,s=>Tj.getSelectors(()=>s?.data??n));return{selectAll:Oi(r,s=>s.selectAll(null)),selectEntities:Oi(r,s=>s.selectEntities(null)),selectIds:Oi(r,s=>s.selectIds(null)),selectTotal:Oi(r,s=>s.selectTotal(null)),selectById:s=>Oi(r,i=>i.selectById(i,s))}},Rq=xA.endpoints.userEngagements.select({assigned:!0}),Nq=Oi(Rq,e=>e.data),Oq=bA.getInitialState(),{selectAll:Pq,selectById:Lq}=bA.getSelectors(e=>Nq(e)??Oq),yu=e=>{const t=sp(Pq),n=sp(l=>Lq(l,e)),{selectAll:r,selectById:s}=Mq(n?.client_id||-1),i=sp(r);return{currentEngagement:sp(s(e)),currentUserEngagement:n,engagements:i,userEngagements:t}},MC=({clientNiceId:e,engagementNiceId:t,userIsInternal:n})=>m5({clientNiceId:e,engagementNiceId:t,userIsInternal:n}),Fq=()=>{const e=Y4();return()=>{e(g5.util.resetApiState()),e(x5.util.resetApiState()),e(b5.util.resetApiState())}},$q=C5(e=>({jwt:e.user.jwt,accessToken:e.user.accessToken}));v5({getToken:$q,isDevelopment:bm});const zq=y5({isDevelopment:bm});({...S5},{...w5});const Bq=["InternalRoles-FullPermissions"],jM=["InternalRoles-FullPermissions","InternalRoles-InternalConfiguration","InternalRoles-InternalAdmin","InternalRoles-MediaInternalAdmin","CustomerRoles-ProviderFullPermissions","CustomerRoles-CustomerAdmin"],gt=j5({roleChecks:[{propertyName:"userIsSuper",roles:Bq},{propertyName:"userIsFeaturesAdmin",roles:jM}],isAuthorized:(e,t)=>pM([...e],[...t])}),Uq=k5(Fq),kM=m.createContext({}),_l=()=>m.useContext(kM),EM=({authorized:e,config:t,exact:n=!1})=>{const r=Array.isArray(e)?e:[e],s=r.filter(i=>t?.[i]).length;return n?s===r.length:!!s},yn=({authorized:e,exact:t=!1})=>{const n=_l();return m.useMemo(()=>EM({authorized:e,config:n,exact:t}),[e,n,t])},ar=({authorized:e,children:t,exact:n=!1,renderOff:r=()=>null,renderOn:s=()=>null})=>yn({authorized:e,exact:n})?t||s():r(),Vq={},Wq=({children:e,config:t})=>{const{engagementId:n,engagementNiceId:r}=pe(),{currentData:s=Vq}=yA(n,{skip:!r||!!t}),i=bm&&t||s;return a.jsx(kM.Provider,{value:i,children:e})},_M="/settings/feature-management",Hq=e=>{const{engagementId:t,engagementNiceId:n,nextEngagement:r}=pe(),{isError:s,isFetching:i}=E5(r,{skip:!e}),o=es(),{isError:l}=_5({assigned:!0},{skip:!e}),{isError:c,isFetching:d,isLoading:u,isUninitialized:p}=yA(t,{skip:!(e&&n)}),h=m.useMemo(()=>o.pathname===_M?u:d,[o.pathname,d,u]),f=i||p||h,g=l||s||c;return m.useMemo(()=>({isAppError:g,isAppLoading:f,ermFetching:i}),[g,f,i])},qq="Darwin",Gq=()=>{const e=ct(),t=es(),n=Hv(),{userVerified:r}=gt(),s=Uq(),i=lC(),{isAppError:o,isAppLoading:l,ermFetching:c}=Hq(r),[d,u]=m.useState(!1),[p,h]=m.useState(!0),[f,g]=m.useState("/"),[x,b]=m.useState(!1),{notifications:y,pushNotification:v,clearNotification:C,clearAllNotifications:w}=OD(),S=m.useRef(!1),{addFavicon:E,addTitle:k}=K4(),j=`https://${window.location.hostname}`,{data:_}=T5(j,{skip:!r}
2),D=_?.domain_url||"",M=_?.name||"",N=_?.nice_id||"",O=_?.support_url||"",{name:R=qq}=_?.llm_chat_config??{},L=m.useRef(null);L.current||(L.current=k4({signOut:dM,resetStoreState:s,fetchAuthSession:sl}));const{checkSession:P,signUserOut:F,useSessionSetup:z}=L.current;z(),m.useEffect(()=>{c&&w()},[c,w]);const B=()=>{E(hs.faviconUrl),k(hs.companyName)},W=async(X=!1)=>{try{const K=await EC(),ie=await sl(),le=cC.parse({username:K.username,userId:K.userId,signInDetails:K.signInDetails,session:ie});if(e()&&await XH(ie)){if(i({fullAuthObj:{user:K,session:ie},validatedUser:le,verified:!0}),h(!1),P(),X){const ce=!f||f==="/login"||f.includes("/oauth2/idpresponse")?"/":f;n(ce)}return!0}throw new Error("user unverified")}catch{if(e()){s();const K=t.pathname==="/login"?"/":t.pathname+t.search;g(K),h(!1),S.current||n("/login")}return!1}},H=hs.amplify.Auth.Cognito,V=H.loginWith?.oauth,G=m.useMemo(()=>D4({oauthConfig:{clientId:H.userPoolClientId,domain:V?.domain??"",redirectUri:V?.redirectSignIn[0]??""},checkForSignedInUser:W,setUserState:i,navigate:n,loginRoute:"/login",setUserLoading:h}),[W,n,i,h]);return m.useEffect(()=>{const{isSsoFlow:X,code:K}=G.checkForSsoAuth();X&&K?(S.current=!0,b(!0),G.handleSsoAuthentication(K)):W(),B()},[]),{checkSession:P,domainUrl:D,initialLandingPath:f,isAppError:o,isAppLoading:l,providerName:M,providerNiceId:N,raiseConversationIcon:d,setInitialLandingPath:g,setRaiseConversationIcon:u,setUserLoading:h,signUserOut:F,supportLink:O,userLoading:p,llmAssistantName:R,isSsoAuthentication:x,notifications:y,pushNotification:v,clearNotification:C}},TM=m.createContext(null),jt=()=>m.useContext(TM),Yq=({children:e})=>{const t=Gq();return a.jsx(TM.Provider,{value:t,children:e})},Kq=({children:e})=>{const{engagementId:t}=pe(),{accessToken:n}=gt(),{webSocketUrl:r}=hs;return a.jsx(I5,{engagementId:t,token:n,url:r,children:e})},Qq="49b4ccc777069bb8c4246f6f575c7f31Tz0xMjgzMjksRT0xODA4MDA2Mzk5MDAwLFM9cHJvLExNPWFubnVhbCxQVj1pbml0aWFsLEtWPTI=";xW.setLicenseKey(Qq);const Jq=({children:e})=>{const{isPluscoDomain:t}=hs,{search:n}=window.location,r=new URLSearchParams(n),s=t||bm&&r.get("theme")==="plusco";return a.jsx(fB,{children:a.jsxs(mB,{themeName:s?"plusco":"mevo",children:[a.jsx(W4,{store:zq,children:a.jsx(gB,{children:a.jsx(Yq,{children:a.jsx(Wq,{children:a.jsx(Kq,{children:e})})})})}),a.jsx(xB,{})]})})},Xq=m.forwardRef(({TooltipProps:e,...t},n)=>{const{title:r,...s}=e;return a.jsx(be,{...s,title:r,children:a.jsx(T,{children:a.jsx(yi,{ref:n,...t})})})}),Zq={contribution:{label:"Contribution",tooltip:"Explore aggregated data based on conversion date."},attribution:{label:"Attribution",tooltip:"Explore aggregated data based on media exposure date."}},Mm=({disabled:e,onChange:t,testId:n,value:r,isLoading:s=!1})=>a.jsx(Nt,{isLoading:s,children:a.jsx(ml,{"aria-label":"attribution-contribution-toggle",color:"primary","data-testid":n,disabled:e,onChange:({target:i})=>{const o=i.value;t(o)},size:"small",value:r,children:Object.entries(Zq).map(([i,{label:o,tooltip:l}])=>a.jsx(Xq,{"data-testid":n?`${n}:${i}`:void 0,TooltipProps:{title:l},value:i,children:o},i))})}),vu=({handleNavigateHome:e,pageName:t,parentConfig:n})=>{const r=Array.isArray(n)?n:[n];return a.jsxs(Zz,{sx:{color:"text.disabled",pb:1},children:[a.jsx(He,{sx:{pb:.5},onClick:e,children:a.jsx(bB,{size:16})}),r.map(({handleNavigateToParent:s,parentName:i},o)=>a.jsx(He,{onClick:s,children:a.jsx(I,{variant:"body2",children:i||"..."})},o)),a.jsx(I,{color:"text.secondary",variant:"body2",children:t||"..."})]})},e6=({dataUrl:e,extension:t,fileName:n})=>{const r=document.createElement("a");r.href=e,r.download=`${n}.${t}`,document.body.appendChild(r),r.click(),document.body.removeChild(r)},t6=[{fileType:"csv",name:"CSV"},{fileType:"png",name:"PNG"}],Rm=({getFileData:e,menuOptions:t=t6,onDownload:n=()=>{},disabled:r=!1})=>{const[s,i]=m.useState(null),o=!!s,l=p=>{i(p.currentTarget)},c=()=>{i(null)},d=m.useCallback(p=>()=>{const h=e(p),{dataUrl:f,error:g=!1,fileName:x}=h;g||(e6({extension:p,fileName:x,dataUrl:f}),n({fileName:x,fileType:p})),i(null)},[e,n]),u=m.useMemo(()=>t.map(({fileType:p,name:h})=>a.jsxs(Se,{onClick:d(p),children:["Download ",h]},h)),[d,t]);return a.jsxs(a.Fragment,{children:[a.jsx(Ie,{disableRipple:!0,disabled:r,onClick:l,children:a.jsx(bl,{size:20})}),a.jsx(dr,{anchorEl:s,onClose:c,open:o,children:u})]})},sa=({src:e,size:t=24})=>a.jsx(T,{sx:n=>({width:t,height:t,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"transparent","& > img":{objectFit:"contain",height:"100%",width:"100%",mixBlendMode:n.palette.mode==="dark"?"lighten":"multiply",opacity:n.palette.mode==="dark"?.9:1}}),children:!!e?.trim()?.length&&a.jsx("img",{src:e,alt:"connector icon",loading:"lazy"})}),Tl=rt(De)(({theme:e})=>{const{neutral:t}=e.palette;return{".MuiFormLabel-root":{height:48,letterSpacing:"0.15px",lineHeight:"24px",transitionProperty:"color, transform, max-width, font-size, line-height","&.MuiInputLabel-root":{transform:"translate(12px, 12px)"},"&.MuiInputLabel-shrink":{fontSize:11,lineHeight:"12px",transform:"translate(12px, 6px)"},"&.Mui-focused":{transform:"translate(12px, 6px)"}},".MuiInputBase-root":{borderColor:t[300],"&.MuiFilledInput-root > input":{height:24,letterSpacing:"0.15px",padding:"19px 11px 3px 11px","&.Mu
2iInputBase-inputAdornedStart":{paddingLeft:"8px"}}},"&.Mui-error":{".MuiFormLabel-root":{color:e.palette.error.main},".MuiInputBase-root":{borderColor:e.palette.error.main,"&.MuiFilledInput-root > input":{letterSpacing:"0.15px",padding:"19px 11px 3px 11px",color:e.palette.error.main}}}}}),n6=rt(Tl)(()=>({".MuiInputBase-root":{"&.MuiFilledInput-root > input":{padding:"10px 11px 10px 11px"}},"&.Mui-error":{".MuiInputBase-root":{"&.MuiFilledInput-root > input":{padding:"10px 11px 10px 11px"}}}})),Gj=({disabled:e,handleChange:t,startAdornment:n,isError:r,value:s})=>a.jsx(iu,{allowLeadingZeros:!1,allowNegative:!0,customInput:n6,decimalScale:3,onValueChange:t,thousandSeparator:",",value:s,label:!1,disabled:e,error:r,fullWidth:!0,InputProps:n?{startAdornment:a.jsx(Bn,{position:"start",sx:{mr:0,mt:"0px !important"},children:n})}:void 0});var dh={exports:{}},r6=dh.exports,Yj;function s6(){return Yj||(Yj=1,(function(e,t){(function(n,r){e.exports=r()})(r6,(function(){var n="week",r="year";return function(s,i,o){var l=i.prototype;l.week=function(c){if(c===void 0&&(c=null),c!==null)return this.add(7*(c-this.week()),"day");var d=this.$locale().yearStart||1;if(this.month()===11&&this.date()>25){var u=o(this).startOf(r).add(1,r).date(d),p=o(this).endOf(n);if(u.isBefore(p))return 1}var h=o(this).startOf(r).date(d).startOf(n).subtract(1,"millisecond"),f=this.diff(h,n,!0);return f<0?o(this).startOf("week").week():Math.ceil(f)},l.weeks=function(c){return c===void 0&&(c=null),this.week(c)}}}))})(dh)),dh.exports}var i6=s6();const a6=dt(i6);var uh={exports:{}},o6=uh.exports,Kj;function l6(){return Kj||(Kj=1,(function(e,t){(function(n,r){e.exports=r()})(o6,(function(){var n={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},r=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,s=/\d\d/,i=/\d\d?/,o=/\d*[^-_:/,()\s\d]+/,l={},c=function(x){return(x=+x)+(x>68?1900:2e3)},d=function(x){return function(b){this[x]=+b}},u=[/[+-]\d\d:?(\d\d)?|Z/,function(x){(this.zone||(this.zone={})).offset=(function(b){if(!b||b==="Z")return 0;var y=b.match(/([+-]|\d\d)/g),v=60*y[1]+(+y[2]||0);return v===0?0:y[0]==="+"?-v:v})(x)}],p=function(x){var b=l[x];return b&&(b.indexOf?b:b.s.concat(b.f))},h=function(x,b){var y,v=l.meridiem;if(v){for(var C=1;C<=24;C+=1)if(x.indexOf(v(C,0,b))>-1){y=C>12;break}}else y=x===(b?"pm":"PM");return y},f={A:[o,function(x){this.afternoon=h(x,!1)}],a:[o,function(x){this.afternoon=h(x,!0)}],S:[/\d/,function(x){this.milliseconds=100*+x}],SS:[s,function(x){this.milliseconds=10*+x}],SSS:[/\d{3}/,function(x){this.milliseconds=+x}],s:[i,d("seconds")],ss:[i,d("seconds")],m:[i,d("minutes")],mm:[i,d("minutes")],H:[i,d("hours")],h:[i,d("hours")],HH:[i,d("hours")],hh:[i,d("hours")],D:[i,d("day")],DD:[s,d("day")],Do:[o,function(x){var b=l.ordinal,y=x.match(/\d+/);if(this.day=y[0],b)for(var v=1;v<=31;v+=1)b(v).replace(/\[|\]/g,"")===x&&(this.day=v)}],M:[i,d("month")],MM:[s,d("month")],MMM:[o,function(x){var b=p("months"),y=(p("monthsShort")||b.map((function(v){return v.slice(0,3)}))).indexOf(x)+1;if(y<1)throw new Error;this.month=y%12||y}],MMMM:[o,function(x){var b=p("months").indexOf(x)+1;if(b<1)throw new Error;this.month=b%12||b}],Y:[/[+-]?\d+/,d("year")],YY:[s,function(x){this.year=c(x)}],YYYY:[/\d{4}/,d("year")],Z:u,ZZ:u};function g(x){var b,y;b=x,y=l&&l.formats;for(var v=(x=b.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(_,D,M){var N=M&&M.toUpperCase();return D||y[M]||n[M]||y[N].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(O,R,L){return R||L.slice(1)}))}))).match(r),C=v.length,w=0;w<C;w+=1){var S=v[w],E=f[S],k=E&&E[0],j=E&&E[1];v[w]=j?{regex:k,parser:j}:S.replace(/^\[|\]$/g,"")}return function(_){for(var D={},M=0,N=0;M<C;M+=1){var O=v[M];if(typeof O=="string")N+=O.length;else{var R=O.regex,L=O.parser,P=_.slice(N),F=R.exec(P)[0];L.call(D,F),_=_.replace(F,"")}}return(function(z){var B=z.afternoon;if(B!==void 0){var W=z.hours;B?W<12&&(z.hours+=12):W===12&&(z.hours=0),delete z.afternoon}})(D),D}}return function(x,b,y){y.p.customParseFormat=!0,x&&x.parseTwoDigitYear&&(c=x.parseTwoDigitYear);var v=b.prototype,C=v.parse;v.parse=function(w){var S=w.date,E=w.utc,k=w.args;this.$u=E;var j=k[1];if(typeof j=="string"){var _=k[2]===!0,D=k[3]===!0,M=_||D,N=k[2];D&&(N=k[2]),l=this.$locale(),!_&&N&&(l=y.Ls[N]),this.$d=(function(P,F,z){try{if(["x","X"].indexOf(F)>-1)return new Date((F==="X"?1e3:1)*P);var B=g(F)(P),W=B.year,H=B.month,V=B.day,G=B.hours,X=B.minutes,K=B.seconds,ie=B.milliseconds,le=B.zone,ce=new Date,J=V||(W||H?1:ce.getDate()),he=W||ce.getFullYear(),ne=0;W&&!H||(ne=H>0?H-1:ce.getMonth());var Y=G||0,ae=X||0,je=K||0,me=ie||0;return le?new Date(Date.UTC(he,ne,J,Y,ae,je,me+60*le.offset*1e3)):z?new Date(Date.UTC(he,ne,J,Y,ae,je,me)):new Date(he,ne,J,Y,ae,je,me)}catch{return new Date("")}})(S,j,E),this.init(),N&&N!==!0&&(this.$L=this.locale(N).$L),M&&S!=this.format(j)&&(this.$d=new Date("")),l={}}else if(j instanceof Array)for(var O=j.length,R=1;R<=O;R+=1){k[1]=j[R-1];var L=y.apply(this,k);if(L.isValid()){this.$d=L.$d,this.$L=L.$L,this.init();break}R===O&&(this.$d=new Date(""))}else C.call(this,w)}}}))})(uh)),uh.exports}var c6=l6();const d6=dt(c6);var ph={exports:{}},u6=ph.exports,Qj;function p6(){return Qj||(Qj=1,(function(e,t){(function(n,r){e.exports=r()})(u6,(function(){var n={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};return function(r,s,i){var o=s.prototype,l=o.format;i.en.formats=n,o.format=function(c){c===void 0&&(c="YYYY-MM-DDTHH:mm:ssZ");var d=this.$locale().formats,u=(function(p,h){return p.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(f,g,x){var b=x&&x.toUpperCase();return g||h[x]||n[x]||h[b].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(y,v,C){return v||C.slice(1)}))}))})(c,d===void 0?{}:d);return l.call(this,u)}}}))})(ph)),ph.exports}var h6=p6();const Nm=dt(h6);var hh={exports:{}},f6=hh.exports,Jj;function m6(){return Jj||(Jj=1,(function(e,t){(function(n,r){e.exports=r()})(f6,(function(){return function(n,r,s){r.prototype.isBetween=function(i,o,l,c){var d=s(i),u=s(o),p=(c=c||"()")[0]==="(",h=c[1]===")";return(p?this.isAfter(d,l):!this.isBefore(d,l))&&(h?this.isBefore(u,l):!this.isAfter(u,l))||(p?this.isBefore(d,l):!this.isAfter(d,l))&&(h?this.isAfter(u,l):!this.isBefore(u,l))}}}))})(hh)),hh.exports}var g6=m6();const x6=dt(g6);Z.extend(d6);Z.extend(Nm);Z.extend(x6);const b6=bW(["Your locale has not been found.","Either the locale key is not a supported one. Locales supported by dayjs are available here: https://github.com/iamkun/dayjs/tree/dev/src/locale","Or you forget to import the locale from 'dayjs/locale/{localeUsed}'","fallback on English locale"]),y6={YY:"year",YYYY:{sectionType:"year",contentType:"digit",maxLength:4},M:{sectionType:"month",contentType:"digit",maxLength:2},MM:"month",MMM:{sectionType:"month",contentType:"letter"},MMMM:{sectionType:"month",contentType:"letter"},D:{sectionType:"day",contentType:"digit",maxLength:2},DD:"day",Do:{sectionType:"day",contentType:"digit-with-letter"},d:{sectionType:"weekDay",contentType:"digit",maxLength:2},dd:{sectionType:"weekDay",contentType:"letter"},ddd:{sectionType:"weekDay",contentType:"letter"},dddd:{sectionType:"weekDay",contentType:"letter"},A:"meridiem",a:"meridiem",H:{sectionType:"hours",contentType:"digit",maxLength:2},HH:"hours",h:{sectionType:"hours",contentType:"digit",maxLength:2},hh:"hours",m:{sectionType:"minutes",contentType:"digit",maxLength:2},mm:"minutes",s:{sectionType:"seconds",contentType:"digit",maxLength:2},ss:"seconds"},v6={year:"YYYY",month:"MMMM",monthShort:"MMM",dayOfMonth:"D",weekday:"dddd",weekdayShort:"dd",hours24h:"HH",hours12h:"hh",meridiem:"A",minutes:"mm",seconds:"ss",fullDate:"ll",fullDateWithWeekday:"dddd, LL",keyboardDate:"L",shortDate:"MMM D",normalDate:"D MMMM",normalDateWithWeekday:"ddd, MMM D",monthAndYear:"MMMM YYYY",monthAndDate:"MMMM D",fullTime:"LT",fullTime12h:"hh:mm A",fullTime24h:"HH:mm",fullDateTime:"lll",fullDateTime12h:"ll hh:mm A",fullDateTime24h:"ll HH:mm",keyboardDateTime:"L LT",keyboardDateTime12h:"L hh:mm A",keyboardDateTime24h:"L HH:mm"},Ng=["Missing UTC plugin","To be able to use UTC or timezones, you have to enable the `utc` plugin","Find more information on https://mui.com/x/react-date-pickers/timezone/#day-js-and-utc"].join(` 3`),Xj=["Missing timezone plugin","To be able to use timezones, you have to enable both the `utc` and the `timezone` plugin","Find more information on https://mui.com/x/react-date-pickers/timezone/#day-js-and-timezone"].join(` 4`),C6=(e,t)=>t?(...n)=>e(...n).locale(t):e;class Cu{constructor({locale:t,formats:n,instance:r}={}){var s;this.isMUIAdapter=!0,this.isTimezoneCompatible=!0,this.lib="dayjs",this.rawDayJsInstance=void 0,this.dayjs=void 0,this.locale=void 0,this.formats=void 0,this.escapedCharacters={start:"[",end:"]"},this.formatTokenMap=y6,this.setLocaleToValue=i=>{const o=this.getCurrentLocaleCode();return o===i.locale()?i:i.locale(o)},this.hasUTCPlugin=()=>typeof Z.utc<"u",this.hasTimezonePlugin=()=>typeof Z.tz<"u",this.isSame=(i,o,l)=>{const c=this.setTimezone(o,this.getTimezone(i));return i.format(l)===c.format(l)},this.cleanTimezone=i=>{switch(i){case"default":return;case"system":return Z.tz.guess();default:return i}},this.createSystemDate=i=>{if(this.rawDayJsInstance)return this.rawDayJsInstance(i);if(this.hasUTCPlugin()&&this.hasTimezonePlugin()){const o=Z.tz.guess();return o!=="UTC"?Z.tz(i,o):Z(i)}return Z(i)},this.createUTCDate=i=>{if(!this.hasUTCPlugin())throw new Error(Ng);return Z.utc(i)},this.createTZDate=(i,o)=>
4{if(!this.hasUTCPlugin())throw new Error(Ng);if(!this.hasTimezonePlugin())throw new Error(Xj);const l=i!==void 0&&!i.endsWith("Z");return Z(i).tz(this.cleanTimezone(o),l)},this.getLocaleFormats=()=>{const i=Z.Ls,o=this.locale||"en";let l=i[o];return l===void 0&&(b6(),l=i.en),l.formats},this.adjustOffset=i=>{if(!this.hasTimezonePlugin())return i;const o=this.getTimezone(i);if(o!=="UTC"){var l,c;const d=i.tz(this.cleanTimezone(o),!0);return((l=d.$offset)!=null?l:0)===((c=i.$offset)!=null?c:0)?i:d}return i},this.date=i=>i===null?null:this.dayjs(i),this.dateWithTimezone=(i,o)=>{if(i===null)return null;let l;return o==="UTC"?l=this.createUTCDate(i):o==="system"||o==="default"&&!this.hasTimezonePlugin()?l=this.createSystemDate(i):l=this.createTZDate(i,o),this.locale===void 0?l:l.locale(this.locale)},this.getTimezone=i=>{if(this.hasTimezonePlugin()){var o;const l=(o=i.$x)==null?void 0:o.$timezone;if(l)return l}return this.hasUTCPlugin()&&i.isUTC()?"UTC":"system"},this.setTimezone=(i,o)=>{if(this.getTimezone(i)===o)return i;if(o==="UTC"){if(!this.hasUTCPlugin())throw new Error(Ng);return i.utc()}if(o==="system")return i.local();if(!this.hasTimezonePlugin()){if(o==="default")return i;throw new Error(Xj)}return Z.tz(i,this.cleanTimezone(o))},this.toJsDate=i=>i.toDate(),this.parseISO=i=>this.dayjs(i),this.toISO=i=>i.toISOString(),this.parse=(i,o)=>i===""?null:this.dayjs(i,o,this.locale,!0),this.getCurrentLocaleCode=()=>this.locale||"en",this.is12HourCycleInCurrentLocale=()=>/A|a/.test(this.getLocaleFormats().LT||""),this.expandFormat=i=>{const o=this.getLocaleFormats(),l=c=>c.replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(d,u,p)=>u||p.slice(1));return i.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(c,d,u)=>{const p=u&&u.toUpperCase();return d||o[u]||l(o[p])})},this.getFormatHelperText=i=>this.expandFormat(i).replace(/a/gi,"(a|p)m").toLocaleLowerCase(),this.isNull=i=>i===null,this.isValid=i=>this.dayjs(i).isValid(),this.format=(i,o)=>this.formatByString(i,this.formats[o]),this.formatByString=(i,o)=>this.dayjs(i).format(o),this.formatNumber=i=>i,this.getDiff=(i,o,l)=>i.diff(o,l),this.isEqual=(i,o)=>i===null&&o===null?!0:this.dayjs(i).toDate().getTime()===this.dayjs(o).toDate().getTime(),this.isSameYear=(i,o)=>this.isSame(i,o,"YYYY"),this.isSameMonth=(i,o)=>this.isSame(i,o,"YYYY-MM"),this.isSameDay=(i,o)=>this.isSame(i,o,"YYYY-MM-DD"),this.isSameHour=(i,o)=>i.isSame(o,"hour"),this.isAfter=(i,o)=>i>o,this.isAfterYear=(i,o)=>this.hasUTCPlugin()?!this.isSameYear(i,o)&&i.utc()>o.utc():i.isAfter(o,"year"),this.isAfterDay=(i,o)=>this.hasUTCPlugin()?!this.isSameDay(i,o)&&i.utc()>o.utc():i.isAfter(o,"day"),this.isBefore=(i,o)=>i<o,this.isBeforeYear=(i,o)=>this.hasUTCPlugin()?!this.isSameYear(i,o)&&i.utc()<o.utc():i.isBefore(o,"year"),this.isBeforeDay=(i,o)=>this.hasUTCPlugin()?!this.isSameDay(i,o)&&i.utc()<o.utc():i.isBefore(o,"day"),this.isWithinRange=(i,[o,l])=>i>=o&&i<=l,this.startOfYear=i=>this.adjustOffset(i.startOf("year")),this.startOfMonth=i=>this.adjustOffset(i.startOf("month")),this.startOfWeek=i=>this.adjustOffset(i.startOf("week")),this.startOfDay=i=>this.adjustOffset(i.startOf("day")),this.endOfYear=i=>this.adjustOffset(i.endOf("year")),this.endOfMonth=i=>this.adjustOffset(i.endOf("month")),this.endOfWeek=i=>this.adjustOffset(i.endOf("week")),this.endOfDay=i=>this.adjustOffset(i.endOf("day")),this.addYears=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"year"):i.add(o,"year")),this.addMonths=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"month"):i.add(o,"month")),this.addWeeks=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"week"):i.add(o,"week")),this.addDays=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"day"):i.add(o,"day")),this.addHours=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"hour"):i.add(o,"hour")),this.addMinutes=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"minute"):i.add(o,"minute")),this.addSeconds=(i,o)=>this.adjustOffset(o<0?i.subtract(Math.abs(o),"second"):i.add(o,"second")),this.getYear=i=>i.year(),this.getMonth=i=>i.month(),this.getDate=i=>i.date(),this.getHours=i=>i.hour(),this.getMinutes=i=>
4i.minute(),this.getSeconds=i=>i.second(),this.getMilliseconds=i=>i.millisecond(),this.setYear=(i,o)=>this.adjustOffset(i.set("year",o)),this.setMonth=(i,o)=>this.adjustOffset(i.set("month",o)),this.setDate=(i,o)=>this.adjustOffset(i.set("date",o)),this.setHours=(i,o)=>this.adjustOffset(i.set("hour",o)),this.setMinutes=(i,o)=>this.adjustOffset(i.set("minute",o)),this.setSeconds=(i,o)=>this.adjustOffset(i.set("second",o)),this.setMilliseconds=(i,o)=>this.adjustOffset(i.set("millisecond",o)),this.getDaysInMonth=i=>i.daysInMonth(),this.getNextMonth=i=>this.addMonths(i,1),this.getPreviousMonth=i=>this.addMonths(i,-1),this.getMonthArray=i=>{const l=[i.startOf("year")];for(;l.length<12;){const c=l[l.length-1];l.push(this.addMonths(c,1))}return l},this.mergeDateAndTime=(i,o)=>i.hour(o.hour()).minute(o.minute()).second(o.second()),this.getWeekdays=()=>{const i=this.dayjs().startOf("week");return[0,1,2,3,4,5,6].map(o=>this.formatByString(this.addDays(i,o),"dd"))},this.getWeekArray=i=>{const o=this.setLocaleToValue(i),l=o.startOf("month").startOf("week"),c=o.endOf("month").endOf("week");let d=0,u=l;const p=[];for(;u<c;){const h=Math.floor(d/7);p[h]=p[h]||[],p[h].push(u),u=this.addDays(u,1),d+=1}return p},this.getWeekNumber=i=>i.week(),this.getYearRange=(i,o)=>{const l=i.startOf("year"),c=o.endOf("year"),d=[];let u=l;for(;u<c;)d.push(u),u=this.addYears(u,1);return d},this.getMeridiemText=i=>i==="am"?"AM":"PM",this.rawDayJsInstance=r,this.dayjs=C6((s=this.rawDayJsInstance)!=null?s:Z,t),this.locale=t,this.formats=Ln({},v6,n),Z.extend(a6)}}var fh={exports:{}},w6=fh.exports,Zj;function S6(){return Zj||(Zj=1,(function(e,t){(function(n,r){e.exports=r()})(w6,(function(){return{name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(n){var r=["th","st","nd","rd"],s=n%100;return"["+n+(r[(s-20)%10]||r[s]||r[0])+"]"}}}))})(fh)),fh.exports}S6();const Ui=(e,t)=>{switch(t){case"last30Days":return[e.subtract(29,"days"),e];case"last3Months":return[e.subtract(2,"months").startOf("month"),e];case"last6Months":return[e.subtract(5,"months").startOf("month"),e];case"last12Months":return[e.subtract(11,"months").startOf("month"),e];default:return[e.clone(),e]}},j6=({maxDate:e,minDate:t})=>{if(!e)return[];const n=[{label:"Last 30 Days",getValue:()=>Ui(e,"last30Days")},{label:"Last 3 Months",getValue:()=>Ui(e,"last3Months")},{label:"Last 6 Months",getValue:()=>Ui(e,"last6Months")},{label:"Last 12 Months",getValue:()=>Ui(e,"last12Months")}];return t?n.concat([{label:"Total Time Frame",getValue:()=>[t,e]}]):n};Z.extend(Nm);const ts=({allowManualInput:e=!1,fullWidth:t=!1,loading:n=!1,locale:r="en",maxDate:s,minDate:i,onClose:o=()=>{},onOpen:l=()=>{},shortcutItems:c,setValue:d,value:u=[null,null],...p})=>{const h=s??Z(),f=i??Ui(h,"last12Months")[0],g=c??j6({maxDate:h,minDate:f});return a.jsx(Nt,{isLoading:n,children:a.jsx(xu,{adapterLocale:r,dateAdapter:Cu,localeText:{fieldDayPlaceholder:x=>x.format,fieldMonthPlaceholder:x=>x.format},children:a.jsx(yW,{format:"ll",onChange:d,value:u,maxDate:h,minDate:f||h?.subtract(1,"year"),slots:{field:vW},onClose:o,onOpen:l,slotProps:{field:{readOnly:!e,shouldRespectLeadingZeros:!0},textField:{placeholder:"Start Date - End Date",InputProps:{startAdornment:a.jsx(au,{size:18}),endAdornment:a.jsx(vs,{size:18})},sx:{".MuiInputBase-input":{py:1,height:"auto",pl:1},".lucide":{color:"secondary.main"},width:t?"100%":260,minWidth:t?"100%":260}},shortcuts:{items:g,sx:{mt:2,display:"flex",flexDirection:"column",rowGap:1,".MuiChip-label":{fontSize:14,fontWeight:400}}}},...p})})})};var Jl={},ek;function k6(){if(ek)return Jl;ek=1;var e=Pt();Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.default=void 0;var t=e(Lt()),n=Ot();return Jl.default=(0,t.default)([(0,n.jsx)("path",{d:"M21 19.1H3V5h18zM21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2"},"0"),(0,n.jsx)("path",{d:"M14.59 8 12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41z"},"1")],"CancelPresentation"),Jl}var E6=k6();const IM=dt(E6),DM=({message:e="",...t})=>a.jsxs($,{alignItems:"center",direction:"column",sx:{minHeight:"150px"},justifyContent:"center",gap:1.5,...t,children:[a.jsx(IM,{sx:{width:40,height:40},color:"disabled"}),a.jsx(I,{variant:"subtitle1",color:"text.disabled",children:e})]}),gs=({children:e,isDataEmpty:t,isError:n=!1})=>t?a.jsx(DM,{message:n?"There was an error while fetching the requested data, please try again after some time.":"Not available"}):e,_6=({resetErrorBoundary:e})=>{const{pathname:t}=es(),[n,r]=m.useState("");m.useEffect(()=>{!n&&t?r(t):t!==n&&e&&e()},[n,t,e,r]);const s=()=>{window.location.reload()};return a.jsxs(T,{sx:{maxWidth:600,px:4,py:2,display:"flex",flexDirection:"column",gap:3},children:[a.jsx(I,{sx:{alignSelf:"center"},children:"Something Went Wrong"}),a.jsx(re,{onClick:s,variant:"contained",children:"Reload Page"})]})};rt(T)(()=>({animationName:`${mm` 5 0% { transform: rotate(0deg) } 6 15% { transform: rotate(24deg) } 7 23% { transform: rotate(-8deg) } 8 32% { transform: rotate(14deg) } 9 40% { transform: rotate(-4deg) } 10 50% { transform: rotate(10deg) } 11 60% { transform: rotate(0deg) } 12 100% { transform: rotate(0deg) } 13 `}`,animationDuration:"2.5s",animationIterationCount:2,transformOrigin:"70% 70%",display:"inline-block",fontSize:30}));const Bb=rt(tt)({minHeight:40,"& .MuiSelect-select":{paddingTop:"6px",paddingBottom:"6px"},"& .MuiSelect-icon":{width:"16px",height:"16px"}});Bb.defaultProps={...Bb.defaultProps,IconComponent:vs,size:"small"};const T6={noOptions:"Not Available"},Ar=({disabled:e=!1,isLoading:t=!1,menuItemStartIcon:n,options:r,customOption:s,customOptionPlacement:i="last",uncontrolled:o=!1,value:l="",...c})=>{const d=!!Object.keys(r).length,u=!!s,p=m.useMemo(()=>d?r:T6,[d,r]),h=!u&&Object.keys(p).length===1,f=m.useMemo(()=>Object.entries(p).map(([x,b])=>a.jsx(Se,{value:x,children:a.jsxs($,{alignItems:"center",direction:"row",gap:1,children:[d&&n?a.jsx(T,{sx:{height:"16px",mb:"2px",width:"16px"},children:n}):null,a.jsx(I,{variant:"inherit",noWrap:!0,children:b})]})},x)),[d,n,p]),g=o?{defaultValue:Object.keys(p)[0]}:{value:d?l:"noOptions"};return a.jsx(Nt,{isLoading:t,children:a.jsxs(Bb,{disabled:e||h,...c,...g,children:[u&&i==="first"?s:null,f,u&&i==="last"?s:null]})})},da=({children:e,dataFirstDate:t,dataLastDate:n,disableDatePicker:r=!1,disableKpis:s=!1,disableTargetAudience:i=!1,handleDatePickerOnChange:o=()=>{},handleDatePickerOnClose:l=()=>{}
13,handleDatePickerOnOpen:c=()=>{},handleKpiOnChange:d=()=>{},handleTargetAudienceOnChange:u=()=>{},hideDatePicker:p=!1,hideKpis:h=!1,hideTargetAudience:f=!1,isDataLoading:g=!1,isMetaLoading:x=!1,kpiListOptions:b=[],kpiSxProps:y,selectedDateRange:v,selectedKpi:C,selectedTargetAudience:w,targetAudienceListOptions:S=[],targetAudienceSxProps:E,testId:k})=>{const j=m.useMemo(()=>S.reduce((D,{name:M,niceId:N})=>({...D,[N]:M}),{}),[S]),_=m.useMemo(()=>b.reduce((D,{name:M,niceId:N})=>({...D,[N]:M}),{}),[b]);return a.jsxs($,{"data-testid":k,direction:{md:"row",xs:"column"},spacing:2,justifyContent:"space-between",children:[a.jsxs($,{direction:{xl:"row",xs:"column"},spacing:2,children:[!f&&a.jsx(Ar,{inputProps:k?{"data-testid":`${k}:target-audience:select`}:void 0,sx:{width:250,...E},disabled:g||i,isLoading:x,menuItemStartIcon:a.jsx(ym,{size:16}),onChange:({target:{value:D}})=>{u(D)},options:j,value:w}),!h&&a.jsx(Ar,{inputProps:k?{"data-testid":`${k}:kpi:select`}:void 0,sx:{width:230,...y},disabled:g||s,isLoading:x,menuItemStartIcon:a.jsx(yB,{size:16}),onChange:({target:{value:D}})=>{d(D)},options:_,value:C})]}),e,!p&&a.jsx(ts,{disabled:g||r,loading:x,value:v,setValue:D=>{o(D)},maxDate:n||Z(),minDate:t,onClose:l,onOpen:c})]})},AM=({color:e,icon:t,variant:n,value:r})=>a.jsxs(gi,{sx:{width:"170px",height:"170px",display:"flex",justifyContent:"center",alignItems:"center",position:"relative",borderRadius:"50%"},children:[a.jsx(Ze,{color:e,size:170,thickness:1,variant:n,value:r}),t&&a.jsx(gi,{sx:{width:"140px",height:"140px",display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"background.brand.subtlest.hovered",borderRadius:"50%",position:"absolute",color:"primary.main"},children:t})]}),zh=40,I6=31,D6={brand:"icon.brand.main",error:"icon.error",success:"icon.success"},Ji=({ariaLabel:e,color:t,disabled:n=!1,icon:r,iconSize:s=I6,onClick:i,tooltip:o})=>a.jsx(be,{placement:"top",title:o,children:a.jsx(T,{component:"span",sx:{display:"inline-flex"},children:a.jsx(Ie,{"aria-label":e,disabled:n,onClick:i,size:"small",sx:{"&.Mui-disabled":{color:"icon.disabled"},"&:hover":{bgcolor:"action.hover"},borderRadius:2,color:D6[t],height:zh,width:zh},children:a.jsx(r,{sx:{fontSize:s}})})})}),MM=()=>a.jsx(T,{"aria-hidden":!0,sx:{height:zh,width:zh}}),Ub=({open:e,title:t,message:n,resourceName:r,confirmationText:s="DELETE",confirmButtonText:i="Confirm",confirmButtonColor:o="error",cancelButtonText:l="Cancel",isProcessing:c,onClose:d,onConfirm:u,errorMessage:p="",sxProps:h={},maxWidth:f="sm"})=>{const[g,x]=m.useState(""),b=()=>{d(),x("")},y=()=>{u(),x("")},v=g!==s;return a.jsxs(yt,{open:e,fullWidth:!0,maxWidth:f,children:[a.jsx(vt,{children:t}),a.jsxs(Ct,{sx:{display:"flex",gap:4,flexDirection:"column",...h},children:[typeof n=="string"?a.jsxs(I,{children:[n,r&&a.jsxs(a.Fragment,{children:[" ",a.jsx(I,{component:"span",sx:{fontWeight:"bold",color:"primary.main"},children:r})]})]}):n,a.jsxs(T,{children:[a.jsxs(I,{children:["Type ",a.jsx("strong",{children:s})," to confirm"]}),a.jsx(De,{disabled:c,sx:{width:"100%",mt:1},value:g,onChange:C=>x(C.target.value),label:"Enter confirmation text",autoFocus:!0}),a.jsx(Yt,{in:!!p,children:a.jsx(vn,{severity:"error",sx:{mb:2,bgcolor:"background.error.default",color:"text.primary","& .MuiAlert-icon":{color:"text.primary"}},children:p})})]}),a.jsxs(T,{sx:{display:"flex",gap:1,justifyContent:"flex-end"},children:[a.jsx(re,{disabled:c,color:"secondary",onClick:b,children:l}),a.jsx(Dt,{loading:c,color:o,variant:"contained",disabled:v,onClick:y,children:i})]})]})]})},ho=({loading:e,testId:t})=>a.jsx($,{"data-testid":t,height:"16px",position:"fixed",sx:{top:0,left:0,right:0},children:e&&a.jsx(lo,{sx:{borderRadius:"unset",height:"10px"}})});rt(T)(({theme:e})=>{const{icon:t}=e.palette;return{width:8,height:8,margin:"3px 6px 3px 16px",borderRadius:"50%",opacity:1,animation:`${mm` 14 0% {box-shadow: 12px 0 ${t.brand.light}, -12px 0 ${t.brand.main}; background: ${t.brand.bold} } 15 33% {box-shadow: 12px 0 ${t.brand.bold}, -12px 0 ${t.brand.light}; background: ${t.brand.main}} 16 66% {box-shadow: 12px 0 ${t.brand.main}, -12px 0 ${t.brand.bold}; background: ${t.brand.light}} 17 100%{box-shadow: 12px 0 ${t.brand.light}, -12px 0 ${t.brand.main}; background: ${t.brand.bold} } 18`} 2s infinite linear`}});const Cs=({numberOfRows:e=10,rowHeight:t=60,...n})=>
18a.jsx($,{sx:{gap:1},children:Array(e).fill(null).map((r,s)=>a.jsx(fe,{height:t,variant:"rounded",...n},s))}),RM=m.createContext(null),Vr=()=>m.useContext(RM),A6="https://www.marketingevolution.com/marketing-evolution-privacy-policy",M6="https://support.marketingevolution.com",R6=()=>{const{collapsed:e,supportLink:t}=Vr();return a.jsx(T,{sx:{alignItems:"center",borderColor:"border.default",borderTop:"1px solid",display:"flex",flexDirection:"column",gap:.5,mt:"auto",pb:.5,pt:1},children:a.jsx(vB,{collapsed:e,href:t||M6})})},tk=({label:e})=>{const{collapsed:t}=Vr();return t?null:a.jsx(I,{sx:{color:"text.secondary",fontSize:11,fontWeight:600,letterSpacing:"0.08em",px:2,py:1,textTransform:"uppercase"},children:e})},N6={borderRadius:1,flexGrow:0,position:"relative"},O6={bgcolor:"primary.main",borderRadius:1,height:"100%",left:0,position:"absolute",top:0,width:4},Vb=({active:e,expanded:t,featurePath:n,href:r,Icon:s,name:i,onClick:o,path:l,Slot:c})=>{const{collapsed:d,currentPath:u,featuresConfig:p,onClickMenuItem:h}=Vr(),f=e??(!!l&&l===u),g=`nav:${i.toLowerCase().replace(/\s+/g,"-")}`,x=t??!1,b=r?{component:"a",href:r,target:"_blank",rel:"noopener noreferrer"}:{},y=()=>{l&&h(l),o&&o()};if(n&&!p[n])return null;const v=a.jsxs(Fv,{...b,"data-testid":g,onClick:y,sx:C=>({...N6,bgcolor:x?C.palette.mode==="dark"?"rgba(86, 0, 216, 0.15)":"neutral.100":"transparent","&:hover":{bgcolor:x?C.palette.mode==="dark"?"rgba(86, 0, 216, 0.2)":"neutral.200":void 0},"&.Mui-selected":{bgcolor:x?C.palette.mode==="dark"?"rgba(86, 0, 216, 0.15)":"neutral.100":"transparent"},"&.Mui-focusVisible":{bgcolor:x?C.palette.mode==="dark"?"rgba(86, 0, 216, 0.15)":"neutral.100":"transparent"},justifyContent:d?"center":"flex-start",minWidth:d?48:"auto",px:d?1.5:2}),children:[a.jsx(kD,{sx:{color:f?"icon.brand.main":"inherit",minWidth:d?"auto":20},children:a.jsx(s,{size:18})}),!d&&a.jsx(Kt,{primary:i,primaryTypographyProps:{color:f?"primary.main":"text.primary",fontSize:"12px",fontWeight:f||x?600:400},sx:{my:0}}),!d&&c,f&&a.jsx(T,{sx:O6})]});return d?a.jsx(be,{title:i,placement:"right",arrow:!0,children:v}):v},P6=({featurePath:e,name:t,onClick:n,path:r})=>{const{currentPath:s,featuresConfig:i,onClickMenuItem:o}=Vr(),l=!!r&&s.startsWith(r),c=`nav:${t.toLowerCase().replace(/\s+/g,"-")}`,d=()=>{r&&o(r),n&&n()};return e&&!i[e]?null:a.jsx(Fv,{"data-testid":c,onClick:d,sx:{borderRadius:1,pl:7,py:1},children:a.jsx(Kt,{primary:t,primaryTypographyProps:{color:l?"primary.main":"text.secondary",fontSize:12,fontWeight:500}})})},Il=({active:e,childrenConfig:t,Icon:n,name:r,onClick:s,open:i})=>{const{palette:o}=Re(),{collapsed:l,currentPath:c,featuresConfig:d}=Vr(),u=i?yl:vs,p=String(o.text.disabled),h=`nav:section:${r.toLowerCase().replace(/\s+/g,"-")}`;if(!t.some(({featurePath:g})=>!!d[g]))return null;const f=e??t.some(({path:g})=>g&&g===c);if(l){const g=t.find(({featurePath:x,path:b})=>b&&d[x]);return a.jsx(T,{"data-testid":h,children:a.jsx(Vb,{active:f,Icon:n,name:r,path:g?.path})})}return a.jsxs(T,{"data-testid":h,children:[a.jsx(Vb,{active:f,expanded:i,Icon:n,name:r,onClick:s,Slot:a.jsx(u,{size:20,color:p})}),a.jsx(Yt,{in:i,timeout:"auto",unmountOnExit:!0,children:a.jsx($v,{sx:{pb:0},children:t.map(({featurePath:g,name:x,path:b})=>b?a.jsx(P6,{featurePath:g,name:x,path:b},b):null)})})]})},L6=[{featurePath:"DataPipeline.DataDictionary",name:"Data Dictionary",path:"/data-pipeline/data-dictionary"},{featurePath:"DataPipeline.DataValidation",name:"Data Validation",path:"/data-pipeline/data-validation"},{featurePath:"DataPipeline.Processing",name:"Processing",path:"/data-pipeline/processing"},{featurePath:"DataPipeline.MachineLearning",name:"Machine Learning",path:"/data-pipeline/machine-learning"},{featurePath:"DataPipeline.DisplaySettings",name:"Display Settings",path:"/data-pipeline/display-settings"}],F6=()=>{const{buildHandleClickSection:e,state:t}=Vr(),{focusedSection:n}=t;return a.jsx(Il,{childrenConfig:L6,Icon:CB,name:"Data Pipeline",onClick:e("DataPipeline"),open:n==="DataPipeline"})},$6=[{featurePath:"DataSources.FileUpload",name:"File Uploads",path:"/data-sources/file-upload"},{featurePath:"DataSources.Connections",name:"Connections",path:"/data-sources/connections"},{featurePath:"DataSources.QueryStudio",name:"Query Studio",path:"/data-sources/query-studio"},{featurePath:"DataSources.Configurations",name:"Configurations",path:"/data-sources/configurations"},{featurePath:"DataSources.NameCleaning",name:"Name Cleaning",path:"/data-sources/name-cleaning"}],z6=()=>{const{buildHandleClickSection:e,state:t}=Vr(),{focusedSection:n}=t;return a.jsx(Il,{childrenConfig:$6,Icon:PD,name:"Data Sources",onClick:e("DataSources"),open:n==="DataSources"})},B6=[{featurePath:"Exports.Attribution",name:"Attribution",path:"/exports/attribution"},{featurePath:"Exports.ExportConfiguration",name:"Export Configuration",path:"/exports/export-configuration"}],U6=()=>{const{buildHandleClickSection:e,state:t}=Vr(),{focusedSection:n}=t;return a.jsx(Il,{childrenConfig:B6,Icon:wB,name:"Exports",onClick:e("Exports"),open:n==="Exports"})},V6=()=>{const{currentPath:e}=Vr(),t=e==="/overview";return a.jsx(Vb,{active:t,featurePath:"Overview",Icon:LD,name:"Overview",path:"/overview"})};var Xl={},nk;function W6(){if(nk)return Xl;nk=1;var e=Pt();
18Object.defineProperty(Xl,"__esModule",{value:!0}),Xl.default=void 0;var t=e(Lt()),n=Ot();return Xl.default=(0,t.default)((0,n.jsx)("path",{d:"M7 11H1v2h6zm2.17-3.24L7.05 5.64 5.64 7.05l2.12 2.12zM13 1h-2v6h2zm5.36 6.05-1.41-1.41-2.12 2.12 1.41 1.41zM17 11v2h6v-2zm-5-2c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3m2.83 7.24 2.12 2.12 1.41-1.41-2.12-2.12zm-9.19.71 1.41 1.41 2.12-2.12-1.41-1.41zM11 23h2v-6h-2z"}),"Flare"),Xl}var H6=W6();const q6=dt(H6),G6=({size:e})=>a.jsx(q6,{sx:{fontSize:e}}),NM=G6,OM=SB,Y6=[{featurePath:"Planning",name:"My Plans",path:"/planning/my-plans"},{featurePath:"Planning.NewPlan",name:"New Plan",path:"/planning/new-plan"}],K6=()=>{const{buildHandleClickSection:e,state:t}=Vr(),{focusedSection:n}=t;return a.jsx(Il,{childrenConfig:Y6,Icon:OM,name:"Planning",onClick:e("Planning"),open:n==="Planning"})},Q6=[{featurePath:"ReportsInsights.MediaReporting",name:"Media Reporting",path:"/reports-insights/media-reporting"},{featurePath:"ReportsInsights.ConversionSummary",name:"Conversion Summary",path:"/reports-insights/conversion-summary"},{featurePath:"ReportsInsights.ConversionLookback",name:"Conversion Lookback",path:"/reports-insights/conversion-lookback"},{featurePath:"ReportsInsights.Journey",name:"Journey",path:"/reports-insights/journey"},{featurePath:"ReportsInsights.Geography",name:"Geo",path:"/reports-insights/geography"},{featurePath:"ReportsInsights.ExternalFactors",name:"External Factors",path:"/reports-insights/external-factors"},{featurePath:"ReportsInsights.Audiences",name:"Audiences",path:"/reports-insights/audiences"}],J6=()=>{const{buildHandleClickSection:e,state:t}=Vr(),{focusedSection:n}=t;return a.jsx(Il,{childrenConfig:Q6,Icon:NM,name:"Reports & Insights",onClick:e("ReportsInsights"),open:n==="ReportsInsights"})},X6=[{featurePath:"Visualize.Dashboards",name:"Dashboards",path:"/visualize/dashboards"},{featurePath:"Visualize.MediaDashboard",name:"Media Dashboard",path:"/visualize/media-dashboard"}],Z6=()=>{const{buildHandleClickSection:e,state:t}=Vr(),{focusedSection:n}=t;return a.jsx(Il,{childrenConfig:X6,Icon:FD,name:"Visualize",onClick:e("Visualize"),open:n==="Visualize"})},eG=()=>{const{collapsed:e}=Vr();return a.jsxs($v,{sx:{display:"flex",flexDirection:"column",flexGrow:1,height:"100%",p:0},children:[a.jsxs($,{flexGrow:1,rowGap:.5,sx:{overflow:e?"hidden":"auto"},children:[a.jsx(V6,{}),a.jsx(tk,{label:"Strategy"}),a.jsx(Z6,{}),a.jsx(J6,{}),a.jsx(K6,{}),a.jsx(U6,{}),a.jsx(tk,{label:"Platform"}),a.jsx(z6,{}),a.jsx(F6,{})]}),a.jsx(R6,{})]})},tG={focusedSection:null},nG=(e,t)=>t.type==="focusedSection"?{...e,focusedSection:t.value}:e,rG=({collapsed:e=!1,currentPath:t,featuresConfig:n,onClickMenuItem:r,supp
18ortLink:s})=>{const[i,o]=m.useReducer(nG,tG),{focusedSection:l}=i,c=m.useCallback(p=>()=>{e||o({type:"focusedSection",value:l===p?null:p})},[e,o,l]),d=m.useCallback(()=>{o({type:"focusedSection",value:null})},[o]),u=m.useMemo(()=>({buildHandleClickSection:c,collapsed:e,currentPath:t,dispatch:o,featuresConfig:n,onClickMenuItem:r,resetFocus:d,state:i,supportLink:s}),[c,e,t,o,n,r,d,i,s]);return a.jsx(RM.Provider,{value:u,children:a.jsx(eG,{})})},Dl=({sx:e})=>{const{engagementCurrency:t}=pe(),n={alignSelf:"center",color:"text.disabled",...e};switch(t){case"EUR":return a.jsx(kB,{sx:n});case"GBP":return a.jsx(jB,{sx:n});default:return a.jsx($D,{sx:n})}},ft=({fractionDigits:e=2,isCurrency:t=!1,isPercent:n=!1,locale:r="en",noTooltip:s=!1,StackProps:i,TypographyProps:o,value:l})=>{const c=Number.isNaN(Number(l)),d=c?"":new Intl.NumberFormat(r,{maximumFractionDigits:e,minimumFractionDigits:e}).format(n?100*Number(l):Number(l)),u=s?"":new Intl.NumberFormat(r).format(Number(l));return a.jsx(be,{title:u,children:a.jsxs($,{direction:"row",...i,children:[t&&!c&&a.jsx(Dl,{sx:{fontSize:22}}),a.jsx(I,{component:"span",...o,children:d}),n&&!c&&a.jsx(EB,{sx:{alignSelf:"center",color:"text.disabled",fontSize:22}})]})})},Xt=({subTitle:e,testId:t,title:n})=>a.jsxs($,{"data-testid":t,gap:1,children:[a.jsx(I,{variant:"h5",children:n}),!!e&&a.jsx(I,{variant:"body2",children:e})]}),Zt=({children:e,title:t,titleSx:n,endIcon:r})=>a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[a.jsx(I,{sx:{fontSize:"18px",fontWeight:600,lineHeight:"22px",...n},children:t}),r]}),a.jsx(T,{children:e})]})}),RC=rt(Qe)(({theme:e})=>{const{neutral:t}=e.palette;return{".MuiFormLabel-root":{letterSpacing:"0.15px",lineHeight:"24px",transitionProperty:"color, transform, max-width, font-size, line-height",transform:"translate(12px, 12px)","&.Mui-focused":{fontSize:11,lineHeight:"12px"}},".MuiInputBase-root":{height:48,".MuiSelect-select":{height:24,letterSpacing:"0.15px",padding:"19px 11px 3px 11px"},"> fieldset":{borderColor:t[300]}},".MuiInputLabel-root":{"&.MuiInputLabel-shrink":{"&.MuiInputLabel-outlined":{transform:"translate(12px, 6px)",fontSize:11,lineHeight:"12px"}}}}}),Wb=rt(Se)(({theme:e})=>{const{background:t,primary:n,text:r}=e.palette;return{height:48,padding:"12px 16px 12px 16px",":hover":{backgroundColor:t.secondary.hovered},"&.Mui-selected":{backgroundColor:t.paper,":hover":{backgroundColor:t.secondary.hovered}},".MuiCheckbox-root":{color:r.disabled,"&.Mui-checked":{color:n.main}},".MuiListItemText-root":{paddingLeft:"5px",color:r.secondary,".MuiListItemText-primary":{lineHeight:"24px",fontWeight:500}}}});Wb.defaultProps={...Wb.defaultProps,disableRipple:!0};var ap={},rk;function sG(){if(rk)return ap;rk=1,Object.defineProperty(ap,"__esModule",{value:!0});var e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(b){return typeof b}:function(b){return b&&typeof Symbol=="function"&&b.constructor===Symbol&&b!==Symbol.prototype?"symbol":typeof b},t=Object.assign||function(b){for(var y=1;y<arguments.length;y++){var v,C=arguments[y];for(v in C)Object.prototype.hasOwnProperty.call(C,v)&&(b[v]=C[v])}return b},n=(function(){function b(y,v){for(var C=0;C<v.length;C++){var w=v[C];w.enumerable=w.enumerable||!1,w.configurable=!0,"value"in w&&(w.writable=!0),Object.defineProperty(y,w.key,w)}}return function(y,v,C){return v&&b(y.prototype,v),C&&b(y,C),y}})(),r=CW(),s=d(r),i=SD(),o=d(i),l=Gz(),c=d(l);function d(b){return b&&b.__esModule?b:{default:b}}function u(b,y,v){return y in b?Object.defineProperty(b,y,{value:v,enumerable:!0,configurable:!0,writable:!0}):b[y]=v,b}function p(b,y){var v,C={};for(v in b)0<=y.indexOf(v)||Object.prototype.hasOwnProperty.call(b,v)&&(C[v]=b[v]);return C}function h(b,y){if(!(b instanceof y))throw new TypeError("Cannot call a class as a function")}function f(b,y){if(b)return!y||typeof y!="object"&&typeof y!="function"?b:y;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}function g(b,y){if(typeof y!="function"&&y!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof y);b.prototype=Object.create(y&&y.prototype,{constructor:{value:b,enumerable:!1,writable:!0,configurable:!0}}),y&&(Object.setPrototypeOf?Object.setPrototypeOf(b,y):b.__proto__=y)}window.ApexCharts=s.default;var x=(function(){function b(y){h(this,b);var v=f(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,y));return o.default.createRef?v.chartRef=o.default.createRef():v.setRef=function(C){return v.chartRef=C},v.chart=null,v}return g(b,i.Component),n(b,[{key:"render",value:function(){var y=p(this.props,[]);return o.default.createElement("div",t({ref:o.default.createRef?this.chartRef:this.setRef},y))}},{key:"componentDidMount",value:function(){var y=o.default.createRef?this.chartRef.current:this.chartRef;this.chart=new s.default(y,this.getConfig()),this.chart.render()}},{key:"getConfig",value:function(){var S=this.props,y=S.type,v=S.height,C=S.width,w=S.series,S=S.options;return this.extend(S,{chart:{type:y,height:v,width:C},series:w})}},{key:"isObject",value:function(y){return y&&(y===void 0?"undefined":e(y))==="object"&&!Array.isArray(y)&&y!=null}},{key:"extend",value:function(y,v){var C=this,w=(typeof Object.assign!="function"&&(Object.assign=function(S){if(S==null)throw new TypeError("Cannot convert undefined or null to object");for(var E=Object(S),k=1;k<arguments.length;k++){var j=arguments[k];if(j!=null)for(var _ in j)j.hasOwnProperty(_)&&(E[_]=j[_])}return E}),Object.assign({},y));return this.isObject(y)&&this.isObject(v)&&Object.keys(v).forEach(function(S){C.isObject(v[S])&&S in y?w[S]=C.extend(y[S],v[S]):Object.assign(w,u({},S,v[S]))}),w}},{key:"componentDidUpdate",value:function(y){if(!this.chart)return null;var w=this.props,k=w.options,v=w.series,C=w.height,w=w.width,S=JSON.stringify(y.options),E=JSON.stringify(y.series),k=JSON.stringify(k),j=JSON.stringify(v);S===k&&E===j&&C===y.height&&w===y.width||(E!==j&&S===k&&C===y.height&&w===y.width?this.chart.updateSeries(v):this.chart.updateOptions(this.getConfig()))}},{key:"componentWillUnmount",value:function(){this.chart&&typeof this.chart.destroy=="function"&&this.chart.destroy()}}]),b})();return(ap.default=x).propTypes={type:c.default.string.isRequired,width:c.default.oneOfType([c.default.string,c.default.number]),height:c.default.oneOfType([c.default.string,c.default.number]),series:c.default.array.isRequired,options:c.default.object.isRequired},x.defaultProps={type:"line",width:"100%",height:"auto"},ap}var iG=sG();const ua=dt(iG),aG=["33%","55%","80%","65%","55%","43%"],oG=()=>a.jsxs(T,{height:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:30,width:"50%"}),a.jsx($,{sx:{width:"100%",pl:"40px",pb:"40px",height:"250px"},direction:"row",spacing:2,alignItems:"flex-end",children:aG.map((e,t)=>a.jsx(fe,{variant:"rounded",animation:"pulse",height:e,sx:{flex:1}},`skeleton-item-${t}`))})]}),lG=rt(ua)(({theme:e})=>({".apexcharts-menu-icon svg":{fill:"none !important"},".apexcharts-menu-icon svg path":{stroke:`${e.palette.icon.default} !important`},".apexcharts-menu-icon":{transform:"none"},".apexcharts-svg":{overflow:"visible"},".apexcharts-menu":{backgroundColor:`${e.palette.background.paper} !important`,border:`1px solid ${e.palette.border.default} !important`},".apexcharts-menu-item":{color:`${e.palette.text.primary} !important`},".apexcharts-menu-item:hover":{backgroundColor:`${e.palette.background.secondary.hovered} !important`},".apexcharts-tooltip":{backgroundColor:`${e.palette.background.paper} !important`,border:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`},".apexcharts-tooltip-title":{backgroundColor:`${e.palette.surface.tertiary} !important`,borderBottom:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`}})),Og=({isDataEmpty:e,loading:t,options:n,series:r,subtext:s,title:i,titleValue:o})=>a.jsx(Ve,{sx:{flex:1},children:a.jsx(Ue,{sx:{height:"100%"},children:t?a.jsx(oG,{}):a.jsxs($,{direction:"column",gap:1.5,flexGrow:"1",flexBasis:"0",sx:{overflowX:"auto",overflowY:"hidden"}
18,children:[typeof o=="string"?a.jsx(I,{variant:"h5",marginLeft:2,children:o}):o||a.jsx(I,{variant:"h5",color:"text.disabled",children:"n/a"}),a.jsx(I,{marginLeft:2,children:i}),a.jsx(gs,{isDataEmpty:e,children:a.jsx(lG,{options:n,series:r,width:"95%",sx:{minWidth:"250px"},type:"bar"})}),!!s&&a.jsx(I,{variant:"caption",marginLeft:2,children:s})]})})}),cG=({authorized:e,...t})=>a.jsx(ar,{authorized:e,children:a.jsx(_n,{...t})}),fo=({children:e,defaultValue:t,onChange:n=()=>{},renderOff:r=()=>null,tabs:s,testId:i="tabs",value:o,variant:l="standard"})=>{const c=_l(),d=m.useMemo(()=>s.filter(({authorized:g})=>EM({authorized:g,config:c})),[c,s]),u=!!o,[p,h]=m.useState((t||d?.[0]?.value)??"-1"),f=(g,x)=>{h(x),n(x)};return d.length?a.jsx(T,{sx:{width:"100%"},children:a.jsxs(co,{value:u?o:p,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default"},children:a.jsx(uo,{onChange:f,variant:l,children:d.map(g=>{const x=g.value.toLowerCase().replace(/\s+/g,"-");return a.jsx(cG,{...g,"data-testid":`${i}:${x}`},g.value)})})}),e]})}):r()};var wu=e=>e.type==="checkbox",Uo=e=>e instanceof Date,vr=e=>e==null;const PM=e=>typeof e=="object";var Un=e=>!vr(e)&&!Array.isArray(e)&&PM(e)&&!Uo(e),LM=e=>Un(e)&&e.target?wu(e.target)?e.target.checked:e.target.value:e,dG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,FM=(e,t)=>e.has(dG(t)),uG=e=>{const t=e.constructor&&e.constructor.prototype;return Un(t)&&t.hasOwnProperty("isPrototypeOf")},NC=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Wn(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(NC&&(e instanceof Blob||e instanceof FileList))&&(n||Un(e)))if(t=n?[]:{},!n&&!uG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=Wn(e[r]));else return e;return t}var Su=e=>Array.isArray(e)?e.filter(Boolean):[],Gt=e=>e===void 0,_e=(e,t,n)=>{if(!t||!Un(e))return n;const r=Su(t.split(/[,[\].]+?/)).reduce((s,i)=>vr(s)?s:s[i],e);return Gt(r)||r===e?Gt(e[t])?n:e[t]:r},Kr=e=>typeof e=="boolean",OC=e=>/^\w*$/.test(e),$M=e=>Su(e.replace(/["|']|\]/g,"").split(/\.|\[/)),kt=(e,t,n)=>{let r=-1;const s=OC(t)?[t]:$M(t),i=s.length,o=i-1;for(;++r<i;){const l=s[r];let c=n;if(r!==o){const d=e[l];c=Un(d)||Array.isArray(d)?d:isNaN(+s[r+1])?{}:[]}if(l==="__proto__")return;e[l]=c,e=e[l]}return e};const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},Jr={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ri={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},zM=Ne.createContext(null),on=()=>Ne.useContext(zM),Js=e=>{const{children:t,...n}=e;return Ne.createElement(zM.Provider,{value:n},t)};var BM=(e,t,n,r=!0)=>{const s={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(s,i,{get:()=>{const o=i;return t._proxyFormState[o]!==Jr.all&&(t._proxyFormState[o]=!r||Jr.all),n&&(n[o]=!0),e[o]}});return s},br=e=>Un(e)&&!Object.keys(e).length,UM=(e,t,n,r)=>{n(e);const{name:s,...i}=e;return br(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(o=>t[o]===(!r||Jr.all))},Ir=e=>Array.isArray(e)?e:[e],VM=(e,t,n)=>!e||!t||e===t||Ir(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Om(e){const t=Ne.useRef(e);t.current=e,Ne.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function pG(e){const t=on(),{control:n=t.control,disabled:r,name:s,exact:i}=e||{},[o,l]=Ne.useState(n._formState),c=Ne.useRef(!0),d=Ne.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),u=Ne.useRef(s);return u.current=s,Om({disabled:r,next:p=>c.current&&VM(u.current,p.name,i)&&UM(p,d.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Ne.useEffect(()=>(c.current=!0,d.current.isValid&&n._updateValid(!0),()=>{c.current=!1}),[n]),BM(o,n,d.current,!1)}var zs=e=>typeof e=="string",WM=(e,t,n,r,s)=>zs(e)?(r&&t.watch.add(e),_e(n,e,s)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),_e(n,i))):(r&&(t.watchAll=!0),n);function Fo(e){const t=on(),{control:n=t.control,name:r,defaultValue:s,disabled:i,exact:o}=e||{},l=Ne.useRef(r);l.current=r,Om({disabled:i,subject:n._subjects.values,next:u=>{VM(l.current,u.name,o)&&d(Wn(WM(l.current,n._names,u.values||n._formValues,!1,s)))}});const[c,d]=Ne.useState(n._getWatch(r,s));return Ne.useEffect(()=>n._removeUnmounted()),c}function hG(e){const t=on(),{name:n,disabled:r,control:s=t.control,shouldUnregister:i}=e,o=FM(s._names.array,n),l=Fo({control:s,name:n,defaultValue:_e(s._formValues,n,_e(s._defaultValues,n,e.defaultValue)),exact:!0}),c=pG({control:s,name:n,exact:!0}),d=Ne.useRef(s.register(n,{...e.rules,value:l,...Kr(e.disabled)?{disabled:e.disabled}:{}}));return Ne.useEffect(()=>{const u=s._options.shouldUnregister||i,p=(h,f)=>{const g=_e(s._fields,h);g&&g._f&&(g._f.mount=f)};if(p(n,!0),u){const h=Wn(_e(s._options.defaultValues,n));kt(s._defaultValues,n,h),Gt(_e(s._formValues,n))&&kt(s._formValues,n,h)}return()=>{(o?u&&!s._state.action:u)?s.unregister(n):p(n,!1)}},[n,s,o,i]),Ne.useEffect(()=>{_e(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:_e(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:l,...Kr(r)||c.disabled?{disabled:c.disabled||r}:{},onChange:Ne.useCallback(u=>d.current.onChange({target:{value:LM(u),name:n},type:Bh.CHANGE}),[n]),onBlur:Ne.useCallback(()=>d.current.onBlur({target:{value:_e(s._formValues,n),name:n},type:Bh.BLUR}),[n,s]),ref:Ne.useCallback(u=>{const p=_e(s._fields,n);p&&u&&(p._f.ref={focus:()=>
vendor: 4,342 bytes, line 18
18u.focus(),select:()=>u.select(),setCustomValidity:h=>u.setCustomValidity(h),reportValidity:()=>u.reportValidity()})},[s._fields,n])},formState:c,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!_e(c.errors,n)},isDirty:{enumerable:!0,get:()=>!!_e(c.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!_e(c.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!_e(c.validatingFields,n)},error:{enumerable:!0,get:()=>_e(c.errors,n)}})}}const Et=e=>e.render(hG(e));var HM=(e,t,n,r,s)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:s||!0}}:{},Ii=()=>{const e=typeof performance>"u"?Date.now():performance.now()*1e3;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(Math.random()*16+e)%16|0;return(t=="x"?n:n&3|8).toString(16)})},Pg=(e,t,n={})=>n.shouldFocus||Gt(n.shouldFocus)?n.focusName||`${e}.${Gt(n.focusIndex)?t:n.focusIndex}.`:"",fd=e=>({isOnSubmit:!e||e===Jr.onSubmit,isOnBlur:e===Jr.onBlur,isOnChange:e===Jr.onChange,isOnAll:e===Jr.all,isOnTouch:e===Jr.onTouched}),Hb=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const qo=(e,t,n,r)=>{for(const s of n||Object.keys(e)){const i=_e(e,s);if(i){const{_f:o,...l}=i;if(o){if(o.refs&&o.refs[0]&&t(o.refs[0],s)&&!r)return!0;if(o.ref&&t(o.ref,o.name)&&!r)return!0;if(qo(l,t))break}else if(Un(l)&&qo(l,t))break}}};var qM=(e,t,n)=>{const r=Ir(_e(e,n));return kt(r,"root",t[n]),kt(e,n,r),e},PC=e=>e.type==="file",mi=e=>typeof e=="function",Uh=e=>{if(!NC)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},mh=e=>zs(e),LC=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const sk={value:!1,isValid:!1},ik={value:!0,isValid:!0};var GM=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Gt(e[0].attributes.value)?Gt(e[0].value)||e[0].value===""?ik:{value:e[0].value,isValid:!0}:ik:sk}return sk};const ak={isValid:!1,value:null};var YM=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,ak):ak;function ok(e,t,n="validate"){if(mh(e)||Array.isArray(e)&&e.every(mh)||Kr(e)&&!e)return{type:n,message:mh(e)?e:"",ref:t}}var Io=e=>Un(e)&&!Vh(e)?e:{value:e,message:""},qb=async(e,t,n,r,s)=>{const{ref:i,refs:o,required:l,maxLength:c,minLength:d,min:u,max:p,pattern:h,validate:f,name:g,valueAsNumber:x,mount:b,disabled:y}=e._f,v=_e(t,g);if(!b||y)return{};const C=o?o[0]:i,w=N=>{r&&C.reportValidity&&(C.setCustomValidity(Kr(N)?"":N||""),C.reportValidity())},S={},E=LC(i),k=wu(i),j=E||k,_=(x||PC(i))&&Gt(i.value)&&Gt(v)||Uh(i)&&i.value===""||v===""||Array.isArray(v)&&!v.length,D=HM.bind(null,g,n,S),M=(N,O,R,L=ri.maxLength,P=ri.minLength)=>{const F=N?O:R;S[g]={type:N?L:P,message:F,ref:i,...D(N?L:P,F)}};if(s?!Array.isArray(v)||!v.length:l&&(!j&&(_||vr(v))||Kr(v)&&!v||k&&!GM(o).isValid||E&&!YM(o).isValid)){const{value:N,message:O}=mh(l)?{value:!!l,message:l}:Io(l);if(N&&(S[g]={type:ri.required,message:O,ref:C,...D(ri.required,O)},!n))return w(O),S}if(!_&&(!vr(u)||!vr(p))){let N,O;const R=Io(p),L=Io(u);if(!vr(v)&&!isNaN(v)){const P=i.valueAsNumber||v&&+v;vr(R.value)||(N=P>R.value),vr(L.value)||(O=P<L.value)}else{const P=i.valueAsDate||new Date(v),F=W=>new Date(new Date().toDateString()+" "+W),z=i.type=="time",B=i.type=="week";zs(R.value)&&v&&(N=z?F(v)>F(R.value):B?v>R.value:P>new Date(R.value)),zs(L.value)&&v&&(O=z?F(v)<F(L.value):B?v<L.value:P<new Date(L.value))}if((N||O)&&(M(!!N,R.message,L.message,ri.max,ri.min),!n))return w(S[g].message),S}if((c||d)&&!_&&(zs(v)||s&&Array.isArray(v))){const N=Io(c),O=Io(d),R=!vr(N.value)&&v.length>+N.value,L=!vr(O.value)&&v.length<+O.value;if((R||L)&&(M(R,N.message,O.message),!n))return w(S[g].message),S}if(h&&!_&&zs(v)){const{value:N,message:O}=Io(h);if(Vh(N)&&!v.match(N)&&(S[g]={type:ri.pattern,message:O,ref:i,...D(ri.pattern,O)},!n))return w(O),S}if(f){if(mi(f)){const N=await f(v,t),O=ok(N,C);if(O&&(S[g]={...O,...D(ri.validate,O.message)},!n))return w(O.message),S}else if(Un(f)){let N={};for(const O in f){if(!br(N)&&!n)break;const R=ok(await f[O](v,t),C,O);R&&(N={...R,...D(O,R.message)},w(R.message),n&&(S[g]=N))}if(!br(N)&&(S[g]={ref:C,...N},!n))return S}}return w(!0),S},Lg=(e,t)=>
18[...e,...Ir(t)],Fg=e=>Array.isArray(e)?e.map(()=>{}):void 0;function $g(e,t,n){return[...e.slice(0,t),...Ir(n),...e.slice(t)]}var zg=(e,t,n)=>Array.isArray(e)?(Gt(e[n])&&(e[n]=void 0),e.splice(n,0,e.splice(t,1)[0]),e):[],Bg=(e,t)=>[...Ir(t),...Ir(e)];function fG(e,t){let n=0;const r=[...e];for(const s of t)r.splice(s-n,1),n++;return Su(r).length?r:[]}var Ug=(e,t)=>Gt(t)?[]:fG(e,Ir(t).sort((n,r)=>n-r)),Vg=(e,t,n)=>{[e[t],e[n]]=[e[n],e[t]]};function mG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r<n;)e=Gt(e)?r++:e[t[r++]];return e}function gG(e){for(const t in e)if(e.hasOwnProperty(t)&&!Gt(e[t]))return!1;return!0}function On(e,t){const n=Array.isArray(t)?t:OC(t)?[t]:$M(t),r=n.length===1?e:mG(e,n),s=n.length-1,i=n[s];return r&&delete r[i],s!==0&&(Un(r)&&br(r)||Array.isArray(r)&&gG(r))&&On(e,n.slice(0,-1)),e}var lk=(e,t,n)=>(e[t]=n,e);function KM(e){const t=on(),{control:n=t.control,name:r,keyName:s="id",shouldUnregister:i}=e,[o,l]=Ne.useState(n._getFieldArray(r)),c=Ne.useRef(n._getFieldArray(r).map(Ii)),d=Ne.useRef(o),u=Ne.useRef(r),p=Ne.useRef(!1);u.current=r,d.current=o,n._names.array.add(r),e.rules&&n.register(r,e.rules),Om({next:({values:S,name:E})=>{if(E===u.current||!E){const k=_e(S,u.current);Array.isArray(k)&&(l(k),c.current=k.map(Ii))}},subject:n._subjects.array});const h=Ne.useCallback(S=>{p.current=!0,n._updateFieldArray(r,S)},[n,r]),f=(S,E)=>{const k=Ir(Wn(S)),j=Lg(n._getFieldArray(r),k);n._names.focus=Pg(r,j.length-1,E),c.current=Lg(c.current,k.map(Ii)),h(j),l(j),n._updateFieldArray(r,j,Lg,{argA:Fg(S)})},g=(S,E)=>{const k=Ir(Wn(S)),j=Bg(n._getFieldArray(r),k);n._names.focus=Pg(r,0,E),c.current=Bg(c.current,k.map(Ii)),h(j),l(j),n._updateFieldArray(r,j,Bg,{argA:Fg(S)})},x=S=>{const E=Ug(n._getFieldArray(r),S);c.current=Ug(c.current,S),h(E),l(E),n._updateFieldArray(r,E,Ug,{argA:S})},b=(S,E,k)=>{const j=Ir(Wn(E)),_=$g(n._getFieldArray(r),S,j);n._names.focus=Pg(r,S,k),c.current=$g(c.current,S,j.map(Ii)),h(_),l(_),n._updateFieldArray(r,_,$g,{argA:S,argB:Fg(E)})},y=(S,E)=>{const k=n._getFieldArray(r);Vg(k,S,E),Vg(c.current,S,E),h(k),l(k),n._updateFieldArray(r,k,Vg,{argA:S,argB:E},!1)},v=(S,E)=>{const k=n._getFieldArray(r);zg(k,S,E),zg(c.current,S,E),h(k),l(k),n._updateFieldArray(r,k,zg,{argA:S,argB:E},!1)},C=(S,E)=>{const k=Wn(E),j=lk(n._getFieldArray(r),S,k);c.current=[...j].map((_,D)=>!_||D===S?Ii():c.current[D]),h(j),l([...j]),n._updateFieldArray(r,j,lk,{argA:S,argB:k},!0,!1)},w=S=>{const E=Ir(Wn(S));c.current=E.map(Ii),h([...E]),l([...E]),n._updateFieldArray(r,[...E],k=>k,{},!0,!1)};return Ne.useEffect(()=>{if(n._state.action=!1,Hb(r,n._names)&&n._subjects.state.next({...n._formState}),p.current&&(!fd(n._options.mode).isOnSubmit||n._formState.isSubmitted))if(n._options.resolver)n._executeSchema([r]).then(S=>{const E=_e(S.errors,r),k=_e(n._formState.errors,r);(k?!E&&k.type||E&&(k.type!==E.type||k.message!==E.message):E&&E.type)&&(E?kt(n._formState.errors,r,E):On(n._formState.errors,r),n._subjects.state.next({errors:n._formState.errors}))});else{const S=_e(n._fields,r);S&&S._f&&!(fd(n._options.reValidateMode).isOnSubmit&&fd(n._options.mode).isOnSubmit)&&qb(S,n._formValues,n._options.criteriaMode===Jr.all,n._options.shouldUseNativeValidation,!0).then(E=>!br(E)&&n._subjects.state.next({errors:qM(n._formState.errors,E,r)}))}n._subjects.values.next({name:r,values:{...n._formValues}}),n._names.focus&&qo(n._fields,(S,E)=>{if(n._names.focus&&E.startsWith(n._names.focus)&&S.focus)return S.focus(),1}),n._names.focus="",n._updateValid(),p.current=!1},[o,r,n]),Ne.useEffect(()=>(!_e(n._formValues,r)&&n._updateFieldArray(r),()=>{(n._options.shouldUnregister||i)&&n.unregister(r)}),[r,n,s,i]),{swap:Ne.useCallback(y,[h,r,n]),move:Ne.useCallback(v,[h,r,n]),prepend:Ne.useCallback(g,[h,r,n]),append:Ne.useCallback(f,[h,r,n]),remove:Ne.useCallback(x,[h,r,n]),insert:Ne.useCallback(b,[h,r,n]),update:Ne.useCallback(C,[h,r,n]),replace:Ne.useCallback(w,[h,r,n]),fields:Ne.useMemo(()=>o.map((S,E)=>({...S,[s]:c.current[E]||Ii()})),[o,s])}}var Wg=()=>{let e=[];return{get observers(){return e},next:s=>{for(const i of e)i.next&&i.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(i=>i!==s)}}),unsubscribe:()=>{e=[]}}},Wh=e=>vr(e)||!PM(e);function $i(e,t){if(Wh(e)||Wh(t))return e===t;if(Uo(e)&&Uo(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n){const i=e[s];if(!r.includes(s))return!1;if(s!=="ref"){const o=t[s];if(Uo(i)&&Uo(o)||Un(i)&&Un(o)||Array.isArray(i)&&Array.isArray(o)?!$i(i,o):i!==o)return!1}}return!0}var QM=e=>e.type==="select-multiple",xG=e=>LC(e)||wu(e),Hg=e=>Uh(e)&&e.isConnected,JM=e=>{for(const t in e)if(mi(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(Un(e)||n)for(const r in e)Array.isArray(e[r])||Un(e[r])&&!JM(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):vr(e[r])||(t[r]=!0);return t}function XM(e,t,n){const r=Array.isArray(e);if(Un(e)||r)for(const s in e)Array.isArray(e[s])||Un(e[s])&&!JM(e[s])?Gt(t)||Wh(n[s])?n[s]=Array.isArray(e[s])?Hh(e[s],[]):{...Hh(e[s])}:XM(e[s],vr(t)?{}:t[s],n[s]):n[s]=!$i(e[s],t[s]);return n}var op=(e,t)=>XM(e,t,Hh(t)),ZM=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Gt(e)?e:t?e===""?NaN:e&&+e:n&&zs(e)?new Date(e):r?r(e):e;function qg(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return PC(t)?t.files:LC(t)?YM(e.refs).value:QM(t)?[...t.selectedOptions].map(({value:n})=>n):wu(t)?GM(e.refs).value:ZM(Gt(t.value)?e.ref.value:t.value,e)}var bG=(e,t,n,r)=>{const s={};for(const i of e){const o=_e(t,i);o&&kt(s,i,o._f)}return{criteriaMode:n,names:[...e],fields:s,shouldUseNativeValidation:r}},Zl=e=>Gt(e)?e:Vh(e)?e.source:Un(e)?Vh(e.value)?e.value.source:e.value:e;const ck="AsyncFunction";var yG=e=>(!e||!e.validate)&&!!(mi(e.validate)&&e.validate.constructor.name===ck||Un(e.validate)&&Object.values(e.validate).find(t=>t.constructor.name===ck)),vG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function dk(e,t,n){const r=_e(e,n);if(r||OC(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const i=s.join("."),o=_e(t,i),l=_e(e,i);if(o&&!Array.isArray(o)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};s.pop()}return{name:n}}
vendor: 13,254 bytes, line 18
18var CG=(e,t,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(t||e):(n?r.isOnBlur:s.isOnBlur)?!e:(n?r.isOnChange:s.isOnChange)?e:!0,wG=(e,t)=>!Su(_e(e,t)).length&&On(e,t);const SG={mode:Jr.onSubmit,reValidateMode:Jr.onChange,shouldFocusError:!0};function jG(e={}){let t={...SG,...e},n={submitCount:0,isDirty:!1,isLoading:mi(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},s=Un(t.defaultValues)||Un(t.values)?Wn(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Wn(s),o={action:!1,mount:!1,watch:!1},l={mount:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},p={values:Wg(),array:Wg(),state:Wg()},h=fd(t.mode),f=fd(t.reValidateMode),g=t.criteriaMode===Jr.all,x=q=>Q=>{clearTimeout(d),d=setTimeout(q,Q)},b=async q=>{if(u.isValid||q){const Q=t.resolver?br((await j()).errors):await D(r,!0);Q!==n.isValid&&p.state.next({isValid:Q})}},y=(q,Q)=>{(u.isValidating||u.validatingFields)&&((q||Array.from(l.mount)).forEach(ee=>{ee&&(Q?kt(n.validatingFields,ee,Q):On(n.validatingFields,ee))}),p.state.next({validatingFields:n.validatingFields,isValidating:!br(n.validatingFields)}))},v=(q,Q=[],ee,Ce,se=!0,oe=!0)=>{if(Ce&&ee){if(o.action=!0,oe&&Array.isArray(_e(r,q))){const te=ee(_e(r,q),Ce.argA,Ce.argB);se&&kt(r,q,te)}if(oe&&Array.isArray(_e(n.errors,q))){const te=ee(_e(n.errors,q),Ce.argA,Ce.argB);se&&kt(n.errors,q,te),wG(n.errors,q)}if(u.touchedFields&&oe&&Array.isArray(_e(n.touchedFields,q))){const te=ee(_e(n.touchedFields,q),Ce.argA,Ce.argB);se&&kt(n.touchedFields,q,te)}u.dirtyFields&&(n.dirtyFields=op(s,i)),p.state.next({name:q,isDirty:N(q,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else kt(i,q,Q)},C=(q,Q)=>{kt(n.errors,q,Q),p.state.next({errors:n.errors})},w=q=>{n.errors=q,p.state.next({errors:n.errors,isValid:!1})},S=(q,Q,ee,Ce)=>{const se=_e(r,q);if(se){const oe=_e(i,q,Gt(ee)?_e(s,q):ee);Gt(oe)||Ce&&Ce.defaultChecked||Q?kt(i,q,Q?oe:qg(se._f)):L(q,oe),o.mount&&b()}},E=(q,Q,ee,Ce,se)=>{let oe=!1,te=!1;const de={name:q},ke=!!(_e(r,q)&&_e(r,q)._f&&_e(r,q)._f.disabled);if(!ee||Ce){u.isDirty&&(te=n.isDirty,n.isDirty=de.isDirty=N(),oe=te!==de.isDirty);const Le=ke||$i(_e(s,q),Q);te=!!(!ke&&_e(n.dirtyFields,q)),Le||ke?On(n.dirtyFields,q):kt(n.dirtyFields,q,!0),de.dirtyFields=n.dirtyFields,oe=oe||u.dirtyFields&&te!==!Le}if(ee){const Le=_e(n.touchedFields,q);Le||(kt(n.touchedFields,q,ee),de.touchedFields=n.touchedFields,oe=oe||u.touchedFields&&Le!==ee)}return oe&&se&&p.state.next(de),oe?de:{}},k=(q,Q,ee,Ce)=>{const se=_e(n.errors,q),oe=u.isValid&&Kr(Q)&&n.isValid!==Q;if(e.delayError&&ee?(c=x(()=>C(q,ee)),c(e.delayError)):(clearTimeout(d),c=null,ee?kt(n.errors,q,ee):On(n.errors,q)),(ee?!$i(se,ee):se)||!br(Ce)||oe){const te={...Ce,...oe&&Kr(Q)?{isValid:Q}:{},errors:n.errors,name:q};n={...n,...te},p.state.next(te)}},j=async q=>{y(q,!0);const Q=await t.resolver(i,t.context,bG(q||l.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return y(q),Q},_=async q=>{const{errors:Q}=await j(q);if(q)for(const ee of q){const Ce=_e(Q,ee);Ce?kt(n.errors,ee,Ce):On(n.errors,ee)}else n.errors=Q;return Q},D=async(q,Q,ee={valid:!0})=>{for(const Ce in q){const se=q[Ce];if(se){const{_f:oe,...te}=se;if(oe){const de=l.array.has(oe.name),ke=se._f&&yG(se._f);ke&&u.validatingFields&&y([Ce],!0);const Le=await qb(se,i,g,t.shouldUseNativeValidation&&!Q,de);if(ke&&u.validatingFields&&y([Ce]),Le[oe.name]&&(ee.valid=!1,Q))break;!Q&&(_e(Le,oe.name)?de?qM(n.errors,Le,oe.name):kt(n.errors,oe.name,Le[oe.name]):On(n.errors,oe.name))}!br(te)&&await D(te,Q,ee)}}return ee.valid},M=()=>{for(const q of l.unMount){const Q=_e(r,q);Q&&(Q._f.refs?Q._f.refs.every(ee=>!Hg(ee)):!Hg(Q._f.ref))&&ie(q)}l.unMount=new Set},N=(q,Q)=>(q&&Q&&kt(i,q,Q),!$i(H(),s)),O=(q,Q,ee)=>WM(q,l,{...o.mount?i:Gt(Q)?s:zs(q)?{[q]:Q}:Q},ee,Q),R=q=>Su(_e(o.mount?i:s,q,e.shouldUnregister?_e(s,q,[]):[])),L=(q,Q,ee={})=>{const Ce=_e(r,q);let se=Q;if(Ce){const oe=Ce._f;oe&&(!oe.disabled&&kt(i,q,ZM(Q,oe)),se=Uh(oe.ref)&&vr(Q)?"":Q,QM(oe.ref)?[...oe.ref.options].forEach(te=>te.selected=se.includes(te.value)):oe.refs?wu(oe.ref)?oe.refs.length>1?oe.refs.forEach(te=>(!te.defaultChecked||!te.disabled)&&(te.checked=Array.isArray(se)?!!se.find(de=>de===te.value):se===te.value)):oe.refs[0]&&(oe.refs[0].checked=!!se):oe.refs.forEach(te=>te.checked=te.value===se):PC(oe.ref)?oe.ref.value="":(oe.ref.value=se,oe.ref.type||p.values.next({name:q,values:{...i}})))}(ee.shouldDirty||ee.shouldTouch)&&E(q,se,ee.shouldTouch,ee.shouldDirty,!0),ee.shouldValidate&&W(q)},P=(q,Q,ee)=>{for(const Ce in Q){const se=Q[Ce],oe=`${q}.${Ce}`,te=_e(r,oe);(l.array.has(q)||!Wh(se)||te&&!te._f)&&!Uo(se)?P(oe,se,ee):L(oe,se,ee)}},F=(q,Q,ee={})=>{const Ce=_e(r,q),se=l.array.has(q),oe=Wn(Q);kt(i,q,oe),se?(p.array.next({name:q,values:{...i}}),(u.isDirty||u.dirtyFields)&&ee.shouldDirty&&p.state.next({name:q,dirtyFields:op(s,i),isDirty:N(q,oe)})):Ce&&!Ce._f&&!vr(oe)?P(q,oe,ee):L(q,oe,ee),Hb(q,l)&&p.state.next({...n}),p.values.next({name:o.mount?q:void 0,values:{...i}})},z=async q=>{o.mount=!0;const Q=q.target;let ee=Q.name,Ce=!0;const se=_e(r,ee),oe=()=>Q.type?qg(se._f):LM(q),te=de=>{Ce=Number.isNaN(de)||$i(de,_e(i,ee,de))};if(se){let de,ke;const Le=oe(),at=q.type===Bh.BLUR||q.type===Bh.FOCUS_OUT,Wt=!vG(se._f)&&!t.resolver&&!_e(n.errors,ee)&&!se._f.deps||CG(at,_e(n.touchedFields,ee),n.isSubmitted,f,h),zt=Hb(ee,l,at);kt(i,ee,Le),at?(se._f.onBlur&&se._f.onBlur(q),c&&c(0)):se._f.onChange&&se._f.onChange(q);const Ht=E(ee,Le,at,!1),Oe=!br(Ht)||zt;if(!at&&p.values.next({name:ee,type:q.type,values:{...i}}),Wt)return u.isValid&&(e.mode==="onBlur"?at&&b():b()),Oe&&p.state.next({name:ee,...zt?{}:Ht});if(!at&&zt&&p.state.next({...n}),t.resolver){const{errors:Pe}=await j([ee]);if(te(Le),Ce){const Fe=dk(n.errors,r,ee),pt=dk(Pe,r,Fe.name||ee);de=pt.error,ee=pt.name,ke=br(Pe)}}else y([ee],!0),de=(await qb(se,i,g,t.shouldUseNativeValidation))[ee],y([ee]),te(Le),Ce&&(de?ke=!1:u.isValid&&(ke=await D(r,!0)));Ce&&(se._f.deps&&W(se._f.deps),k(ee,ke,de,Ht))}},B=(q,Q)=>{if(_e(n.errors,Q)&&q.focus)return q.focus(),1},W=async(q,Q={})=>{let ee,Ce;const se=Ir(q);if(t.resolver){const oe=await _(Gt(q)?q:se);ee=br(oe),Ce=q?!se.some(te=>_e(oe,te)):ee}else q?(Ce=(await Promise.all(se.map(async oe=>{const te=_e(r,oe);return await D(te&&te._f?{[oe]:te}:te)}))).every(Boolean),!(!Ce&&!n.isValid)&&b()):Ce=ee=await D(r);return p.state.next({...!zs(q)||u.isValid&&ee!==n.isValid?{}:{name:q},...t.resolver||!q?{isValid:ee}:{},errors:n.errors}),Q.shouldFocus&&!Ce&&qo(r,B,q?se:l.mount),Ce},H=q=>{const Q={...o.mount?i:s};return Gt(q)?Q:zs(q)?_e(Q,q):q.map(ee=>_e(Q,ee))},V=(q,Q)=>({invalid:!!_e((Q||n).errors,q),isDirty:!!_e((Q||n).dirtyFields,q),error:_e((Q||n).errors,q),isValidating:!!_e(n.validatingFields,q),isTouched:!!_e((Q||n).touchedFields,q)}),G=q=>{q&&Ir(q).forEach(Q=>On(n.errors,Q)),p.state.next({errors:q?n.errors:{}})},X=(q,Q,ee)=>{const Ce=(_e(r,q,{_f:{}})._f||{}).ref,se=_e(n.errors,q)||{},{ref:oe,message:te,type:de,...ke}=se;kt(n.errors,q,{...ke,...Q,ref:Ce}),p.state.next({name:q,errors:n.errors,isValid:!1}),ee&&ee.shouldFocus&&Ce&&Ce.focus&&Ce.focus()},K=(q,Q)=>mi(q)?p.values.subscribe({next:ee=>q(O(void 0,Q),ee)}):O(q,Q,!0),ie=(q,Q={})=>{for(const ee of q?Ir(q):l.mount)l.mount.delete(ee),l.array.delete(ee),Q.keepValue||(On(r,ee),On(i,ee)),!Q.keepError&&On(n.errors,ee),!Q.keepDirty&&On(n.dirtyFields,ee),!Q.keepTouched&&On(n.touchedFields,ee),!Q.keepIsValidating&&On(n.validatingFields,ee),!t.shouldUnregister&&!Q.keepDefaultValue&&On(s,ee);p.values.next({values:{...i}}),p.state.next({...n,...Q.keepDirty?{isDirty:N()}:{}}),!Q.keepIsValid&&b()},le=({disabled:q,name:Q,field:ee,fields:Ce,value:se})=>{if(Kr(q)&&o.mount||q){const oe=q?void 0:Gt(se)?qg(ee?ee._f:_e(Ce,Q)._f):se;kt(i,Q,oe),E(Q,oe,!1,!1,!0)}},ce=(q,Q={})=>{let ee=_e(r,q);const Ce=Kr(Q.disabled)||Kr(e.disabled);return kt(r,q,{...ee||{},_f:{...ee&&ee._f?ee._f:{ref:{name:q}},name:q,mount:!0,...Q}}),l.mount.add(q),ee?le({field:ee,disabled:Kr(Q.disabled)?Q.disabled:e.disabled,name:q,value:Q.value}):S(q,!0,Q.value),{...Ce?{disabled:Q.disabled||e.disabled}:{},...t.progressive?{required:!!Q.required,min:Zl(Q.min),max:Zl(Q.max),minLength:Zl(Q.minLength),maxLength:Zl(Q.maxLength),pattern:Zl(Q.pattern)}:{},name:q,onChange:z,onBlur:z,ref:se=>{if(se){ce(q,Q),ee=_e(r,q);const oe=Gt(se.value)&&se.querySelectorAll&&se.querySelectorAll("input,select,textarea")[0]||se,te=xG(oe),de=ee._f.refs||[];if(te?de.find(ke=>ke===oe):oe===ee._f.ref)return;kt(r,q,{_f:{...ee._f,...te?{refs:[...de.filter(Hg),oe,...Array.isArray(_e(s,q))?[{}]:[]],ref:{type:oe.type,name:q}}:{ref:oe}}}),S(q,!1,void 0,oe)}else ee=_e(r,q,{}),ee._f&&(ee._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(FM(l.array,q)&&o.action)&&l.unMount.add(q)}}},J=()=>t.shouldFocusError&&qo(r,B,l.mount),he=q=>{Kr(q)&&(p.state.next({disabled:q}),qo(r,(Q,ee)=>{const Ce=_e(r,ee);Ce&&(Q.disabled=Ce._f.disabled||q,Array.isArray(Ce._f.refs)&&Ce._f.refs.forEach(se=>{se.disabled=Ce._f.disabled||q}))},0,!1))},ne=(q,Q)=>async ee=>{let Ce;ee&&(ee.preventDefault&&ee.preventDefault(),ee.persist&&ee.persist());let se=Wn(i);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:oe,values:te}=await j();n.errors=oe,se=te}else await D(r);if(On(n.errors,"root"),br(n.errors)){p.state.next({errors:{}});try{await q(se,ee)}catch(oe){Ce=oe}}else Q&&await Q({...n.errors},ee),J(),setTimeout(J);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:br(n.errors)&&!Ce,submitCount:n.submitCount+1,errors:n.errors}),Ce)throw Ce},Y=(q,Q={})=>{_e(r,q)&&(Gt(Q.defaultValue)?F(q,Wn(_e(s,q))):(F(q,Q.defaultValue),kt(s,q,Wn(Q.defaultValue))),Q.keepTouched||On(n.touchedFields,q),Q.keepDirty||(On(n.dirtyFields,q),n.isDirty=Q.defaultValue?N(q,Wn(_e(s,q))):N()),Q.keepError||(On(n.errors,q),u.isValid&&b()),p.state.next({...n}))},ae=(q,Q={})=>{const ee=q?Wn(q):s,Ce=Wn(ee),se=br(q),oe=se?s:Ce;if(Q.keepDefaultValues||(s=ee),!Q.keepValues){if(Q.keepDirtyValues)for(const te of l.mount)_e(n.dirtyFields,te)?kt(oe,te,_e(i,te)):F(te,_e(oe,te));else{if(NC&&Gt(q))for(const te of l.mount){const de=_e(r,te);if(de&&de._f){const ke=Array.isArray(de._f.refs)?de._f.refs[0]:de._f.ref;if(Uh(ke)){const Le=ke.closest("form");if(Le){Le.reset();break}}}}r={}}i=e.shouldUnregister?Q.keepDefaultValues?Wn(s):{}:Wn(oe),p.array.next({values:{...oe}}),p.values.next({values:{...oe}})}l={mount:Q.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},o.mount=!u.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues,o.watch=!!e.shouldUnregister,p.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:se?!1:Q.keepDirty?n.isDirty:!!(Q.keepDefaultValues&&!$i(q,s)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:se?{}:Q.keepDirtyValues?Q.keepDefaultValues&&i?op(s,i):n.dirtyFields:Q.keepDefaultValues&&q?op(s,q):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},je=(q,Q)=>ae(mi(q)?q(i):q,Q);return{control:{register:ce,unregister:ie,getFieldState:V,handleSubmit:ne,setError:X,_executeSchema:j,_getWatch:O,_getDirty:N,_updateValid:b,_removeUnmounted:M,_updateFieldArray:v,_updateDisabledField:le,_getFieldArray:R,_reset:ae,_resetDefaultValues:()=>mi(t.defaultValues)&&t.defaultValues().then(q=>{je(q,t.resetOptions),p.state.next({isLoading:!1})}),_updateFormState:q=>{n={...n,...q}},_disableForm:he,_subjects:p,_proxyFormState:u,_setErrors:w,get _fields(){return r},get _formValues(){return i},get _state(){return o},set _state(q){o=q},get _defaultValues(){return s},get _names(){return l},set _names(q){l=q},get _formState(){return n},set _formState(q){n=q},get _options(){return t},set _options(q){t={...t,...q}}},trigger:W,register:ce,handleSubmit:ne,watch:K,setValue:F,getValues:H,reset:je,resetField:Y,clearErrors:G,unregister:ie,setError:X,setFocus:(q,Q={})=>{const ee=_e(r,q),Ce=ee&&ee._f;if(Ce){const se=Ce.refs?Ce.refs[0]:Ce.ref;se.focus&&(se.focus(),Q.shouldSelect&&se.select())}},getFieldState:V}}function Xs(e={}){const t=Ne.useRef(),n=Ne.useRef(),[r,s]=Ne.useState({isDirty:!1,isValidating:!1,isLoading:mi(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:mi(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...jG(e),formState:r});const i=t.current.control;return i._options=e,Om({subject:i._subjects.state,next:o=>{UM(o,i._proxyFormState,i._updateFormState,!0)&&s({...i._formState})}}),Ne.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Ne.useEffect(()=>{if(i._proxyFormState.isDirty){const o=i._getDirty();o!==r.isDirty&&i._subjects.state.next({isDirty:o})}},[i,r.isDirty]),Ne.useEffect(()=>{e.values&&!$i(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values,s(o=>({...o}))):i._resetDefaultValues()},[e.values,i]),Ne.useEffect(()=>{e.errors&&i._setErrors(e.errors)},[e.errors,i]),Ne.useEffect(()=>
18{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),Ne.useEffect(()=>{e.shouldUnregister&&i._subjects.values.next({values:i._getWatch()})},[e.shouldUnregister,i]),t.current.formState=BM(r,i),t.current}const ju=({content:e,learnMoreLink:t})=>e?a.jsx(be,{title:a.jsxs(a.Fragment,{children:[e,t&&a.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",display:"block",marginTop:"4px"},children:"Learn more"})]}),placement:"top-start",arrow:!0,children:a.jsx(_B,{fontSize:"small",sx:{cursor:"help"}})}):null,eR=U.object({value:U.string(),label:U.string()}),kG=e=>{try{return eR.parse(e),!0}catch{return!1}},EG=({disabled:e,fieldName:t,freeSolo:n,label:r,description:s,descriptionLink:i,validating:o,options:l=[],required:c,multiple:d,defaultValue:u})=>{const{control:p}=on(),[h,f]=m.useState(""),g=v=>{const C=l.find(w=>w.value===v);return C||{value:v,label:v}},x=v=>typeof v=="string"?g(v):kG(v)?v:null,b=v=>v?Array.isArray(v)?v.map(x).filter(C=>C!==null):x(v):d?[]:null,y=(v,C)=>{if(!C)return;if(Array.isArray(C)){const S=C.map(E=>typeof E=="string"?E:E.value);v(S);return}const w=typeof C=="string"?C:C?.value??null;v(w)};return a.jsx(Et,{control:p,name:t,defaultValue:u,render:({field:{value:v,onBlur:C,onChange:w,ref:S},fieldState:{error:E}})=>a.jsx(gl,{multiple:d,disabled:e,freeSolo:n,inputValue:h,onInputChange:(k,j)=>f(j),getOptionLabel:k=>typeof k=="string"?k:k.label,isOptionEqualToValue:(k,j)=>(typeof k=="string"?k:k.value)===(typeof j=="string"?j:j.value),onChange:(k,j)=>{y(w,j)},options:l,renderInput:k=>a.jsx(De,{...k,error:!!E,helperText:o?a.jsx(Ze,{size:13}):E?.message||" ",inputRef:S,label:a.jsxs(a.Fragment,{children:[r,a.jsx(ju,{content:s,learnMoreLink:i})]}),InputLabelProps:{sx:{display:"flex",alignItems:"center",gap:.5,pointerEvents:"auto"}},required:c,onBlur:j=>{if(C(),!n)return;const _=j.target.value?.trim();if(!_)return;const D=b(v);if(Array.isArray(D)){if(D.some(({value:N})=>N===_))return;const M=[...D,_];y(w,M),f("")}else y(w,_)}}),value:b(v)})})},_G=({value:e,min:t,max:n,required:r=!1})=>{const s=Number(e);return(e==null||e==="")&&r?{type:"invalid",message:"Value is required"}:Number.isNaN(s)?{type:"invalid",message:"Value must be a number"}:typeof t=="number"&&typeof n=="number"&&(s<t||s>n)?{type:"range",message:`Value must be between ${t} and ${n}`}:typeof t=="number"&&s<t?{type:"min",message:`Value must be greater than or equal to ${t}`}:typeof n=="number"&&s>n?{type:"max",message:`Value must be lower than or equal to ${n}`}:null},TG=({defaultValue:e,disabled:t,fieldName:n,validating:r,label:s,description:i,descriptionLink:o,min:l,max:c,decimalScale:d,required:u=!1})=>{const{control:p,clearErrors:h,setError:f}=on();return a.jsx(Et,{control:p,defaultValue:e,name:n,render:({field:{onBlur:g,onChange:x,ref:b,value:y},fieldState:{error:v}})=>a.jsx(iu,{customInput:De,getInputRef:b,value:y??"",onValueChange:({floatValue:C})=>x(C),onBlur:()=>{g();const C=_G({value:y,max:c,min:l,required:u});C?f(n,C):h(n)},disabled:t,label:a.jsxs(a.Fragment,{children:[s,a.jsx(ju,{content:i,learnMoreLink:o})]}),InputLabelProps:{sx:{display:"flex",alignItems:"center",gap:.5,pointerEvents:"auto"}},required:u,fullWidth:!0,error:!!v,helperText:r?a.jsx(Ze,{size:13}):v?.message||" ",decimalScale:d,fixedDecimalScale:!1,thousandSeparator:","})})},IG=({disabled:e,fieldName:t,label:n,description:r,descriptionLink:s,validating:i,onChange:o=()=>{},options:l,required:c,defaultValue:d})=>{const{control:u}=on();return a.jsx(Et,{control:u,name:t,defaultValue:d,render:({field:{value:p,onBlur:h,onChange:f},fieldState:{error:g}})=>a.jsxs(Qe,{fullWidth:!0,required:c,variant:"filled",children:[a.jsxs(wt,{error:!!g,sx:{display:"flex",alignItems:"center",gap:.5,pointerEvents:"auto"},children:[n,a.jsx(ju,{content:r,learnMoreLink:s})]}),a.jsx(tt,{disabled:e,error:!!g,label:n,multiple:!0,onBlur:h,onChange:x=>{const{value:b}=x.target,y=typeof b=="string"?b.split(","):b;f(y),o(y)},required:c,value:p??[],children:l.map(x=>a.jsx(Se,{value:x.value,children:x.label},x.value))}),a.jsx(Zn,{error:!!g,sx:{color:"error.main"},children:i?a.jsx(Ze,{size:13}):g?.message||" "})]})})},DG=({disabled:e=!1,fieldName:t,label:n,description:r,descriptionLink:s,validating:i,onChange:o=()=>{},options:l,required:c,defaultValue:d})=>{const{control:u}=on();return a.jsx(Et,{control:u,name:t,defaultValue:d,render:({field:{value:p,onBlur:h,onChange:f},fieldState:{error:g}})=>a.jsxs(Qe,{disabled:e,fullWidth:!0,required:c,variant:"filled",children:[a.jsxs(wt,{error:!!g,sx:{dis
18play:"flex",alignItems:"center",gap:.5,pointerEvents:"auto"},children:[n,a.jsx(ju,{content:r,learnMoreLink:s})]}),a.jsx(tt,{error:!!g,label:n,onBlur:h,onChange:x=>{const{value:b}=x.target;f(b),o(b)},required:c,value:p??"",children:l.map(x=>a.jsx(Se,{value:x.value,children:x.label},x.value))}),a.jsx(Zn,{error:!!g,sx:{color:"error.main"},children:i?a.jsx(Ze,{size:13}):g?.message||" "})]})})},AG=e=>!!e.multiple,MG=e=>!e.multiple,RG=e=>AG(e)?a.jsx(IG,{...e}):MG(e)?a.jsx(DG,{...e}):null,NG=({handleToggle:e,showText:t})=>a.jsx(Bn,{position:"end",children:a.jsx(Ie,{"aria-label":"Toggle text",onClick:e,sx:{"&:hover":{background:"transparent",boxShadow:"none"}},children:t?a.jsx(vm,{}):a.jsx(zD,{})})}),OG=({defaultValue:e="",disabled:t,fieldName:n,InputProps:r,description:s,descriptionLink:i,label:o,multiline:l,onBlur:c=()=>{},onChange:d=()=>{},required:u=!1,type:p="text",validating:h,visibleRows:f=4})=>{const{control:g}=on(),[x,b]=m.useState(!1),y=()=>b(w=>!w),v=()=>p==="password"?x?"text":"password":p,C=()=>p!=="password"?r:{...r,endAdornment:a.jsx(NG,{handleToggle:y,showText:x})};return a.jsx(Et,{control:g,defaultValue:e,name:n,render:({field:{onBlur:w,onChange:S,ref:E,value:k},fieldState:{error:j}})=>a.jsx(De,{type:v(),disabled:t,error:!!j,fullWidth:!0,helperText:h?a.jsx(Ze,{size:13}):j?.message||" ",InputProps:C(),InputLabelProps:{sx:{display:"flex",alignItems:"center",gap:.5,pointerEvents:"auto"}},inputRef:E,label:a.jsxs(a.Fragment,{children:[o,a.jsx(ju,{content:s,learnMoreLink:i})]}),multiline:l,rows:f,onBlur:_=>{w(),c(_.target.value||"")},onChange:_=>{S(_.target.value||""),d(_.target.value||"")},required:u,value:k??""})})},PG=({separatorPosition:e,size:t=18,value:n})=>a.jsxs(a.Fragment,{children:[e==="top"&&a.jsx(St,{sx:{m:1}}),a.jsx(I,{fontSize:t,m:2,children:a.jsx("b",{children:n})}),e==="bottom"&&a.jsx(St,{sx:{m:1}})]}),FC=({fields:e,disabled:t,validating:n,parentField:r})=>{const s=i=>r?.length?`${r}.${i}`:i;return a.jsx(a.Fragment,{children:e.map(i=>{switch(i.elementType){case"TextField":return a.jsx(OG,{defaultValue:i.default,fieldName:s(i.name),required:i.required,label:i.displayName,description:i.description,descriptionLink:i.descriptionLink,disabled:t,validating:n,multiline:i.multiline,type:i.inputType,visibleRows:i.visibleRows},i.name);case"NumericField":return a.jsx(TG,{defaultValue:i.default,fieldName:s(i.name),required:i.required,label:i.displayName,description:i.description,descriptionLink:i.descriptionLink,disabled:t,validating:n,min:i.min,max:i.max,decimalScale:i.decimalScale},i.name);case"Select":return a.jsx(RG,{defaultValue:i.default,disabled:t,fieldName:s(i.name),label:i.displayName,description:i.description,descriptionLink:i.descriptionLink,validating:n,multiple:i.multiple,options:i.options.map(o=>({label:o,value:o})),required:i.required},i.name);case"Autocomplete":return a.jsx(EG,{defaultValue:i.default,disabled:t,fieldName:s(i.name),freeSolo:i.freeSolo,label:i.displayName,description:i.description,descriptionLink:i.descriptionLink,validating:n,multiple:i.multiple,options:i.options?.map(o=>({label:o,value:o})),required:i.required},i.name);case"TextLabel":return a.jsx(PG,{value:i.displayName,separatorPosition:i.separatorPosition,size:i.size},i.name);default:return null}})})},LG=({status:e,statusText:t="Connection",errorMessage:n})=>{const r=e==="success";if(!e)return null;const s=r?qv:Gv,i=`${t} ${r?"Successful":"Failed"}`;return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",gap:.5},children:[a.jsxs(T,{sx:{alignItems:"center",columnGap:1,display:"flex"},children:[a.jsx(s,{color:r?"success":"error"}),a.jsx(I,{fontSize:"12px",fontWeight:500,children:i})]}),!r&&n&&a.jsx(I,{fontSize:"11px",color:"error",sx:{ml:3.5},children:n})]})},tR=({status:e,statusText:t="Connection",buttonText:n,errorMessage:r,onClick:s=()=>{},disabled:i=!1,loading:o=!1,sx:l,...c})=>a.jsxs($,{alignItems:"center",columnGap:2,direction:"row",children:[a.jsx(LG,{status:e,statusText:t,errorMessage:r}),a.jsx(Dt,{disabled:i,loading:o,onClick:s,sx:{whiteSpace:"nowrap",...l},variant:"outlined",...c,children:n})]}),FG=({availableContacts:e,isUpdating:t,addTooltip:n,onAdd:r,onCreateNewUser:s,allowUserCreation:i,canEdit:o})=>{const[l,c]=m.useState(null),[d,u]=m.useState(""),p=ct(),h=m.useMemo(()=>
18{if(!d)return e;const v=d.toLowerCase();return e.filter(C=>C.name.toLowerCase().includes(v)||C.email?.toLowerCase().includes(v))},[e,d]),f=m.useCallback(v=>{c(v.currentTarget)},[]),g=m.useCallback(()=>{c(null),u("")},[]),x=m.useCallback(async v=>{r(v),p()&&g()},[g,p,r]),b=m.useCallback(()=>{g(),s()},[g,s]),y=!!l;return o?a.jsxs(a.Fragment,{children:[a.jsx(be,{title:n,children:a.jsx("span",{children:a.jsx(Ie,{disabled:t,onClick:f,sx:{border:"2px dashed",borderColor:"divider",height:32,width:32},children:a.jsx(ca,{size:20})})})}),a.jsx(ED,{anchorEl:l,anchorOrigin:{horizontal:"left",vertical:"bottom"},onClose:g,open:y,slotProps:{paper:{sx:{mt:1,width:320}}},children:a.jsxs($,{sx:{p:2},children:[a.jsx(De,{autoFocus:!0,fullWidth:!0,label:"Search contacts",onChange:v=>u(v.target.value),placeholder:"Search by name or email",size:"small",value:d}),a.jsx($,{sx:{maxHeight:300,mt:2,overflowY:"auto"},children:h.length===0?a.jsx(I,{sx:{color:"text.secondary",p:2,textAlign:"center"},children:d?"No contacts found":"All contacts are assigned"}):h.map(v=>a.jsxs(T,{onClick:()=>x(v),sx:{"&:hover":{backgroundColor:"action.hover"},alignItems:"center",cursor:"pointer",display:"flex",gap:1.5,p:1.5},children:[a.jsx(as,{sx:{backgroundColor:"icon.brand.main",color:"text.inverse",fontSize:11,fontWeight:600,height:28,width:28},children:Md(v.name)}),a.jsxs($,{sx:{flex:1,minWidth:0},children:[a.jsx(I,{sx:{fontSize:14,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.email&&a.jsx(I,{sx:{color:"text.secondary",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.email})]})]},v.id))}),i&&a.jsxs(a.Fragment,{children:[a.jsx(St,{sx:{my:1}}),a.jsx(re,{fullWidth:!0,onClick:b,startIcon:a.jsx(BD,{size:18}),sx:{justifyContent:"flex-start",textTransform:"none"},variant:"text",children:"Create new user"})]})]})})]}):null},$G=m.forwardRef(({contact:e,isUpdating:t,onRemove:n,index:r,spacing:s,canEdit:i},o)=>a.jsxs(T,{ref:o,sx:{ml:r===0||!s?0:`${s}px`,position:"relative",zIndex:r??0,transformOrigin:"center",transition:"transform 0.25s ease, box-shadow 0.25s ease","&:hover":{transform:"scale(1.15)",boxShadow:3,zIndex:100},"&:hover .remove-button":{opacity:1}},children:[a.jsx(be,{title:a.jsxs(a.Fragment,{children:[e.name,a.jsx("br",{}),e.email]}),children:a.jsx(as,{sx:{backgroundColor:"icon.brand.main",color:"text.inverse",fontSize:11,fontWeight:600,height:32,width:32},children:e.initials})}),i&&a.jsx(Ie,{className:"remove-button",disabled:t,onClick:()=>n(e.id,e.name),sx:{backgroundColor:"error.main",color:"white",height:24,opacity:0,position:"absolute",right:-8,top:-8,transition:"opacity 0.2s",width:24,"&:hover":{backgroundColor:"error.dark"}},children:a.jsx(Jt,{size:18,strokeWidth:3})})]})),zG=(e,t,n)=>e*(n+4)<=t-48?4:Math.ceil((t-48)/e)-n,nR=({selectedContacts:e,availableContacts:t,isUpdating:n,onAdd:r,onClickRemove:s,onCreateNewUser:i,addTooltip:o,allowUserCreation:l,canEdit:c=!1})=>{const d=m.useRef(null),u=m.useRef(null),[p,h]=m.useState(null),[f,g]=m.useState(null);m.useEffect(()=>{if(!d.current)return;const b=()=>{if(!d.current)return;const{width:v}=d.current.getBoundingClientRect();h(v)};b();const y=new ResizeObserver(()=>{b()});return y.observe(d.current),()=>{y.disconnect()}},[]),m.useEffect(()=>{if(!u.current)return;const b=u.current.getBoundingClientRect();b.width&&g(b.width)},[e.length]);const x=zG(e.length,p||0,f||0);return a.jsxs(T,{ref:d,sx:{display:"flex",alignItems:"center",gap:.5,width:"100%"},children:[a.jsx(T,{sx:{display:"flex",flexGrow:x>4?1:0,flexShrink:1,flexBasis:0},children:e.map((b,y)=>a.jsx($G,{ref:y===0?u:void 0,canEdit:c,contact:b,isUpdating:n,index:y,spacing:x,onRemove:()=>s(b)},b.id))}),a.jsx(FG,{addTooltip:o,availableContacts:t,canEdit:c,isUpdating:n,onAdd:r,onCreateNewUser:i,allowUserCreation:l})]})},rR=m.createContext(null),Al=()=>m.useContext(rR),tr=()=>{const[e]=D5(),{clientId:t,clientName:n,clientNiceId:r,engagementId:s,engagementName:i,engagementNiceId:o}=pe(),l=m.useMemo(()=>({clientId:t,clientName:n,clientNiceId:r,engagementId:s,engagementName:i,engagementNiceId:o,application:"mevo-app",$current_url:window.location.href}),[t,n,r,s,i,o]);return{mpTrack:m.useCallback((d,u)=>{TB()&&e({eventName:d,eventObject:{...l,...u}})},[l,e])}},BG={editRoles:"Save Role Edits",editSubscriptions:"Save Subscription
18Edits"},UG=()=>{const{mpTrack:e}=tr();return(n,r)=>{e("MEVO_FEATURE_MANAGEMENT",{actionType:BG[n],actionData:{...r}})}},sR=e=>e.map(t=>({...t,...t.roles})),uk=(e,t)=>{const n=[...e],r=n.findIndex(s=>s.id===t.id);return r!==-1?n.splice(r,1):n.push(t),n},VG=({field:e,newEdit:t,row:n})=>{const r={...n};return r.roles={...r.roles},r.roles[e]=t,{...r,...r.roles}},iR=(e,t)=>t.findIndex(n=>n.id===e)!==-1,WG=e=>pM(jM.filter(t=>!t.includes("CustomerAdmin")),e),HG=()=>{const e=UG(),{featureManagementData:t,state:n,dispatch:r}=Al(),{editRoles:s,editSubscriptions:i,gridApiRef:o}=n,{rows:l}=t,{engagementId:c}=pe(),d=ct(),[u]=A5(),[p,h]=m.useState(!1),f=m.useMemo(()=>s.length+i.length,[s,i]),g=m.useMemo(()=>f===0,[f]),x=m.useMemo(()=>yM(f),[f]),b=()=>h(!1),y=()=>{o&&(o.current.updateRows(sR(l)),r({type:"clearEdits"}))},v=async()=>{const C=s.length?u({engagementId:c,path:"role",body:s.map(S=>({is_enabled:S.isEnabled,feature_role_id:S.id}))}):null,w=i.length?u({engagementId:c,path:"subscription",body:i.map(S=>({is_enabled:S.isEnabled,subscription_id:S.id}))}):null;C&&e("editRoles",{edits:s}),w&&e("editSubscriptions",{edits:i}),await Promise.all([C,w]),d()&&(r({type:"clearEdits"}),h(!1))};return a.jsxs($,{direction:"row",justifyContent:"end",gap:2,mt:3,children:[a.jsx(be,{title:"Undo edits since last save.",children:a.jsx(T,{children:a.jsx(re,{"data-testid":"feature-management:undo-changes:button",disabled:g,id:"feature-management-undo-edits-button",onClick:y,variant:"outlined",children:"Undo Current Changes"})})}),a.jsx(re,{"data-testid":"feature-management:save-changes:button",disabled:g,id:"feature-management-save-edits-button",onClick:()=>h(!0),variant:"contained",children:"Save Changes"}),a.jsx(mt,{bodyText:x,handleClose:b,handleAccept:v,open:p,testId:"feature-management:save-confirm:dialog",title:"Save Changes?",acceptLabel:"Save"})]})},pk=(e,t,n)=>{if(e&&"reportValidity"in e){const r=_e(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},aR=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?pk(r.ref,n,e):r.refs&&r.refs.forEach(s=>pk(s,n,e))}},qG=(e,t)=>{t.shouldUseNativeValidation&&aR(e,t);const n={};for(const r in e){const s=_e(t.fields,r),i=Object.assign(e[r]||{},{ref:s&&s.ref});if(GG(t.names||Object.keys(e),r)){const o=Object.assign({},_e(n,r));kt(o,"root",i),kt(n,r,o)}else kt(n,r,i)}return n},GG=(e,t)=>e.some(n=>n.startsWith(t+"."));var YG=function(e,t){for(var n={};e.length;){var r=e[0],s=r.code,i=r.message,o=r.path.join(".");if(!n[o])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[o]={message:l.message,type:l.code}}else n[o]={message:i,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(u){return u.errors.forEach(function(p){return e.push(p)})}),t){var c=n[o].types,d=c&&c[r.code];n[o]=HM(o,t,n,s,d?[].concat(d,r.message):r.message)}e.shift()}return n},Zs=function(e,t,n){return n===void 0&&(n={}),function(r,s,i){try{return Promise.resolve((function(o,l){try{var c=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&aR({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return c&&c.then?c.then(void 0,l):c})(0,function(o){if((function(l){return Array.isArray(l?.errors)})(o))return{values:{},errors:qG(YG(o.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw o}))}catch(o){return Promise.reject(o)}}},KG=function(e,t,n){if(n||arguments.length===2)for(var r=0,s=t.length,i;r<s;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))};function QG(e,t,n){var r=function(i){return e.apply(void 0,KG([i],Array.from(t),!1))},s=n??e.lazy;return s===void 0?r:Object.assign(r,{lazy:s,lazyArgs:t})}function ku(e,t,n){var r=e.length-t.length;if(r===0)return e.apply(void 0,Array.from(t));if(r===1)return QG(e,t,n);throw new Error("Wrong number of arguments")}function JG(e){return e===null?"Null":e===void 0?"Undefined":Object.prototype.toString.call(e).slice(8,-1)}function XG(e){return new RegExp(e.source,(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.sticky?"y":"")+(e.unicode?"u":""))}function oR(e,t,n,r){function s(i){for(var o=t.length,l=0;l<o;){if(e===t[l])return n[l];l+=1}t[l+1]=e,n[l+1]=i;for(var c in e)i[c]=oR(e[c],t,n);return i}switch(JG(e)){case"Object":return s({});case"Array":return s([]);case"Date":return new Date(e.valueOf());case"RegExp":return XG(e);default:return e}}function ZG(e){return e!=null&&typeof e.clone=="function"?e.clone():oR(e,[],[])}var lR=function(e,t,n){if(n||arguments.length===2)for(var r=0,s=t.length,i;r<s;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},cR={asc:function(e,t){return e>t},desc:function(e,t){return e<t}};function eY(e,t){var n=Array.isArray(t)?t:Array.from(t),r=n[0],s=n.slice(1);
18if(!tY(r)){var i=Gb.apply(void 0,s);return e(r,i)}var o=Gb.apply(void 0,lR([r],s,!1));return function(l){return e(l,o)}}function Gb(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var s=typeof e=="function"?e:e[0],i=typeof e=="function"?"asc":e[1],o=cR,l=i,c=o[l],d=t===void 0?void 0:Gb.apply(void 0,lR([t],n,!1));return function(u,p){var h,f=s(u),g=s(p);return c(f,g)?1:c(g,f)?-1:(h=d?.(u,p))!==null&&h!==void 0?h:0}}function tY(e){if(hk(e))return!0;if(typeof e!="object"||!Array.isArray(e))return!1;var t=e,n=t[0],r=t[1],s=t.slice(2);return hk(n)&&typeof r=="string"&&r in cR&&s.length===0}var hk=function(e){return typeof e=="function"&&e.length===1};function qh(){return ku(Object.entries,arguments)}(function(e){e.strict=e})(qh||(qh={}));function Ws(){return ku(dR(!1),arguments)}var dR=function(e){return function(t,n){for(var r={},s=0;s<t.length;s++){var i=t[s],o=e?n(i,s,t):n(i);if(o!==void 0){var l=String(o),c=r[l];c===void 0&&(c=[],r[l]=c),c.push(i)}}return r}};(function(e){function t(){return ku(dR(!0),arguments)}e.indexed=t,e.strict=e})(Ws||(Ws={}));function Go(e){return Array.isArray(e)}function nY(e){return!!e&&!Array.isArray(e)&&typeof e=="object"}function rY(e){return typeof e=="string"}function Yb(e){return e===void 0?!0:Go(e)||rY(e)?e.length===0:nY(e)?Object.keys(e).length===0:!1}function sY(e){return typeof e=="number"&&!isNaN(e)}function iY(e){if(typeof e!="object"||e===null)return!1;var t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Kb(){return ku(Object.keys,arguments)}(function(e){e.strict=e})(Kb||(Kb={}));var aY=function(e){return function(t){var n=e,r=t[n];return r}};function Qb(){return eY(oY,arguments)}var oY=function(e,t){return e.slice().sort(t)};(function(e){e.strict=e})(Qb||(Qb={}));function lY(){return ku(Object.values,arguments)}const uR=m.createContext(null),fk={label:"Select/Deselect all engagements",value:"__allEngagements"},Jb=()=>m.useContext(uR),Pm=()=>on(),cY=({onValidInput:e,onInvalidInput:t,overrideEnabled:n=!1})=>{const[r]=M5(),[s,i]=m.useState(null),o=m.useRef(0),l=fs(m.useCallback(async c=>{if(n){i(null),e();return}o.current+=1;const d=o.current,{is_valid:u,message:p}=await r({feature_name:c}).unwrap();if(o.current===d)if(u&&c.length)i(null),e();else{const h=p??"Required";i(h),t(h)}},[r,e,t,n]),500);return{errorMessage:s,debouncedNameValidation:l}},dY=e=>typeof e=="object"&&e!==null&&"title"in e,uY=e=>typeof e=="object"&&e!==null&&"value"in e,pY=e=>e.flatMap(t=>dY(t)?[{title:t.title},...t.items.map(n=>({label:n.label,value:n.value}))]:[{label:t.label,value:t.value}]),hY=e=>e.map(t=>"title"in t?a.jsx(Nh,{children:a.jsx(I,{variant:"overline",children:t.title})},`header-${t.title}`):a.jsx(Se,{value:t.value,children:t.label},t.value)),Gg=({disabled:e=!1,defaultValue:t="",fieldName:n,inputProps:r,label:s,required:i=!1,items:o,multiple:l,selectAllKey:c,testId:d})=>{const{control:u}=Pm(),p=pY(o),h=hY(p),f=m.useRef(null);return a.jsx(Et,{control:u,name:n,render:({field:{value:g,onBlur:x,onChange:b},fieldState:{error:y}})=>a.jsxs(Qe,{disabled:e,fullWidth:!0,required:i,variant:"filled",children:[a.jsx(wt,{error:!!y,children:s}),a.jsx(tt,{multiple:l,error:!!y,inputProps:{...r,...d?{"data-testid":d}:{}},label:s,onBlur:x,onChange:v=>{const{value:C}=v.target;if(l&&c&&Go(C)&&C.includes(c)){if(C.length===p.length){b([]);return}b(p.reduce((w,S)=>uY(S)&&S.value!==c?[S.value,...w]:w,[])),setTimeout(()=>{f.current&&(f.current.scrollTop=0)},0);return}b(C)},required:i,value:g??t,MenuProps:{PaperProps:{ref:f,sx:{maxHeight:400,overflowY:"auto"}},TransitionProps:{onEnter:v=>{v.scrollTop=0}}},children:h}),a.jsx(Zn,{error:!!y,children:y?.message})]})})},fY=({disabled:e,defaultValue:t="",fieldName:n,InputProps:r,label:s,required:i=!1,testId:o,type:l="text",onValueChange:c,errorHelperText:d})=>{const{control:u}=Pm();return a.jsx(Et,{control:u,defaultValue:t,name:n,render:({field:{onBlur:p,onChange:h,value:f},fieldState:{error:g}})=>a.jsx(De,{disabled:e,error:!!g,fullWidth:!0,helperText:g?d??g.message:void 0,inputProps:{"data-testid":o},InputProps:r,label:s,onBlur:p,onChange:x=>{const b=x.target.value;c?.(b),h(b)},required:i,type:l,value:f??null})})},mY=()=>{const{setError:e,clearErrors:t,formState:{errors:n}}
18=Pm(),{dispatch:r}=Jb(),[s,i]=m.useState(!1),{debouncedNameValidation:o}=cY({overrideEnabled:s,onInvalidInput:x=>{r({type:"isValidating",value:!1}),e("name",{message:x,type:"validate"})},onValidInput:()=>{r({type:"isValidating",value:!1}),t("name")}}),l=x=>{s&&i(!1),r({type:"isValidating",value:!0}),o(x)},c=()=>{i(!0),t("name"),r({type:"isValidating",value:!1})},d=n.name?.message,u=!!d&&!s&&d.includes("Please choose another name"),{availableEngagements:p,availableRoles:h,parentMenus:f}=Jb(),g=[fk,...p.map(({name:x,id:b})=>({label:x,value:b}))];return a.jsx(T,{component:"form",children:a.jsx($,{sx:{py:2,width:500,flexDirection:{xs:"column",lg:"row"},gap:3,justifyContent:"center"},children:a.jsxs($,{sx:{width:"100%",maxWidth:700,gap:3},children:[a.jsx(fY,{fieldName:"name",label:"Feature Name",required:!0,onValueChange:l,testId:"feature-management:field:feature-name",errorHelperText:u?a.jsxs(a.Fragment,{children:[d," ",a.jsx(re,{variant:"text",color:"primary",onClick:c,sx:{verticalAlign:"baseline",minWidth:"auto",padding:0,"&:hover":{textDecoration:"underline"}},children:"Override?"})]}):void 0}),a.jsx(St,{}),a.jsx(I,{variant:"subtitle1",children:"Feature Settings"}),a.jsx(Gg,{testId:"feature-management:field:parent-menu",fieldName:"parent",label:"Parent Menu",items:f,required:!0}),a.jsx(Gg,{fieldName:"engagements",label:"Engagements",items:g,multiple:!0,required:!0,selectAllKey:fk.value,testId:"feature-management:field:engagements"}),a.jsx(Gg,{fieldName:"userRoles",label:"Default User Roles",items:h,multiple:!0,required:!0,testId:"feature-management:field:user-roles"})]})})})},gY=()=>{const{open:e,onClose:t,handleSubmit:n,state:{isValidating:r}}=Jb(),{getValues:s,formState:{isValid:i,errors:o},reset:l}=Pm(),c=Object.keys(o).length>0,[d,u]=m.useState(null),[p,h]=m.useState(!1),f=()=>{l(),t()},g=async()=>{u(null),h(!0);try{const{success:x,error:b}=await n(s());u(b),x&&f()}finally{h(!1)}};return a.jsxs(yt,{"data-testid":"feature-management:new-feature:dialog",open:e,children:[a.jsx(vt,{children:"Create New Feature"}),a.jsx(Ct,{children:a.jsx(mY,{})}),a.jsx(T,{sx:{textAlign:"center"},children:a.jsx(I,{color:"error",children:d})}),a.jsxs(T,{sx:{display:"flex",justifyContent:"flex-end",gap:2,px:2},children:[a.jsx(re,{"data-testid":"feature-management:new-feature:cancel",onClick:f,sx:{maxWidth:200,my:2},variant:"outlined",color:"secondary",children:"Cancel"}),a.jsx(Dt,{"data-testid":"feature-management:new-feature:submit",type:"submit",onClick:g,sx:{maxWidth:200,my:2},variant:"contained",color:"primary",disabled:!i||r||c,loading:p,children:"Create Feature"})]})]})},mk=U.string().min(1,{message:"Required"}),xY=U.object({name:mk,parent:mk,engagements:U.array(U.number()).min(1,{message:"Required"}),userRoles:U.array(U.string()).min(1,{message:"Required"})}),bY={isValidating:!1},yY=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,vY=({onClose:e,handleSubmit:t})=>{const{userIsInternal:n}=gt(),[r,s]=m.useReducer(yY,bY),{state:{newFeatureFormOpen:i},featureManagementData:{columns:o,rows:l}}=Al(),{clientId:c}=pe(),{data:d=[]}=Nd({body:n?{}:{client_id:c}}),u=Xs({mode:"onChange",resolver:Zs(xY),values:{engagements:[],name:"",parent:"",userRoles:[]}}),p=m.useMemo(()=>{const g=l.reduce((x,{path:b,name:y})=>({...x,[b]:y}),{});return l.map(({path:x})=>({label:x.split(".").map((y,v,C)=>{const w=C.slice(0,v+1).join(".");return g[w]??C[v]}).join(" ⺠"),value:x}))},[l]),h=m.useMemo(()=>[{title:"Internal Roles",items:o.filter(({value:g})=>g.startsWith("InternalRoles")).map(({label:g,value:x})=>({label:g,value:x}))},{title:"External Roles",items:o.filter(({value:g})=>g.startsWith("CustomerRoles")).map(({label:g,value:x})=>({label:g,value:x}))}],[o]),f=m.useMemo(()=>({dispatch:s,state:r,userIsInternal:n,onClose:e,open:i,availableEngagements:d?.filter(({active:g,value:x})=>g&&sY(x)).map(g=>({name:g.label,id:Number(g.value)})),availableRoles:h,parentMenus:p,handleSubmit:t}),[r,n,e,i,d,h,p,t]);return a.jsx(uR.Provider,{value:f,children:a.jsx(Js,{...u,children:a.jsx(gY,{})})})},pR=800,gk=60,CY=e=>e,wY=({params:e})=>{const{handleClickCheckbox:t,state:n}=Al(),{editRoles:r}
18=n,{field:s,row:i,value:o,colDef:l}=e;if(!o)return null;const c=iR(o.id,r),d=()=>{Tn(Rd,s)&&t({isEnabled:!o.isEnabled,id:o.id,field:s,row:i})};return a.jsx(be,{placement:"top",title:`${i.name} - ${l.headerName}`,children:a.jsx(et,{"aria-label":`${i.name} - ${l.headerName}`,"data-testid":`feature-management:checkbox:${i.name.toLowerCase().replace(/\s+/g,"-")}:${s}`,sx:{color:u=>c?u.palette.info.main:"default"},color:c?"info":"primary",checked:o.isEnabled,onClick:d})})},SY=({params:e})=>a.jsx(be,{placement:"top",title:e.colDef.headerName,children:a.jsx(I,{sx:{height:"auto",fontSize:12,whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis"},children:e.colDef.headerName})}),jY=({params:e})=>{const{handleClickSwitch:t,state:n}=Al(),{userRoles:r}=gt(),{editSubscriptions:s}=n,{colDef:i,row:o,value:l}=e,c=m.useMemo(()=>WG(r),[r]),d=iR(o.id,s),u=()=>{t({id:o.id,isEnabled:!l,row:o})},p=c?`${o.name} - ${i.headerName}`:"Editing not available.";return a.jsx(be,{placement:"top",title:p,children:a.jsx(T,{children:a.jsx(Dn,{"aria-label":`Toggle ${o.name} engagement permission`,checked:l,"data-testid":`feature-management:switch:${o.name.toLowerCase().replace(/\s+/g,"-")}`,onClick:u,disabled:!c,sx:{"& .MuiSwitch-thumb":{backgroundColor:h=>d?h.palette.info.main:"default"}},color:d?"info":"primary"})})})},Lm={sortable:!1,resizable:!0,flex:1,renderHeader:e=>a.jsx(SY,{params:e})},kY={...Lm,field:"loadingSpaceFiller",headerName:""},EY={...Lm,field:"isEnabled",headerName:"Engagement Permissions",flex:0,renderCell:e=>a.jsx(jY,{params:e})},_Y=e=>({...Lm,field:e.value,headerName:e.label,...e,renderCell:t=>a.jsx(wY,{params:t})}),TY=e=>e.length?[EY,...e.map(t=>_Y(t))]:[kY],IY=[{groupId:"switch",headerName:"",children:[{field:"loadingSpaceFiller"}]},{groupId:"Internal",children:Rd.filter(e=>e.includes("Internal")).map(e=>({field:e}))}
18,{groupId:"External",children:Rd.filter(e=>e.includes("Customer")).map(e=>({field:e}))}],DY={...Lm,headerName:"Features",minWidth:220,valueFormatter(e){const t=UD(e.value);return a.jsx(be,{placement:"top",title:t,children:a.jsx("span",{children:t})})}},Xb=bs(Mn)(({theme:e})=>{const{text:t,background:n}=e.palette,{spacing:r}=e,s={backgroundColor:n.paper,color:t.default};return{border:"none",maxHeight:pR,".MuiDataGrid-cell":{border:"none",paddingLeft:r(2),paddingRight:r(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:r(1)}},".MuiDataGrid-columnHeader":{paddingLeft:r(2),paddingRight:r(2),":focus-within":{outline:"none"}},".MuiDataGrid-columnHeaders":{backgroundColor:n.tableHeader,border:"none",paddingLeft:r(.5)},".MuiDataGrid-columnHeaderTitleContainerContent":{textTransform:"uppercase"},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-iconButtonContainer":{paddingLeft:r(1.5)},".MuiDataGrid-row":{paddingLeft:r(.5),borderRadius:r(1),...s},".MuiDataGrid-row:nth-of-type(even)":{...s},".MuiDataGrid-treeDataGroupingCell":{span:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}}});Xb.defaultProps={...Xb.defaultProps,columnHeaderHeight:gk,disableColumnMenu:!0,disableColumnSelector:!0,disableColumnReorder:!0,disableRowSelectionOnClick:!0,hideFooter:!0,getRowSpacing:()=>({top:0,bottom:8}),rowHeight:gk,treeData:!0};const AY=()=>{const{isLoading:e,featureManagementData:t,state:n,dispatch:r}=Al(),{rows:s,columns:i}=t,{gridApiRef:o}=n,l=zn(),c=m.useMemo(()=>TY(i),[i]),d=m.useMemo(()=>sR(s),[s]),u=m.useMemo(()=>a.jsx(Xb,{apiRef:l,autoHeight:e,columnGroupingModel:IY,columns:c,experimentalFeatures:{columnGrouping:!0},getTreeDataPath:p=>p.path.split("."),groupingColDef:DY,loading:e,rows:e?[]:d,slots:{loadingOverlay:Cs}}),[l,c,e,d]);return m.useEffect(()=>{o||r({type:"gridApiRef",value:l})},[o]),a.jsx(T,{sx:{width:"100%",maxHeight:pR},children:u})},MY=()=>{const{isLoading:e,dispatch:t,featureManagementData:{columns:n}}=Al(),[r]=R5(),{userIsSuper:s}=gt(),i=()=>{t({type:"newFeatureFormOpen",value:!0})},o=()=>{t({type:"newFeatureFormOpen",value:!1})},l=async c=>{const d=await r({engagement_ids:c.engagements,feature_name:c.name,feature_roles:n.map(({value:u})=>({is_enabled:c.userRoles.includes(u),role_name:u})),parent:c.parent});return"error"in d?{success:!1,error:JSON.stringify(d.error)}:{success:!0,error:null}};return a.jsxs($,{"data-testid":"feature-management:page:container",direction:"column",gap:5,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(ho,{loading:e}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(Xt,{title:"Feature Management"}),s&&a.jsx(re,{"data-testid":"feature-management:create-feature:button",variant:"contained",onClick:i,children:"Create New Feature"})]}),a.jsxs(T,{children:[a.jsx(AY,{}),a.jsx(HG,{}),a.jsx(vY,{onClose:o,handleSubmit:l})]})]})},Zb={editRoles:[],editSubscriptions:[],gridApiRef:void 0,newFeatureFormOpen:!1},RY=(e,t)=>t?.type==="clearEdits"?{...e,editRoles:Zb.editRoles,editSubscriptions:Zb.editSubscriptions}:t?.type?{...e,[t.type]:t.value}:{...e},NY=({isLoading:e,featureManagementData:t})=>{const[n,r]=m.useReducer(RY,Zb),{editRoles:s,editSubscriptions:i,gridApiRef:o}=n,l=m.useCallback(({field:u,id:p,isEnabled:h,row:f})=>{const g={id:p,isEnabled:h},x=uk(s,g);r({type:"editRoles",value:x});const b=VG({field:u,newEdit:g,row:f});o&&o.current.updateRows([b])},[s,o]),c=m.useCallback(({id:u,isEnabled:p,row:h})=>{const g=uk(i,{id:u,isEnabled:p});r({type:"editSubscriptions",value:g});const x={...h,isEnabled:p};o&&o.current.updateRows([x])},[i,o]),d=m.useMemo(()=>({dispatch:r,featureManagementData:t,handleClickCheckbox:l,handleClickSwitch:c,isLoading:e,state:n}),[t,l,c,e,n]);return a.jsx(rR.Provider,{value:d,children:a.jsx(MY,{})})},OY=()=>{const{engagementId:e}=pe(),{data:t=IB,isLoading:n}=N5(e);return a.jsx(NY,{isLoading:n,featureManagementData:t})},PY="/assets/auth-background-ICLnBOh1.png",LY=()=>{const e=ct(),t=Hv(),{checkSession:n,initialLandingPath:r,setInitialLandingPath:s,supportLink:i,userLoading:o}=jt(),l=lC(),{companyName:c,companyLogo:d,companyLogoDark:u}=hs,{isDarkMode:p,toggleDarkMode:h}=VD(),{palette:f}=Re(),g=f.name==="plusco",x=g?Lb:d,b=g?$h:u,y=g?Fb:c,v=m.useCallback(()=>{!o&&e()&&(t(r),s("/"),n())},[n,r,e,t,s,o]),C=m.useCallback(D=>
18cC.parse({username:D.username,userId:D.userId,signInDetails:D.signInDetails,session:D.session}),[]),{onSignIn:w,onConfirmMfa:S,onForgotPasswordRequest:E,onForgotPasswordSubmit:k,onNewPasswordSubmit:j,onRegisterPhone:_}=e4({onAuthComplete:v,setUserState:l,parseUser:C,isMounted:e});return a.jsx(DB,{backgroundImage:g?void 0:PY,companyLogo:x,companyLogoDark:b,companyName:y,isDarkMode:p,isPluscoDomain:g,onConfirmMfa:S,onForgotPasswordRequest:E,onForgotPasswordSubmit:k,onNewPasswordSubmit:j,onRegisterPhone:_,onSignIn:w,onToggleDarkMode:h,supportLink:i})},hR={attribution:"MEVO_ATTRIBUTION",audience:"MEVO_AUDIENCE",chatbot:"MEVO_CHATBOT",chatbotFeedback:"MEVO_CHATBOT_FEEDBACK",createPlan:"MEVO_NEWPLAN",dashboards:"MEVO_DASHBOARDS",dataConnections:"MEVO_DATACONNECTIONS",dataSource:"MEVO_DATASOURCE",dataVerification:"MEVO_DATA_VERIFICATION",machineLearningKpi:"MEVO_MACHINELEARNING_KPI",myPlans:"MEVO_MYPLANS",overview:"MEVO_OVERVIEW",planResults:"MEVO_PLANRESULTS",pageVisit:"MEVO_PAGEVISIT",queryStudio:"MEVO_QUERY_STUDIO",reporting:"MEVO_REPORTING"},FY=()=>{const{pathname:e}=es(),{engagementId:t}=pe(),{mpTrack:n}=tr(),[r,s]=m.useState();m.useEffect(()=>{const i=e.replace(/\/$/,""),o={engagementId:t,path:i};t&&i&&!Kn(o,r)&&(n(hR.pageVisit,{actionData:{path:i}}),s(o))},[t,n,e,r])},xk=()=>a.jsxs(T,{sx:{alignItems:"center",color:"text.secondary",display:"flex",flexDirection:"row",gap:2,height:"100vh",justifyContent:"center"},children:[a.jsx(I,{variant:"h4",children:"Signing you in..."}),a.jsx(Ze,{size:25})]}),$Y=()=>a.jsx(T,{sx:{position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center"}}),zY=m.createContext(null),Yg={didCatch:!1,error:null};class BY extends m.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=Yg}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:i,reason:"imperative-api"}),this.setState(Yg)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&UY(t.resetKeys,s)){var i,o;(i=(o=this.props).onReset)===null||i===void 0||i.call(o,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(Yg)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:i,error:o}=this.state;let l=t;if(i){const c={error:o,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")l=n(c);else if(r)l=m.createElement(r,c);else if(s===null||m.isValidElement(s))l=s;else throw o}return m.createElement(zY.Provider,{value:{didCatch:i,error:o,resetErrorBoundary:this.resetErrorBoundary}},l)}}function UY(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}const fR=m.createContext(null),Wr=()=>m.useContext(fR),bk=e=>{const t=m.useRef();return m.useEffect(()=>{t.current=e}),[t.current,e]},VY=e=>n=>{const r=e.current,[s,i]=m.useState(()=>r.getSnapshot(n)),o=m.useCallback(l=>{i(l)},[]);return m.useEffect(()=>r.subscribe(n,o),[n,r,o]),s},WY=e=>({editingMetaData:!1,historyOpen:!1,isFullScreen:!1,isOpen:!1,unreadMessages:new Map,...e}),HY=(e,t)=>{if(t.type==="addUnreadMessage"){if(e.isOpen&&t.currentSessionId===t.sessionId)return e;const n=e.unreadMessages.get(t.sessionId)??0,r=new Map(e.unreadMessages);return r.set(t.sessionId,n+1),{...e,unreadMessages:r}}if(t.type==="removeUnreadMessage"){const n=new Map(e.unreadMessages);return n.delete(t.value),{...e,unreadMessages:n}}return t.type in e?{...e,[t.type]:t.value}:e},qY="temp_",yk=e=>!e||e.startsWith(qY),GY=(e,t)=>yk(e)&&!yk(t);class Vo{static instance;subscribers;constructor(){this.subscribers=new Map}static getInstance(){return Vo.instance||(Vo.instance=new Vo),Vo.instance}subscribe(t,n){return this.subscribers.has(t)||this.subscribers.set(t,new Set),this.subscribers.get(t).add(n),()=>{const r=this.subscribers.get(t);r&&(r.delete(n),r.size===0&&this.subscribers.delete(t))}}emit(t,n){const r=this.subscribers.get(t);r&&r.forEach(s=>s(n))}}const Fm=()=>{const e=Vo.getInstance(),t=m.useCallback((o,l)=>e.subscribe(o,l),[e]),n=m.useCallback((o,l)=>{e.emit(o,l)},[e]),r=m.useCallback(o=>{n("SEND_PROMPT",o)},[n]),s=m.useCallback(o=>{n("LOAD_SESSION",o)},[n]),i=m.useCallback(o=>{n("SESSION_STARTED",o)},[n]);return{loadSession:s,notifySessionStarted:i,sendPrompt:r,subscribe:t}},YY=U.object({event:U.literal("connected"),session_id:U.string()}),KY=U.object({event:U.literal("processing"),prompt:U.string()}),QY=U.object({event:U.literal("connection_timeout")}),JY=U.object({event:U.literal("pong"),timestamp:U.number()}),XY=U.object({event:U.literal("keepalive"),timestamp:U.number()}),ZY=U.object({event:U.literal("error"),message:U.string().default("Unknown error")}),eK=U.object({event:U.literal("thinking"),text:U.string()}),tK=U.object({event:U.literal("chunk"),text:U.string()}),nK=U.object({event:U.literal("agent_delegating"),agent:U.string(),id:U.string(),tool:U.string()}),rK=U.object({event:U.literal("tool_start"),id:U.string(),tool:U.string()}),sK=U.object({event:U.literal("tool_complete"),tool:U.string(),id:U.string(),success:U.boolean(),error:U.string().optional()}),iK=U.object({event:U.literal("sub_agent_chunk"),agent:U.string(),text:U.string()}),aK=U.object({event:U.literal("sub_agent_tool_start"),agent:U.string(),tool:U.string(),tool_id:U.string()}),oK=U.object({event:U.literal("sub_agent_tool_complete"),agent:U.string(),tool:U.string(),tool_id:U.string(),success:U.boolean()}),lK=U.object({event:U.literal("complete"),files:U.array(U.object({mime_type:U.string(),name:U.string(),uri:U.string()})).optional(),response:U.string(),langfuse_trace_id:U.string().optional()}),cK=U.object({event:U.literal("job_created"),job_id:U.string(),prompt_preview:U.string()}),dK=U.object({event:U.literal("job_complete"),job_id:U.string(),response:U.string(),files:U.array(U.object({mime_type:U.string(),name:U.string(),uri:U.string()})).optional(),enabled_features:U.array(U.string()).optional(),langfuse_trace_id:U.string().optional(),prompt_preview:U.string().optional()}),uK=U.object({event:U.literal("job_error"),job_id:U.string(),message:U.string()}),pK=U.object({event:U.literal("job_cancelled"),job_id:U.string()}),hK=U.object({event:U.literal("canvas_created"),document_id:U.string(),version_id:U.string(),artifact_type:WD,title:U.string(),session_id:U.string()}),fK=U.object({event:U.literal("canvas_chunk"),document_id:U.string(),text:U.string()}),mK=U.object({event:U.literal("canvas_complete"),document_id:U.string(),version_id:U.string(),artifact_type:WD,markdown:U.string().optional(),summary:U.string().optional()}),gK=U.object({event:U.literal("canvas_error"),document_id:U.string().optional(),message:U.string()}),xK=U.discriminatedUnion("event",[YY,KY,QY,JY,XY,ZY,eK,tK,nK,rK,sK,iK,aK,oK,lK,cK,dK,uK,pK,hK,fK,mK,gK]).transform(AB);
18class qt extends Error{step;errorCode;constructor(t,n,r){super(n),this.name="UploadError",this.step=t,this.errorCode=r?.errorCode,r?.cause!==void 0&&(this.cause=r.cause)}}const bK=3e4,Kg=3,yK=1e3,vK=e=>e!==null&&typeof e=="object"&&"event"in e?e:null,CK=e=>typeof e=="object"&&e!==null,Qg=e=>typeof e=="string"?e:void 0,lp=(e,t)=>{e.splice(0,e.length).forEach(r=>t===void 0?r.resolve():r.reject(t))};class Ia{ws=null;keepaliveInterval=null;reconnectAttempt=0;isCleaningUp=!1;shouldReconnect=!0;config;callbacks;isFirstMessage=!0;pendingPrompts=[];pendingFeedback=[];isFeedbackInFlight=!1;pendingRequests=new Map;static REQUEST_TIMEOUT_MS=3e4;static AUTH_TIMEOUT_MS=15e3;authState="none";authPromise=null;openWaiters=[];authWaiters=[];constructor(t,n){this.config=t,this.callbacks=n}connect(){if(this.isCleaningUp||!this.shouldReconnect||this.ws&&this.ws.readyState!==WebSocket.CLOSED)return;const{websocketUrl:t}=this.config;this.callbacks.onConnectionStateChange("connecting");try{this.ws=new WebSocket(t)}catch(n){We(n),this.callbacks.onConnectionStateChange("error");return}this.ws.onopen=this.handleOpen.bind(this),this.ws.onmessage=this.handleMessage.bind(this),this.ws.onerror=n=>{We(n)},this.ws.onclose=this.handleClose.bind(this)}sendMessage(t,n={}){if(this.callbacks.onStreamStart(),!this.ws||this.ws.readyState!==WebSocket.OPEN){this.pendingPrompts.push({prompt:t,options:n}),this.connect();return}this.sendPrompt(t,n)}sendPrompt(t,{jsonContext:n}={}){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){We(new Error("Cannot send - WebSocket not open"));return}const{sessionId:r,engagementId:s,token:i}=this.config;let o;this.isFirstMessage?(o={prompt:t,session_id:r,engagement_id:s,authorization:`Bearer ${i}`},this.isFirstMessage=!1):o={prompt:t},n&&(o.json_context=n);try{this.ws.send(JSON.stringify(o))}catch(l){We(l),this.callbacks.onError({message:"Failed to send message"})}}sendFeedback(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.pendingFeedback.push(t),this.shouldReconnect=!0,this.connect();return}this.sendFeedbackMessage(t)}sendFeedbackMessage(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){We(new Error("Cannot send feedback - WebSocket not open"));return}try{this.isFeedbackInFlight=!0,this.ws.send(JSON.stringify({prompt:t,is_feedback:!0}))}catch(n){this.isFeedbackInFlight=!1,We(n)}}isConnected(){return this.ws?.readyState===WebSocket.OPEN}static waitFor(t,n,r){return new Promise((s,i)=>{let o;const l={resolve:()=>{clearTimeout(o),s()},reject:c=>{clearTimeout(o),i(c)}};o=setTimeout(()=>{const c=t.indexOf(l);c>=0&&t.splice(c,1),i(new qt("initiate",r,{errorCode:"AUTH_TIMEOUT"}))},n),t.push(l)})}async authenticate(){if(!(this.authState==="authenticated"&&this.isConnected()))return this.authState==="authenticated"&&(this.authState="none",this.authPromise=null),this.authPromise||(this.authPromise=this.performAuthentication().finally(()=>{this.authState!=="authenticated"&&(this.authPromise=null)})),this.authPromise}async performAuthentication(){if(this.isConnected()||(this.shouldReconnect=!0,this.isCleaningUp=!1,this.connect(),await Ia.waitFor(this.openWaiters,Ia.AUTH_TIMEOUT_MS,"WebSocket did not open")),!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new qt("initiate","WebSocket not connected");const{sessionId:t,engagementId:n,token:r}=this.config,s=Ia.waitFor(this.authWaiters,Ia.AUTH_TIMEOUT_MS,"Authentication timed out");this.ws.send(JSON.stringify({type:"authenticate",session_id:t,engagement_id:n,authorization:`Bearer ${r}`})),this.isFirstMessage=!1;try{await s}catch(i){throw this.isFirstMessage=!0,i}this.authState="authenticated"}async request(t,n){try{await this.authenticate()}catch(s){throw s instanceof qt?new qt(n,s.message,{errorCode:s.errorCode,cause:s}):s}const r=crypto.randomUUID();return new Promise((s,i)=>{const o=setTimeout(()=>{this.pendingRequests.delete(r),i(new qt(n,"Upload request timed out",{errorCode:"REQUEST_TIMEOUT"}))},Ia.REQUEST_TIMEOUT_MS);if(this.pendingRequests.set(r,{step:n,resolve:l=>{clearTimeout(o),s(l)},reject:l=>{clearTimeout(o),i(l)}}),!this.ws||this.ws.readyState!==WebSocket.OPEN){this.pendingRequests.delete(r),clearTimeout(o),i(new qt(n,"WebSocket not connected"));return}try{this.ws.send(JSON.stringify({...t,request_id:r}))}catch(l){this.pendingRequests.delete(r),clearTimeout(o),i(new qt(n,"Failed to send upload request",{cause:l}))}})}rejectAllPendingRequests(t){for(const n of this.pendingRequests.values())n.reject(new qt(n.step,t));this.pendingRequests.clear(),this.authState="none",this.authPromise=null,lp(this.authWaiters,new qt("initiate",t)),lp(this.openWaiters,new qt("initiate",t))}disconnect(){if(this.isCleaningUp=!0,this.shouldReconnect=!1,this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null),this.rejectAllPendingRequests("WebSocket disconnected"),this.ws){if(this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"disconnect"}))}catch{}this.ws.close(),this.ws=null}this.callbacks.onConnectionStateChange("disconnected")}handleOpen(){if(this.reconnectAttempt=0,this.startKeepalive(),this.callbacks.onConnectionStateChange("connected"),lp(this.openWaiters),this.isFirstMessage||this.authState==="authenticated"){this.flushQueuedMessages();return}this.authenticate().then(()=>{this.flushQueuedMessages()}).catch(t=>{We(t),this.pendingPrompts=[],this.callbacks.onError({message:"Connection lost. Please try sending your message again."})})}flushQueuedMessages(){for(;this.pendingPrompts.length>0;){const t=this.pendingPrompts.shift();t&&this.sendPrompt(t.prompt,t.options)}for(;this.pendingFeedback.length>0;){const t=this.pendingFeedback.shift();t&&this.sendFeedbackMessage(t)}}handleMessage(t){try{const n=JSON.parse(t.data);if(CK(n)){const s=Qg(n.request_id),i=s?this.pendingRequests.get(s):void 0;if(s&&i){this.pendingRequests.delete(s),n.type==="upload_error"?i.reject(new qt(i.step,Qg(n.error)??"Upload failed",{errorCode:Qg(n.error_code)})):i.resolve(n);return}}const r=vK(n);if(r){const s=xK.safeParse(r);if(!s.success){We(s.error);return}const i=s.data;if(i.event==="connected"&&(this.authState="authenticated",lp(this.authWaiters)),this.isFeedbackInFlight){(i.event==="complete"||i.event==="error")&&(this.isFeedbackInFlight=!1);return}this.callbacks.onProcessEvent(i)}}catch(n){We(n)}}handleClose(t){if(this.isCleaningUp)return;this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null);const n=this.shouldReconnect&&!t.wasClean&&t.code!==1e3&&t.code!==4001&&t.code!==4003&&this.reconnectAttempt<Kg;if(this.rejectAllPendingRequests(n?"WebSocket reconnecting":"WebSocket disconnected"),n){this.reconnectAttempt+=1;const r=yK*2**(this.reconnectAttempt-1);this.callbacks.onConnectionStateChange("reconnecting"),setTimeout(()=>{!this.isCleaningUp&&this.shouldReconnect&&this.connect()},r)}else if(this.callbacks.onConnectionStateChange("disconnected"),this.reconnectAttempt>=Kg||this.pendingPrompts.length>0){const r=this.reconnectAttempt>=Kg?"Connection lost after multiple attempts. Please try sending your message again.":"Connection lost. Please try sending your message again.";this.pendingPrompts=[],this.callbacks.onError({message:r})}}startKeepalive(){this.keepaliveInterval&&clearInterval(this.keepaliveInterval),this.keepaliveInterval=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))},bK)}}const rs=new Map;class zi{static doesSessionExist(t){const n=rs.get(t);return n?n.isConnected()?!0:(n.disconnect(),rs.delete(t),!1):!1}static getSession(t){const n=rs.get(t);return n?n.isConnected()?n:(n.disconnect(),rs.delete(t),null):null}static peekSession(t){return rs.get(t)??null}static startSession(t,n){const r=rs.get(t.sessionId);r&&(r.disconnect(),rs.delete(t.sessionId));const s=new Ia(t,n);return rs.set(t.sessionId,s),s}static endSession(t){const n=rs.get(t);n&&(n.disconnect(),rs.delete(t))}static sendFeedback(t,n){const r=rs.get(t);return r?(r.sendFeedback(n),!0):!1}}const wK=560,vk=280,$C=760,Od=32,mR=1,SK=1301,jK=1302,gR=1305,xR=1310,ey="provide_positive_feedback",ty="provide_negative_feedback",Ck=({activeTools:e=[],backgroundJobs:t=[],completedTools:n=[],history:r=[],...s}={})=>({accumulatedText:"",activeTools:e,backgroundJobs:t,completedTools:n,connectionState:"disconnected",error:null,history:r,loading:null,isStreaming:!1,sessionId:"",thinking:"",...s}),kK=e=>{const t=Z();return e.isAfter(t,"day")?null:e.isSame(t,"day")?"Today":e.isSame(t.subtract(1,"day"),"day")?"Yesterday":t.diff(e,"day")<=3||e.isSame(t,"week")?e.format("dddd"):e.isSame(t.subtract(1,"week"),"week")?"Last Week":e.isSame(t,"year")?e.format("MMMM"):e.format("YYYY")},wk=e=>`${`${Z().format("l")} - ${e}`.slice(0,37)}...`,EK=e=>e.filter(t=>t.role!=="system"&&!t.content.every(({text:n,toolUse:r})=>!r&&(!n||n==="[blank text]"))&&!t.content.some(n=>n.text?.startsWith(ey)||n.text?.startsWith(ty)||n.toolUse?.name.startsWith(ey)||n.toolUse?.name.startsWith(ty)));class Sk{p_initialized=!1;p_wsSession=null;p_accumulatedText="";p_activeTools=[];p_completedTools=[];p_connectionState="disconnected";p_error=null;p_backgroundJobs=[];p_history=[];p_isStreaming=!1;p_loading=null;p_sessionId="";p_thinking=null;notify;notifyAll;getHistory;getWebSocketConfig;initChat;isCurrentChat;onUpdateSessionId;addUnreadMessage;onCanvasEvent;onJobNotification;constructor({addUnreadMessage:t,getHistory:n,getWebSocketConfig:r,initChat:s,isCurrentChat:i,notify:o,notifyAll:l,onCanvasEvent:c,onJobNotification:d,onUpdateSessionId:u,sessionId:p}){this.onUpdateSessionId=u,this.notify=o,this.notifyAll=l,this.onCanvasEvent=c,this.onJobNotification=d,this.isCurrentChat=i,this.getHistory=n,this.getWebSocketConfig=r,this.initChat=s,this.addUnreadMessage=t,this.sessionId=p,this.initialized=!1,this.wsSession=null,this.accumulatedText="",this.completedTools=[],this.connectionState="disconnected",this.activeTools=[],this.backgroundJobs=[],this.error=null,this.history=[],this.isStreaming=!1,this.loading=null,this.thinking=null}async loadPreviousSession(){this.loading="history";const t=await this.getHistory({sessionId:this.sessionId});this.history=EK(t),this.loading=null}async sendPrompt(t,n){const r={content:[{text:t}],messageId:crypto.randomUUID(),role:"user",feedback:null};this.history=this.history.length?[...this.history,r]:[r],this.wsSession?this.wsSession.sendMessage(t,n):this.sessionId.startsWith("temp_")?this.initNewChat(t,n):this.initExistingChat(t,n)}disconnect(){this.wsSession&&(this.wsSession.disconnect(),this.wsSession=null)}async initNewChat(t,n){this.loading="init";const r=await this.initChat({title:wk(t)});if(this.loading=null,!r){We("Failed to initialize chat");return}const s=this.sessionId,i=r.sessionId;this.sessionId=i,this.onUpdateSessionId({nextSessionId:i,prevSessionId:s});const o=zi.startSession(r,this.callbacks);this.wsSession=o,o.sendMessage(t,n)}async ensureAuthenticatedSession(t){const n=zi.getSession(this.sessionId);if(n)return this.wsSession=n,await n.authenticate(),n;const r=this.sessionId.startsWith("temp_");this.loading=r?"init":"connection";try{const s=r?await this.initChat({title:wk(t)}):await this.getWebSocketConfig({sessionId:this.sessionId});if(!s)return We(new Error(r?"Failed to initialize chat for upload":"Failed to get websocket config for upload")),null;if(r){const o=this.sessionId,l=s.sessionId;this.sessionId=l,this.onUpdateSessionId({nextSessionId:l,prevSessionId:o})}const i=zi.startSession(s,this.callbacks);return this.wsSession=i,await i.authenticate(),i}finally{this.loading=null}}async initExistingChat(t,n){const r=zi.getSession(this.sessionId);if(r)this.wsSession=r,r.sendMessage(t,n);else{this.loading="connection";const s=await this.getWebSocketConfig({sessionId:this.sessionId});if(this.loading=null,s){const i=zi.startSession(s,this.callbacks);this.wsSession=i,i.sendMessage(t,n)}else We("Failed to get websocket config")}}setChatState(){this.notifyAll(this.getState())}addFeedbackToHistory({feedback:t,traceId:n}){const r=this.history.map(s=>s.role==="assistant"&&s.traceId===n?{...s,feedback:t}:s);this.history=r}set wsSession(t){this.p_wsSession=t}get wsSession(){return this.p_wsSession}set loading(t){this.isCurrentChat(this.sessionId)&&this.notify("loading",t),this.p_loading=t}get loading(){return this.p_loading}getState(){return{accumulatedText:this.accumulatedText,activeTools:this.activeTools,backgroundJobs:this.backgroundJobs,completedTools:this.completedTools,connectionState:this.connectionState,error:this.error,history:this.history,isStreaming:this.isStreaming,loading:this.loading,sessionId:this.sessionId,thinking:this.thinking}}set sessionId(t){this.p_sessionId=t}get sessionId(){return this.p_sessionId}set initialized(t){this.p_initialized=t}get initialized(){return this.p_initialized}get accumulatedText(){return this.p_accumulatedText}set accumulatedText(t){this.isCurrentChat(this.sessionId)&&this.notify("accumulatedText",t),this.p_accumulatedText=t}set completedTools(t){this.isCurrentChat(this.sessionId)&&this.notify("completedTools",t),this.p_completedTools=t}get completedTools(){return this.p_completedTools}set connectionState(t){this.isCurrentChat(this.sessionId)&&this.notify("connectionState",t),this.p_connectionState=t}
18get connectionState(){return this.p_connectionState}set activeTools(t){this.isCurrentChat(this.sessionId)&&this.notify("activeTools",t),this.p_activeTools=t}get activeTools(){return this.p_activeTools}set error(t){this.isCurrentChat(this.sessionId)&&this.notify("error",t),this.p_error=t}get error(){return this.p_error}set backgroundJobs(t){this.isCurrentChat(this.sessionId)&&this.notify("backgroundJobs",t),this.p_backgroundJobs=t}get backgroundJobs(){return this.p_backgroundJobs}set history(t){this.isCurrentChat(this.sessionId)&&this.notify("history",t),this.p_history=t}get history(){return this.p_history}set isStreaming(t){this.isCurrentChat(this.sessionId)&&this.notify("isStreaming",t),this.p_isStreaming=t}get isStreaming(){return this.p_isStreaming}set thinking(t){this.isCurrentChat(this.sessionId)&&this.notify("thinking",t),this.p_thinking=t}get thinking(){return this.p_thinking}onProcessEvent(t){switch(t.event){case"chunk":{if(this.isStreaming=!0,this.completedTools.length>0){const n=this.accumulatedText?{text:this.accumulatedText}:null,r=this.completedTools.map(o=>({toolUse:{name:o.name}})),s=n?[n,...r]:r,i={messageId:crypto.randomUUID(),content:s,role:"assistant",feedback:null};this.history=[...this.history,i],this.completedTools=[],this.accumulatedText=t.text}else this.accumulatedText+=t.text;break}case"complete":{const n={text:t.response};t.files&&(n.files=t.files.map(s=>({name:s.name,s3_url:s.uri,type:s.mime_type})));const r={messageId:crypto.randomUUID(),content:[n],role:"assistant",feedback:null};t.langfuseTraceId&&(r.traceId=t.langfuseTraceId),this.thinking&&(r.thinking=this.thinking),this.history=[...this.history,r],this.activeTools=[],this.completedTools=[],this.addUnreadMessage(this.sessionId),this.isStreaming=!1,this.accumulatedText="",this.thinking=null;break}case"thinking":{this.thinking=(this.thinking??"")+t.text;break}case"tool_start":{const n={id:t.id,name:t.tool};this.activeTools=[...this.activeTools,n];break}case"tool_complete":{const n={id:t.id,name:t.tool,success:t.success};t.error&&(n.error=t.error),this.completedTools=[...this.completedTools,n],this.activeTools.find(s=>s.id===t.id)&&(this.activeTools=this.activeTools.filter(s=>s.id!==t.id));break}case"agent_delegating":{const n={agent:t.agent,id:t.id,name:t.tool};this.activeTools=[...this.activeTools,n];break}case"sub_agent_chunk":case"sub_agent_tool_start":case"sub_agent_tool_complete":break;case"canvas_created":case"canvas_complete":case"canvas_error":this.onCanvasEvent?.(t);break;case"canvas_chunk":break;case"job_created":{if(this.backgroundJobs.some(s=>s.jobId===t.jobId))break;this.finalizeAccumulatedContent();const n={messageId:crypto.randomUUID(),content:[{text:t.promptPreview}],role:"assistant",feedback:null,createdAt:Z().valueOf(),variant:"tombstone",jobId:t.jobId,promptPreview:t.promptPreview};this.history=[...this.history,n];const r={jobId:t.jobId,promptPreview:t.promptPreview,status:"running",createdAt:Z().valueOf()};this.backgroundJobs=[...this.backgroundJobs,r],this.addUnreadMessage(this.sessionId),this.isStreaming=!1;break}case"job_complete":{const n=this.backgroundJobs.find(o=>o.jobId===t.jobId),r=n?.promptPreview??t.promptPreview??"",s={text:t.response};t.files&&(s.files=t.files.map(o=>({name:o.name,s3_url:o.uri,type:o.mime_type})));const i={messageId:t.jobId,content:[s],role:"assistant",feedback:null,variant:"job-result",jobId:t.jobId,promptPreview:r};t.langfuseTraceId&&(i.traceId=t.langfuseTraceId),this.history=[...this.history,i],n?this.backgroundJobs=this.backgroundJobs.map(o=>o.jobId===t.jobId?{...o,status:"complete",completedAt:Z().valueOf()}:o):this.backgroundJobs=[...this.backgroundJobs,{jobId:t.jobId,promptPreview:r,status:"complete",createdAt:Z().valueOf(),completedAt:Z().valueOf()}],this.addUnreadMessage(this.sessionId),this.onJobNotification?.({jobId:t.jobId,promptPreview:r,status:"complete"});break}case"job_error":{const n=this.backgroundJobs.find(i=>i.jobId===t.jobId),r=n?.promptPreview??"",s={messageId:t.jobId,content:[{text:t.message}],role:"assistant",feedback:null,variant:"job-error",jobId:t.jobId,promptPreview:r};this.history=[...this.history,s],n?this.backgroundJobs=this.backgroundJobs.map(i=>i.jobId===t.jobId?{...i,status:"error",completedAt:Z().valueOf()}:i):this.backgroundJobs=[...this.backgroundJobs,{jobId:t.jobId,promptPreview:r,status:"error",createdAt:Z().valueOf(),completedAt:Z().valueOf()}],this.addUnreadMessage(this.sessionId),this.onJobNotification?.({jobId:t.jobId,promptPreview:r,status:"error"});break}case"job_cancelled":{this.backgroundJobs=this.backgroundJobs.map(n=>n.jobId===t.jobId?{...n,status:"cancelled",completedAt:Z().valueOf()}:n);break}}}finalizeAccumulatedContent(){const t=[];if(this.accumulatedText&&t.push({text:this.accumulatedText}
18),this.completedTools.forEach(({name:n})=>{t.push({toolUse:{name:n}})}),this.activeTools.forEach(({name:n})=>{t.push({toolUse:{name:n}})}),t.length>0){const n={messageId:crypto.randomUUID(),content:t,role:"assistant",feedback:null};this.thinking&&(n.thinking=this.thinking),this.history=[...this.history,n]}this.accumulatedText="",this.activeTools=[],this.completedTools=[],this.thinking=null}get callbacks(){return{onConnectionStateChange:t=>{this.connectionState=t},onError:t=>{We(t),this.error=t},onStreamStart:()=>{this.isStreaming=!0},onProcessEvent:this.onProcessEvent.bind(this)}}}class _K{p_currentSessionId="";p_state;conversationDispatch;sessions;subscribers;getChatHistory;getWebSocketConfig;initChat;onCanvasEvent;onJobNotification;constructor({conversationDispatch:t,getChatHistory:n,getWebSocketConfig:r,initChat:s,initialCurrentChat:i,onCanvasEvent:o,onJobNotification:l}){this.sessions=new Map,this.conversationDispatch=t,this.getChatHistory=n,this.getWebSocketConfig=r,this.initChat=s,this.onCanvasEvent=o,this.onJobNotification=l,this.p_state=Ck(i),this.subscribers={accumulatedText:new Set,activeTools:new Set,backgroundJobs:new Set,completedTools:new Set,connectionState:new Set,error:new Set,history:new Set,isStreaming:new Set,loading:new Set,sessionId:new Set,thinking:new Set},this.onUpdateSessionId=this.onUpdateSessionId.bind(this),this.addUnreadMessage=this.addUnreadMessage.bind(this),this.notify=this.notify.bind(this),this.notifyAll=this.notifyAll.bind(this)}get currentSessionId(){return this.p_currentSessionId}set currentSessionId(t){t!==this.p_currentSessionId&&(this.p_currentSessionId=t,this.notify("sessionId",t))}getSnapshot(t){return this.p_state[t]}subscribersFor(t){return this.subscribers[t]}subscribe(t,n){const r=this.subscribersFor(t);return r.add(n),()=>{r.delete(n)}}notify(t,n){this.p_state={...this.p_state,[t]:n},this.subscribersFor(t).forEach(s=>s(n))}notifyAll(t){this.p_state=t,Object.keys(t).forEach(n=>{this.subscribersFor(n).forEach(s=>s(t[n]))})}resetState(){this.notifyAll(Ck())}addUnreadMessage(t){this.conversationDispatch({type:"addUnreadMessage",sessionId:t,currentSessionId:this.currentSessionId})}loadPreviousSession(t){this.currentSessionId=t;const n=this.sessions.get(t);if(n)n.setChatState();else{const r=new Sk({addUnreadMessage:this.addUnreadMessage,getHistory:this.getChatHistory,getWebSocketConfig:this.getWebSocketConfig,initChat:this.initChat,isCurrentChat:this.isCurrentChat.bind(this),notify:this.notify,notifyAll:this.notifyAll,onCanvasEvent:this.onCanvasEvent,onJobNotification:this.onJobNotification,onUpdateSessionId:this.onUpdateSessionId,sessionId:t});this.sessions.set(t,r),r.loadPreviousSession()}}sendPrompt({prompt:t,sessionId:n,options:r}){this.currentSessionId=n,this.getOrCreateSession(n).sendPrompt(t,r)}getOrCreateSession(t){const n=this.sessions.get(t);if(n)return n;const r=new Sk({addUnreadMessage:this.addUnreadMessage,getHistory:this.getChatHistory,getWebSocketConfig:this.getWebSocketConfig,initChat:this.initChat,isCurrentChat:this.isCurrentChat.bind(this),notify:this.notify,notifyAll:this.notifyAll,onCanvasEvent:this.onCanvasEvent,onJobNotification:this.onJobNotification,onUpdateSessionId:this.onUpdateSessionId,sessionId:t});return this.sessions.set(t,r),r}async ensureUploadSession({sessionId:t,title:n}){const r=t||`temp_${crypto.randomUUID()}`;this.currentSessionId=r;const s=this.getOrCreateSession(r),i=await s.ensureAuthenticatedSession(n);return i?{session:i,sessionId:s.sessionId}:null}removeSession(t){t===this.currentSessionId&&(this.currentSessionId="",this.resetState());const n=this.sessions.get(t);n&&(n.disconnect(),this.sessions.delete(t)),zi.endSession(t)}openNewChat(){this.resetState(),this.currentSessionId=""}sendFeedback({comment:t="",feedback:n,sessionId:r,topics:s,traceId:i}){const o=n==="positive"?ey:ty,l=s?.length?`${s.join(", ")} ${t.trim()}`:t,c=l?`${o} ${i} ${l}`:`${o} ${i}`;zi.sendFeedback(r,c);const d=this.sessions.get(r);d&&d.addFeedbackToHistory({feedback:n,traceId:i})}onUpdateSessionId({nextSessionId:t,prevSessionId:n}){if(n===t)return;const r=this.sessions.get(n);if(!r){We(new Error("Previous session not found"));return}this.sessions.set(t,r),this.sessions.delete(n),n===this.currentSessionId&&(this.currentSessionId=t,r.setChatState())}isCurrentChat(t){return t===this.currentSessionId}}const TK=({conversationDispatch:e,getChatHistory:t,getConfigForSession:n,initialCurrentChat:r,initializeChat:s,onCanvasEvent:i,onJobNotification:o,onUpdateMeta:l})=>{const c=m.useRef(null);
18c.current||(c.current=new _K({conversationDispatch:e,getChatHistory:t,getWebSocketConfig:n,initChat:s,initialCurrentChat:r,onCanvasEvent:i,onJobNotification:o}));const[d,u]=m.useState([]),p=m.useRef(d),h=m.useCallback(k=>{p.current=k(p.current),u(p.current)},[]),f=m.useCallback(()=>{h(()=>[])},[h]),g=m.useCallback(()=>{f(),c.current.openNewChat()},[f]),x=m.useCallback(k=>{k!==c.current.currentSessionId&&(f(),e({type:"removeUnreadMessage",value:k}),c.current.loadPreviousSession(k))},[f,e]),b=m.useCallback(async({nextPinned:k,sessionId:j})=>{await l({nextPinned:k,sessionId:j})},[l]),y=m.useCallback(async({nextTitle:k,sessionId:j})=>{await l({nextTitle:k,sessionId:j})},[l]),v=m.useCallback(async({sessionId:k})=>{const j=k===c.current.currentSessionId;c.current.removeSession(k),j&&f(),await l({sessionId:k,nextActive:!1})},[f,l]),C=m.useCallback((k,j)=>{h(_=>[..._,{displayName:j,fileContext:k}])},[h]),w=m.useCallback(k=>{h(j=>j.filter(_=>_.fileContext.upload_id!==k))},[h]),S=m.useCallback(({prompt:k,sessionId:j,options:_,attachPending:D})=>{const M=j||`temp_${crypto.randomUUID()}`,N=p.current,O=D===!0&&N.length>0;c.current.sendPrompt({options:O?{..._,jsonContext:[..._?.jsonContext??[],...N.map(R=>R.fileContext)]}:_,prompt:k,sessionId:M}),O&&f()},[f]),E=m.useCallback(({comment:k,feedback:j,sessionId:_,topics:D,traceId:M})=>{c.current.sendFeedback({comment:k,feedback:j,sessionId:_,topics:D,traceId:M})},[]);return{addAttachment:C,deleteSession:v,handleOpenNewChat:g,handleSendFeedback:E,handleSendPrompt:S,handleSwitchSession:x,pendingAttachments:d,removeAttachment:w,sessionManagerRef:c,updatePinned:b,updateTitle:y}},IK=({chatExamples:e,chatExamplesLoading:t,children:n,feedbackMpTrack:r,getChatHistory:s,getConfigForSession:i,initialCurrentChat:o,initializeChat:l,initialState:c,llmAssistantName:d,metaData:u,metaDataLoading:p,onCanvasEvent:h,onJobNotification:f,onOpenUI:g,onUpdateMeta:x,shouldRaiseButton:b,username:y})=>{const v=m.useRef(null),[C,w]=m.useReducer(HY,WY(c)),{addAttachment:S,deleteSession:E,handleOpenNewChat:k,handleSendFeedback:j,handleSendPrompt:_,handleSwitchSession:D,pendingAttachments:M,removeAttachment:N,sessionManagerRef:O,updatePinned:R,updateTitle:L}=TK({conversationDispatch:w,getChatHistory:s,getConfigForSession:i,initialCurrentChat:o,initializeChat:l,onCanvasEvent:h,onJobNotification:f,onUpdateMeta:x}),{isOpen:P}=C,{notifySessionStarted:F,subscribe:z}=Fm(),B=m.useMemo(()=>VY(O),[O]),W=m.useCallback(()=>{const K=!P;K&&(g(),w({type:"removeUnreadMessage",value:O.current.currentSessionId})),w({type:"isOpen",value:K})},[P,g,O]),H=m.useCallback(K=>{v.current?.setText(K),v.current?.focus()},[]),V=m.useCallback(K=>{D(K.sessionId),P||W()},[D,W,P]),G=m.useCallback(K=>{_({prompt:K.prompt,sessionId:"",options:K.options}),P||W()},[_,W,P]);m.useEffect(()=>{const K=[z("LOAD_SESSION",V),z("SEND_PROMPT",G)];return()=>K.forEach(ie=>ie())},[V,G,z]),m.useEffect(()=>{const K=O.current;let ie=K.getSnapshot("sessionId");return K.subscribe("sessionId",le=>{const ce=GY(ie,le);ie=le,ce&&F({sessionId:le})})},[F,O]);const X=m.useMemo(()=>({addAttachment:S,chatExamples:e,chatExamplesLoading:t,deleteSession:E,dispatch:w,feedbackMpTrack:r,handleOpenClose:W,handleOpenNewChat:k,handleSendFeedback:j,handleSendPrompt:_,handleSetMessage:H,handleSwitchSession:D,llmAssistantName:d,metaData:u,metaDataLoading:p,pendingAttachments:M,removeAttachment:N,sessionManagerRef:O,
18shouldRaiseButton:b,state:C,textBoxRef:v,updatePinned:R,updateTitle:L,username:y,watch:B}),[S,e,t,E,r,W,k,j,_,H,D,d,u,p,M,N,O,b,C,R,L,y,B]);return a.jsx(fR.Provider,{value:X,children:n})},Jg=rt(Se)(({theme:e})=>({fontWeight:500,color:e.palette.text.secondary,lineHeight:"24px",paddingTop:"8px",paddingBottom:"8px"})),bR=({anchorEl:e,onClickAction:t,onClose:n,open:r,pinned:s})=>a.jsxs(dr,{anchorEl:e,open:r,onClick:n,onClose:n,sx:{zIndex:gR},slotProps:{paper:{sx:{width:128,maxWidth:128,borderRadius:1.5,p:.5}}},children:[a.jsx(Jg,{onClick:()=>{t("rename")},children:"Rename"}),a.jsx(Jg,{onClick:()=>{t("togglePinned")},children:s?"Unpin":"Pin"}),a.jsx(Jg,{onClick:()=>{t("delete")},children:"Delete"})]}),DK=({items:e,disabled:t=!1,label:n="Add files and more"})=>{const[r,s]=m.useState(null),i=!!r,o=()=>s(null);return e.length===0?null:a.jsxs(a.Fragment,{children:[a.jsx(be,{title:n,children:a.jsx(Ie,{"aria-expanded":i,"aria-haspopup":"menu","aria-label":n,disabled:t,onClick:l=>s(l.currentTarget),size:"small",sx:{borderRadius:mR,flexShrink:0,height:Od,width:Od},children:a.jsx(wC,{fontSize:"small"})})}),a.jsx(dr,{anchorEl:r,anchorOrigin:{horizontal:"left",vertical:"top"},onClose:o,open:i,sx:{zIndex:gR},transformOrigin:{horizontal:"left",vertical:"bottom"},children:e.map(l=>{const c=l.active===void 0?{}:{role:"menuitemcheckbox","aria-checked":l.active};return a.jsxs(Se,{disabled:l.disabled,onClick:()=>{l.disabled||(o(),l.onSelect())},...c,children:[a.jsx(kD,{sx:{minWidth:0,mr:.5},children:l.icon}),a.jsx(Kt,{children:l.label}),l.active?a.jsx(iM,{fontSize:"small",sx:{ml:1}}):null]},l.id)})})]})};var ec={},jk;function AK(){if(jk)return ec;jk=1;var e=Pt();Object.defineProperty(ec,"__esModule",{value:!0}),ec.default=void 0;var t=e(Lt()),n=Ot();return ec.default=(0,t.default)((0,n.jsx)("path",{d:"m4 12 1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8z"}),"ArrowUpward"),ec}var MK=AK();const RK=dt(MK),NK=({disabled:e,loading:t,onClick:n})=>a.jsx(Ie,{"aria-label":"Send message",sx:{display:"inline-flex",justifyContent:"center",alignItems:"center",flexShrink:0,width:Od,height:Od,opacity:.6,backgroundColor:t||e?"background.disabled":"background.brand.bold.default","&:hover":{backgroundColor:t||e?"background.disabled":"background.brand.bold.default"},borderRadius:mR},onClick:n,disabled:t||e,children:t?a.jsx(T,{sx:{width:12,height:12,backgroundColor:"icon.disabled",borderRadius:.25}}):a.jsx(RK,{sx:{fontSize:16,color:"common.white",cursor:"pointer"}})});var tc={},kk;function OK(){if(kk)return tc;kk=1;var e=Pt();Object.defineProperty(tc,"__esModule",{value:!0}),tc.default=void 0;var t=e(Lt()),n=Ot();return tc.default=(0,t.default)((0,n.jsx)("path",{d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Close"),tc}var PK=OK();const ji=dt(PK);var nc={},Ek;function LK(){if(Ek)return nc;Ek=1;var e=Pt();Object.defineProperty(nc,"__esModule",{value:!0}),nc.default=void 0;var t=e(Lt()),n=Ot();return nc.default=(0,t.default)((0,n.jsx)("path",{d:"M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zM6 20V4h7v5h5v11z"}),"InsertDriveFileOutlined"),nc}var FK=LK();const $K=dt(FK),zK=({label:e,dismissLabel:t,onDismiss:n,disabled:r=!1})=>a.jsx(ut,{"data-testid":"composer-chip",disabled:r,icon:a.jsx($K,{fontSize:"small"}),title:e,label:a.jsxs(T,{component:"span",sx:{alignItems:"center",display:"flex",gap:.5,minWidth:0},children:[a.jsx(T,{component:"span",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),!r&&a.jsx(Ie,{"aria-label":t,size:"small",onClick:s=>{s.stopPropagation(),n()},sx:{ml:.5,mr:-.5,p:.5,"&:hover":{backgroundColor:"transparent"}},children:a.jsx(ji,{fontSize:"small"})})]}),size:"small",sx:{borderRadius:1,maxWidth:200},variant:"outlined",color:"default"}),rc="ComposerModeChip-dismiss",BK=24,_k={ml:.25,maxWidth:`${BK}px`,opacity:1},UK=({icon:e,label:t,dismissLabel:n,onDismiss:r,disabled:s=!1})=>a.jsx(ut,{color:"default","data-testid":"composer-mode-chip",disabled:s,icon:e,title:t,label:a.jsxs(T,{component:"span",sx:{alignItems:"center",display:"flex",gap:.5,minWidth:0},children:[a.jsx(T,{component:"span",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),!s&&a.jsx(Ie,{"aria-label":n,className:rc,onClick:i=>{i.stopPropagation(),r()},size:"small",sx:{"&:hover":{backgroundColor:"transparent"}},children:a.jsx(ji,{fontSize:"small"})})]}),size:"small",sx:{borderRadius:5,height:Od,maxWidth:200,"& .MuiChip-icon":{ml:1.25,mr:0},"& .MuiChip-label":{pl:.75,pr:1.25},[`& .${rc}`]:{boxSizing:"border-box",color:"icon.secondary",ml:0,maxWidth:0,opacity:0,overflow:"hidden",p:.25,transition:"max-width 0.15s ease-in-out, opacity 0.15s ease-in-out, margin 0.15s ease-in-out"},[`&:hover .${rc}, & .${rc}:focus-visible`]:_k,"@media (hover: none)":{[`& .${rc}`]:_k}},variant:"filled"}),VK=1.2,WK=e=>{const t=Number.parseFloat(e.lineHeight);if(Number.isFinite(t))return t;const n=Number.parseFloat(e.fontSize);return Number.isFinite(n)?n*VK:Number.NaN},HK=({ref:e,value:t,hasAttachments:n,hasActiveModes:r})=>{const[s,i]=m.useState(!1),o=m.useCallback(()=>{const c=e.current;if(!c)return;const d=window.getComputedStyle(c),u=Number.parseFloat(d.paddingTop),p=Number.parseFloat(d.paddingBottom),h=WK(d);if(!Number.isFinite(h))return;const f=h+(Number.isFinite(u)?u:0)+(Number.isFinite(p)?p:0);c.scrollHeight>f+1&&i(!0)},[e]);m.useEffect(()=>{const c=e.current;if(!c||typeof ResizeObserver>"u")return;const d=new ResizeObserver(()=>o());return d.observe(c),()=>d.disconnect()},[o,e]),m.useEffect(()=>{o()},[o,t]),m.useEffect(()=>{const{fonts:c}=document;c&&c.ready.then(()=>o()).catch(()=>{})},[o]);const l=t.length===0&&!n&&!r;return m.useEffect(()=>{l&&i(!1)},[l]),s&&!l||n||r},yR=m.forwardRef((e,t)=>
18{const{attachments:n=[],disabled:r=!1,disclaimerStartSlot:s,handleSendQuestion:i,hideDisclaimer:o=!1,llmAssistantName:l,loading:c=!1,menuItems:d=[],onRemoveAttachment:u,sendDisabled:p=!1}=e,h=m.useRef(null),[f,g]=m.useState(""),x=d.filter(j=>j.active),b=HK({hasActiveModes:x.length>0,hasAttachments:n.length>0,ref:h,value:f}),y=c||r,v=y||p;m.useImperativeHandle(t,()=>({focus:()=>{h.current?.focus()},setText:j=>{g(j)},prefill:j=>{g(j),requestAnimationFrame(()=>{const _=h.current;if(!_)return;_.focus();const D=_.value.length;_.setSelectionRange?.(D,D)})}}));const C=j=>{j.stopPropagation(),j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),f&&!v&&(i(f),g("")))},w=()=>{f&&!v&&(i(f),g(""))},S=()=>{h.current?.focus()},E=m.useRef(!1);m.useEffect(()=>{E.current&&(E.current=!1,document.activeElement===document.body&&h.current?.focus())},[b]);const k=a.jsxs(T,{onBlur:()=>{E.current=!1},onFocus:()=>{E.current=!0},sx:{alignItems:"center",display:"flex",flexShrink:0,gap:.5,minWidth:0},children:[a.jsx(DK,{disabled:y,items:d}),x.map(j=>a.jsx(UK,{disabled:y,dismissLabel:`Turn off ${j.label}`,icon:j.icon,label:j.label,onDismiss:()=>{j.onSelect(),S()}},j.id))]});return a.jsxs(T,{width:"100%",sx:{display:"flex",flexDirection:"column",gap:.5},maxWidth:$C,children:[a.jsxs(T,{"data-expanded":b?"true":"false","data-testid":"composer-input-row",sx:{alignItems:b?"flex-end":"center",backgroundColor:"background.input.default",border:"1px solid",borderColor:"border.input",borderRadius:"10px",display:"flex",flexWrap:"wrap",gap:1,justifyContent:"space-between",minWidth:0,px:1,pb:b?1:.5,pt:.5,transition:"border 0.2s ease-in-out","&:focus-within":{border:"2px solid",borderColor:"border.brand"}},children:[!b&&d.length>0&&k,a.jsxs(T,{sx:j=>({display:"flex",flexDirection:"column",flexBasis:b?"100%":0,flexGrow:1,gap:1,maxHeight:"300px",minWidth:0,overflow:"auto","&::-webkit-scrollbar":{width:"10px"},"&::-webkit-scrollbar-track":{background:j.palette.mode==="dark"?j.palette.neutral[700]:j.palette.neutral[100],borderRadius:"0 9px 9px 0"},"&::-webkit-scrollbar-thumb":{background:j.palette.mode==="dark"?j.palette.neutral[500]:j.palette.neutral[400],borderRadius:"10px"}}),children:[n.length>0&&a.jsx(T,{sx:{display:"flex",flexWrap:"wrap",gap:.5,width:"100%"},children:n.map(j=>a.jsx(zK,{disabled:y||!u,dismissLabel:`Remove ${j.label}`,label:j.label,onDismiss:()=>{u?.(j.id),S()}},j.id))}),a.jsx(De,{inputRef:h,value:f,onChange:j=>{g(j.target.value)},sx:{flexGrow:1,minWidth:0,pointerEvents:y?"none":"inherit",whiteSpace:"pre-wrap",overflowWrap:"break-word",wordBreak:"keep-all","& .MuiOutlinedInput-root, & .MuiOutlinedInput-root:hover":{backgroundColor:"transparent"},"& .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline ":{border:"none",boxShadow:"none"},"& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline":{border:"none",boxShadow:"none"}},disabled:y,onKeyDown:j=>C(j),placeholder:`Ask ${l}`,variant:"outlined",multiline:!0})]}),b&&k,a.jsx(NK,{disabled:r||p||f.length===0,loading:c,onClick:w})]}),!o&&a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,justifyContent:"space-between",mt:2,pr:1,width:"100%"},children:[a.jsx(T,{sx:{display:"flex",minWidth:0},children:s}),a.jsx(T,{sx:{color:"text.secondary",fontSize:"0.65rem",lineHeight:1,textAlign:"right"},children:"AI content may be flawed, verify important info."})]})]})}),qK=({disabled:e,onClickAction:t,pinned:n})=>{const[r,s]=m.useState(null),i=!!r,o=()=>{s(null)};return a.jsxs(a.Fragment,{children:[a.jsx(Ie,{disabled:e,onClick:l=>{s(l.currentTarget)},sx:{p:.5},children:a.jsx(vl,{size:16})}),a.jsx(bR,{anchorEl:r,onClickAction:t,onClose:o,open:i,pinned:n})]})},GK=m.memo(({chat:e,deleteSession:t,dispatch:n,editingMetaData:r,handleSwitchSession:s,onSessionSelect:i,selected:o,unreadCount:l,updatePinned:c,updateTitle:d})=>{const{pinned:u,sessionId:p,sessionTitle:h}=e,f=m.useRef(null),[g,x]=m.useState(!1),[b,y]=m.useState(!1),v=m.useCallback(k=>{const j=k.target.value;d({nextTitle:j,sessionId:p}),x(!1),n({type:"editingMetaData",value:!1})},[n,p,d]),C=m.useCallback(()=>{t({sessionId:p}),y(!1)},[t,p]),w=m.useCallback(k=>{switch(k){case"rename":x(!0),n({type:"editingMetaData",value:!0});break;case"togglePinned":c({nextPinned:!u,sessionId:p});break;case"delete":y(!0);break}},[n,u,p,c]),S=m.useCallback(()=>{o||s(p),i?.()},[s,i,o,p]);m.useEffect(()=>{g&&f.current?.focus()},[g]);const E=g?a.jsx(De,{defaultValue:h,inputRef:f,onBlur:v,onKeyDown:k=>{k.code==="Enter"&&f.current?.blur()},sx:{height:36,width:250,".MuiInputBase-root":{height:36},".MuiInputBase-input":{fontSize:13,height:34,lineHeight:"24px",px:"7px",py:"5px"}}}):a.jsxs(a.Fragment,{children:[a.jsxs(He,{disabled:r,onClick:S,sx:{columnGap:1.5,justifyContent:"start",minWidth:0,width:"100%"},children:[a.jsx(Yt,{in:!!l,orientation:"horizontal",unmountOnExit:!0,children:a.jsxs(T,{sx:{alignItems:"center",bgcolor:"success.main",borderRadius:2,color:"success.contrastText",display:"flex",flexDirection:"row",gap:"2px",mr:1,p:"2px 6px"},children:[a.jsx(I,{children:l}),a.jsx(MB,{size:14})]})}),a.jsx(I,{component:"span",sx:{fontSize:13,fontWeight:500,lineHeight:"24px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h})]}),a.jsx(qK,{disabled:r,onClickAction:w,pinned:u}),a.jsx(Cl,{bodyText:"Are you sure you want to delete this chat?",dialogProps:{sx:{zIndex:xR}},handleClose:()=>y(!1),handleDelete:C,open:b,title:"Delete chat?"})]});return a.jsx(T,{sx:({palette:k})=>({alignItems:"center",bgcolor:o?k.background.brand.subtle.hovered:"none",borderRadius:1,display:"flex",height:36,justifyContent:"space-between",pl:g?0:1,py:g?.75:0}),children:E})}),Tk=({activeChat:e,chats:t,deleteSession:n,dispatch:r,editingMetaData:s,handleSwitchSession:i,onSessionSelect:o,shortHand:l,unreadMessages:c,updatePinned:d,updateTitle:u})=>a.jsxs($,{children:[a.jsx(I,{color:"text.secondary",variant:"caption",sx:{alignItems:"center",display:"flex",height:24},children:l}),a.jsx(_D,{children:t.map(p=>a.jsx(Yt,{children:a.jsx(GK,{chat:p,deleteSession:n,dispatch:r,editingMetaData:s,handleSwitchSession:i,onSessionSelect:o,selected:e===p.sessionId,unreadCount:c?.get(p.sessionId)??null,updatePinned:d,updateTitle:u})},p.sessionId))})]},l);Z.extend(El);const YK=e=>{const t=e.filter(({pinned:s})=>!s).sort((s,i)=>Z(i.updatedAt).valueOf()-Z(s.updatedAt).valueOf());let n="";const r=[];return t.forEach(s=>{const{updatedAt:i}=s,o=Z.utc(i).local(),l=kK(o);l&&l!==n?(r.push({shortHand:l,chats:[s]}),n=l):r[r.length-1]?.chats.push(s)}),r},KK=({onSessionSelect:e,showCloseButton:t=!1,sx:n})=>{const{deleteSession:r,dispatch:s,handleSwitchSession:i,metaData:o,state:{editingMetaData:l,historyOpen:c,unreadMessages:d},updatePinned:u,updateTitle:p,watch:h}=Wr(),f=h("sessionId"),[g,x]=m.useMemo(()=>[o.filter(({pinned:b})=>b).sort((b,y)=>Z(y.updatedAt).valueOf()-Z(b.updatedAt).valueOf()),YK(o)],[o]);return a.jsxs($,{sx:{bgcolor:"background.neutral.default",borderColor:"border.default",borderLeft:"1px solid",height:"fit-content",minHeight:"100%",p:2,pr:3,rowGap:2,...n},children:[t&&a.jsxs($,{sx:{alignItems:"center",flexDirection:"row",justifyContent:"space-between"},children:[a.jsx(I,{variant:"subtitle2",children:"History"}),a.jsx(Ie,{onClick:()=>{s({type:"historyOpen",value:!c})},sx:{p:.5},children:a.jsx(Jt,{size:16})})]}),g.length?a.jsx(Tk,{activeChat:f,chats:g,deleteSession:r,dispatch:s,editingMetaData:l,handleSwitchSession:i,onSessionSelect:e,shortHand:"Pinned",unreadMessages:d,updatePinned:u,updateTitle:p}):null,a.jsx(_D,{children:x.map(({chats:b,shortHand:y})=>a.jsx(Yt,{children:a.jsx(Tk,{activeChat:f,chats:b,deleteSession:r,dispatch:s,editingMetaData:l,handleSwitchSession:i,onSessionSelect:e,shortHand:y,unreadMessages:d,updatePinned:u,updateTitle:p})},y))})]})},QK=({status:e})=>{switch(e){case"running":return a.jsx(Ze,{size:16});case"complete":return a.jsx(Yv,{size:16});case"error":return a.jsx(wl,{size:16});case"cancelled":return a.jsx(RB,{size:16});default:return null}},JK=e=>{switch(e){case"complete":return"success.main";case"error":return"error.main";case"cancelled":return"text.disabled";default:return"text.primary"}},XK=e=>{switch(e){case"running":return"Running in background";case"complete":return"Completed";case"error":return"Failed";case"cancelled":return"Cancelled";default:return""}},ZK=({scrollToJobResult:e})=>{const{watch:t}=Wr(),n=t("backgroundJobs"),[r,s]=m.useState(()=>new Set),i=m.useCallback(c=>{s(d=>{const u=new Set(d);return u.add(c),u})},[]),o=m.useCallback(c=>{e(c)},[e]),l=n.filter(c=>!r.has(c.jobId));return l.length===0?null:a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:.5,position:"sticky",top:0,width:"100%",zIndex:10},children:l.map(c=>a.jsxs(T,{sx:{alignItems:"center",bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1,display:"flex",gap:1.5,px:2,py:1},children:[a.jsx(QK,{status:c.status}),a.jsxs(T,{sx:{flex:1,minWidth:0},children:[a.jsx(I,{variant:"body2",noWrap:!0,sx:{color:JK(c.status)},children:c.promptPreview}),a.jsx(I,{variant:"caption",sx:{color:"text.secondary"},children:XK(c.status)})]}),(c.status==="complete"||c.status==="error")&&a.jsx(re,{size:"small",variant:"text",onClick:()=>o(c.jobId),"aria-label":"View result",sx:{textTransform:"none",whiteSpace:"nowrap"},children:"View result"}),a.jsx(Ie,{size:"small",onClick:()=>i(c.jobId),"aria-label":"Dismiss job notification",children:a.jsx(Jt,{size:16})})]},c.jobId))})};var sc={},Ik;function e8(){if(Ik)return sc;Ik=1;var e=Pt();Object.defineProperty(sc,"__esModule",{value:!0}),sc.default=void 0;var t=e(Lt()),n=Ot();return sc.default=(0,t.default)((0,n.jsx)("path",{d:"m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58
18L18 14z"}),"ExpandLess"),sc}var t8=e8();const vR=dt(t8);var ic={},Dk;function n8(){if(Dk)return ic;Dk=1;var e=Pt();Object.defineProperty(ic,"__esModule",{value:!0}),ic.default=void 0;var t=e(Lt()),n=Ot();return ic.default=(0,t.default)((0,n.jsx)("path",{d:"M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"}),"ExpandMore"),ic}var r8=n8();const Gh=dt(r8),Pd=({children:e,isUser:t})=>a.jsx(T,{sx:({palette:n,spacing:r})=>({alignContent:"center",backgroundColor:t?n.mode==="light"?"primary.lightest":"background.brand.subtle.default":"surface.default",borderBottomLeftRadius:t?r(1):0,borderBottomRightRadius:t?0:r(1),borderRadius:1,color:"text.secondary",height:"auto",ml:t?2:0,overflow:"hidden",p:2,position:"relative",textAlign:"left"}),children:e}),s8=["Overactive refusal","Didn't fully follow my request","Not factually correct"],i8=({onChange:e,topics:t})=>{const n=r=>{if(t.includes(r)){e(t.filter(s=>s!==r));return}e([...t,r])};return a.jsx(T,{sx:{display:"flex",flexWrap:"wrap",gap:"8px"},children:s8.map((r,s)=>a.jsx(ut,{onClick:()=>n(r),label:r,variant:"filled",sx:{borderColor:"border.default",border:"1px solid",filter:t.includes(r)?"invert(100%)":void 0,WebkitFilter:t.includes(r)?"invert(100%)":void 0}},`chip_${s.toString()}`))})},a8=({messageId:e,onClose:t,onSubmit:n,scrollRef:r,sessionId:s,traceId:i,visible:o})=>{const[l,c]=m.useState([]),d=m.useRef(null),{feedbackMpTrack:u,handleSendFeedback:p}=Wr(),h=()=>{n(),i&&p({comment:d.current?.value??"",feedback:"negative",sessionId:s,topics:l,traceId:i}),u("dislikedChat",{sessionId:s,messageId:e,feedback:d.current?.value,topics:l})};return a.jsx(Yt,{in:o,children:a.jsxs(T,{ref:r,sx:{border:"1px solid",borderColor:"primary.lightest",borderRadius:"8px",padding:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",alignItems:"self-start"},children:[a.jsx(I,{align:"left",children:"Tell us more about this issue:"}),a.jsx(Ie,{"aria-label":"close",sx:{padding:0},onClick:t,children:a.jsx(Jt,{size:20})})]}),a.jsx(i8,{onChange:f=>c(f),topics:l}),a.jsxs(T,{children:[a.jsx(I,{align:"left",sx:{paddingBottom:"7px"},children:"Please provide details (optional):"}),a.jsx(De,{inputRef:d,style:{width:"100%"},variant:"outlined",multiline:!0,minRows:2})]}),a.jsx(T,{sx:{display:"flex",justifyContent:"flex-end"},children:a.jsx(re,{onClick:h,children:"Submit"})})]})})},o8=({visible:e,onClose:t})=>a.jsx(Yt,{in:e,children:a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px 16px",backgroundColor:"background.neutral.default",borderRadius:"8px"},children:[a.jsx(I,{align:"left",sx:{maxWidth:"287px"},children:"Thank you for sharing your feedback. It helps me to learn."}),a.jsx(Ie,{"aria-label":"close",sx:{padding:0},onClick:t,children:a.jsx(Jt,{size:20})})]})}),l8=({canProvideFeedback:e,feedback:t,handleDislike:n,handleLike:r})=>{const{palette:s}=Re();return t?t==="positive"?a.jsx(be,{title:"Liked",children:a.jsx(yj,{size:20,fill:s.icon.brand.main})}):a.jsx(be,{title:"Disliked",children:a.jsx(vj,{size:20,fill:s.icon.secondary})}):e?a.jsxs(a.Fragment,{children:[a.jsx(be,{title:"Like",children:a.jsx(Ie,{"aria-label":"like-button",onClick:r,sx:{p:.5,fill:"icon.inverse"},children:a.jsx(yj,{size:20})})}),a.jsx(be,{title:"Dislike",children:a.jsx(Ie,{"aria-label":"dislike-button",onClick:n,sx:{p:.5,fill:"icon.inverse"},children:a.jsx(vj,{size:20})})})]}):null},c8=3e4,CR=({messageId:e,feedback:t,sessionId:n,handleCopy:r,copied:s,traceId:i})=>{const[o,l]=m.useState(!1),[c,d]=m.useState(!1),u=ct(),{feedbackMpTrack:p,handleSendFeedback:h}=Wr(),f=m.useRef(null),g=!!i,x=m.useCallback(()=>{u()&&f.current?.scrollIntoView({behavior:"smooth",block:"nearest"})},[u,f]),b=()=>{i&&h({feedback:"positive",sessionId:n,traceId:i}),p("likedChat",{sessionId:n,messageId:e}),l(!1),d(!0)},y=()=>{l(!0),d(!1),setTimeout(x,300)};return m.useEffect(()=>{if(c){const v=setTimeout(()=>{u()&&d(!1)},c8);return()=>clearTimeout(v)}return()=>{}},[u,c]),a.jsxs(T,{sx:{display:"flex",gap:o||c?"12px":"0",flexDirection:"column",paddingTop:"8px"},children:[a.jsxs(T,{sx:{display:"flex",columnGap:.5,justifyContent:"flex-start",alignItems:"center"},children:[a.jsx(l8,{canProvideFeedback:g,feedback:t,handleDislike:y,handleLike:b}),a.jsx(be,{title:s?"Copied!":"Copy",children:a.jsx(Ie,{"aria-label":"Copy",onClick:r,color:s?"success":"default",sx:{padding:"4px",fill:({palette:v})=>v.icon.secondary},children:a.jsx(NB,{sx:{height:20,width:20}})})})]}),g&&a.jsxs(a.Fragment,{children:[a.jsx(a8,{messageId:e,onClose:()=>l(!1),onSubmit:()=>{l(!1),d(!0)},scrollRef:f,sessionId:n,traceId:i??null,visible:o&&!c}),a.jsx(o8,{onClose:()=>d(!1),visible:c})]})]})},d8=({message:e,registerJobResultRef:t,sessionId:n})=>{const[r,s]=m.useState(!0),[i,o]=m.useState(!1),l=ct(),c=m.useRef(null),d=m.useCallback(x=>{const b=e.jobId;b&&t(b,x)}
18,[t,e.jobId]),u=e.variant==="job-error",p=`job-result-content-${e.jobId}`,h=m.useMemo(()=>e.content.filter(x=>x.text),[e.content]),f=m.useCallback(()=>{s(x=>!x)},[]),g=m.useCallback(async()=>{if(c.current){const x=c.current,b=x.innerHTML,y=x.innerText;try{const v=new Blob([b],{type:"text/html"}),C=new Blob([y],{type:"text/plain"}),w=new ClipboardItem({"text/html":v,"text/plain":C});await navigator.clipboard.write([w]),o(!0),setTimeout(()=>{l()&&o(!1)},2e3)}catch{alert("Failed to copy text.")}}},[l]);return a.jsx(T,{ref:d,children:a.jsxs(Pd,{isUser:!1,children:[a.jsxs(T,{sx:{border:1,borderColor:"divider",borderRadius:1,overflow:"hidden"},children:[a.jsx(re,{variant:"text",onClick:f,startIcon:u?a.jsx(wl,{size:16}):a.jsx(Yv,{size:16}),endIcon:r?a.jsx(vR,{}):a.jsx(Gh,{}),"aria-expanded":r,"aria-controls":p,sx:{bgcolor:"action.hover",borderRadius:0,color:u?"error.main":"success.main",justifyContent:"space-between",p:1,textTransform:"none",width:"100%"},children:a.jsx(I,{variant:"body2",sx:{flex:1,textAlign:"left"},children:u?"Background task failed":`Result: â${e.promptPreview}â`})}),a.jsx(Yt,{in:r,children:a.jsx(T,{id:p,ref:c,sx:{p:2},children:h.map((x,b)=>a.jsx(T,{children:a.jsx(ms,{markdownText:x.text,filesMap:x.files?.reduce((y,v)=>({...y,[v.name]:{url:v.s3_url,type:v.type}}),{})})},`${e.messageId}-text-${b}`))})})]}),e.traceId&&a.jsx(CR,{messageId:e.messageId,sessionId:n,feedback:e.feedback??null,handleCopy:g,copied:i,traceId:e.traceId})]})})};var ac={},Ak;function u8(){if(Ak)return ac;Ak=1;var e=Pt();Object.defineProperty(ac,"__esModule",{value:!0}),ac.default=void 0;var t=e(Lt()),n=Ot();return ac.default=(0,t.default)((0,n.jsx)("path",{d:"M4 9h4v11H4zm12 4h4v7h-4zm-6-9h4v16h-4z"}),"BarChart"),ac}var p8=u8();const h8=dt(p8);var oc={},Mk;function f8(){if(Mk)return oc;Mk=1;var e=Pt();Object.defineProperty(oc,"__esModule",{value:!0}),oc.default=void 0;var t=e(Lt()),n=Ot();return oc.default=(0,t.default)((0,n.jsx)("path",{d:"m19 8-4 4h3c0 3.31-2.69 6-6 6-1.01 0-1.97-.25-2.8-.7l-1.46 1.46C8.97 19.54 10.43 20 12 20c4.42 0 8-3.58 8-8h3zM6 12c0-3.31 2.69-6 6-6 1.01 0 1.97.25 2.8.7l1.46-1.46C15.03 4.46 13.57 4 12 4c-4.42 0-8 3.58-8 8H1l4 4 4-4z"}),"Cached"),oc}var m8=f8();const wR=dt(m8);var lc={},Rk;function g8(){if(Rk)return lc;Rk=1;var e=Pt();Object.defineProperty(lc,"__esModule",{value:!0}),lc.default=void 0;var t=e(Lt()),n=Ot();return lc.default=(0,t.default)((0,n.jsx)("path",{d:"M4 4h16v12H5.17L4 17.17zm0-2c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm2 10h8v2H6zm0-3h12v2H6zm0-3h12v2H6z"}),"ChatOutlined"),lc}var x8=g8();const b8=dt(x8);var cc={},Nk;function y8(){if(Nk)return cc;Nk=1;var e=Pt();Object.defineProperty(cc,"__esModule",{value:!0}),cc.default=void 0;var t=e(Lt()),n=Ot();return cc.default=(0,t.default)((0,n.jsx)("path",{d:"M8 16h8v2H8zm0-4h8v2H8zm6-10H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z"}),"DescriptionOutlined"),cc}var v8=y8();const C8=dt(v8);var dc={},Ok;
18function w8(){if(Ok)return dc;Ok=1;var e=Pt();Object.defineProperty(dc,"__esModule",{value:!0}),dc.default=void 0;var t=e(Lt()),n=Ot();return dc.default=(0,t.default)((0,n.jsx)("path",{d:"M18 15v3H6v-3H4v3c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-3zm-1-4-1.41-1.41L13 12.17V4h-2v8.17L8.41 9.59 7 11l5 5z"}),"FileDownloadOutlined"),dc}var S8=w8();const SR=dt(S8);var uc={},Pk;function j8(){if(Pk)return uc;Pk=1;var e=Pt();Object.defineProperty(uc,"__esModule",{value:!0}),uc.default=void 0;var t=e(Lt()),n=Ot();return uc.default=(0,t.default)((0,n.jsx)("path",{d:"m16 6 2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"}),"TrendingUp"),uc}var k8=j8();const E8=dt(k8),_8=e=>{switch(e){case"DescriptionOutlinedIcon":return C8;case"TrendingUpIcon":return E8;case"FileDownloadOutlinedIcon":return SR;case"BarChartIcon":return h8;default:return b8}},T8=()=>{const{chatExamples:e,chatExamplesLoading:t,handleSetMessage:n,llmAssistantName:r,username:s}=Wr(),i=m.useMemo(()=>e.examples??[],[e.examples]),[o,l]=m.useState([]),c=m.useCallback(()=>{l(i.toSorted(()=>Math.random()-.5).slice(0,6))},[i]);return m.useEffect(()=>{c()},[c]),a.jsxs(T,{textAlign:"left",children:[a.jsxs(I,{fontSize:16,children:["Hi ",s,", I am ",r,", an AI assistant. Let's dive into your data!"]}),a.jsxs($,{direction:"row",alignItems:"center",gap:1,mt:3,children:[a.jsx(T,{sx:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:1,flex:1},children:t?[...Array(6)].map((d,u)=>a.jsx(Ve,{sx:{borderColor:"divider",borderRadius:1,borderStyle:"solid",borderWidth:1,boxShadow:"none"},children:a.jsxs(Ue,{sx:{alignItems:"flex-start",display:"flex",padding:"12px !important"},children:[a.jsx(fe,{variant:"circular",width:18,height:18,sx:{mr:1,mt:.25}}),a.jsx(fe,{variant:"text",width:"80%",sx:{transform:"none"}})]})},`skeleton-${u}`)):o.map(d=>{const u=_8(d.icon);return a.jsx(Ve,{onClick:()=>n(d.prompt),sx:{"&:hover":{bgcolor:"action.hover",cursor:"pointer"},borderColor:"divider",borderRadius:1,borderStyle:"solid",borderWidth:1,boxShadow:"none"},children:a.jsxs(Ue,{sx:{alignItems:"flex-start",display:"flex",padding:"12px !important",width:"100%"},children:[a.jsx(u,{sx:{color:"secondary.main",fontSize:"1.125rem",mr:1,mt:.25}}),a.jsx(I,{variant:"body1",sx:{flex:1,fontWeight:400,lineHeight:1.4},children:d.title})]})},d.id||d.title)})}),i.length>0&&a.jsx(Ie,{onClick:c,size:"small",sx:{color:"secondary.main",mt:.5},children:a.jsx(wR,{})})]})]})},I8=({toolName:e,isActive:t=!1})=>e?a.jsxs(T,{sx:{alignItems:"center",bgcolor:"background.brand.subtle.default",borderLeft:3,borderLeftColor:"info.main",borderRadius:1,display:"flex",gap:1,mb:.5,px:1.5,py:1},role:t?"status":void 0,"aria-live":t?"polite":void 0,children:[a.jsx(I,{component:"span",sx:{color:"info.main",fontSize:12,fontWeight:600,textTransform:"uppercase"},children:"Tool call:"}),a.jsx(I,{component:"span",sx:{color:"text.secondary",flex:1,fontFamily:"monospace",fontSize:13},children:e}),t&&a.jsx(Ze,{size:12,thickness:6,sx:{color:"info.main"},"aria-label":"Tool in progress"})]}):null,ny=({isActive:e=!1,tools:t})=>t.length===0?null:a.jsx(T,{sx:{mt:1.5},children:t.map(({displayName:n,id:r},s)=>a.jsx(I8,{isActive:e,toolName:n},r??`tool-${s}`))}),jR=({thinking:e})=>{const[t,n]=m.useState(!1),r=m.useCallback(()=>{n(s=>!s)},[]);return e?a.jsxs(T,{sx:{border:1,borderColor:"divider",borderRadius:1},children:[a.jsx(re,{variant:"text",onClick:r,endIcon:t?a.jsx(vR,{}):a.jsx(Gh,{}),"aria-expanded":t,"aria-controls":"thinking-content",sx:{bgcolor:"action.hover",borderRadius:0,color:"text.primary",justifyContent:"space-between",p:1,textTransform:"none",width:"100%"},children:a.jsxs(T,{component:"span",sx:{alignItems:"center",color:"text.secondary",display:"flex",gap:.75},children:[a.jsx(OB,{size:16}),a.jsx(I,{variant:"body2",children:"Thinking"})]})}),a.jsx(Yt,{in:t,children:a.jsx(T,{id:"thinking-content",sx:{bgcolor:"background.default",p:1},children:a.jsx(I,{variant:"body2",sx:{color:"text.secondary",fontFamily:"monospace",whiteSpace:"pre-wrap"},children:e})})})]}):null},D8=({message:e,sessionId:t})=>{const[n,r]=m.useState(!1),s=ct(),i=m.useRef(null),{content:o,feedback:l,messageId:c,promptPreview:d,role:u,thinking:p,traceId:h}=e,f=m.useMemo(()=>o.filter(v=>v.text),[o]),g=m.useMemo(()=>o.map(({toolUse:v})=>
18v?.name).filter(Boolean).map(v=>({displayName:v})),[o]),x=u==="user",b=!(x||g.length),y=async()=>{if(i.current){const v=i.current,C=v.innerHTML,w=v.innerText;try{const S=new Blob([C],{type:"text/html"}),E=new Blob([w],{type:"text/plain"}),k=new ClipboardItem({"text/html":S,"text/plain":E});await navigator.clipboard.write([k]),r(!0),setTimeout(()=>{s()&&r(!1)},2e3)}catch{alert("Failed to copy text.")}}};return a.jsxs(Pd,{isUser:x,children:[a.jsxs(T,{children:[!!d&&a.jsxs(a.Fragment,{children:[a.jsx(I,{variant:"h6",sx:{color:"text.primary"},children:"Long Running Task Complete:"}),a.jsxs(I,{sx:{fontStyle:"italic"},children:[d,"..."]}),a.jsx(St,{sx:{my:2}})]}),!x&&p&&a.jsx(T,{sx:{mb:1},children:a.jsx(jR,{thinking:p})}),f.map((v,C)=>a.jsx(T,{ref:C===0?i:void 0,children:a.jsx(ms,{markdownText:v.text,filesMap:v.files?.reduce((w,S)=>({...w,[S.name]:{url:S.s3_url,type:S.type}}),{})})},`${c}-text-${C}`)),a.jsx(ny,{tools:g})]}),b&&a.jsx(CR,{messageId:c,sessionId:t,feedback:l??null,handleCopy:y,copied:n,traceId:h})]})},A8=({error:e})=>a.jsx(vn,{severity:"error",variant:"filled",children:e.message||"An error occurred"}),M8=e=>mm` 19 0%, 80%, 100% { 20 transform: translateY(0); 21 background-color: ${e.palette.icon.brand.light}; 22 } 23 40% { 24 transform: translateY(-6px); 25 background-color: ${e.palette.icon.brand.main}; 26 } 27`,Xg=rt(T)(({theme:e,delay:t})=>({width:8,height:8,borderRadius:"50%",backgroundColor:e.palette.icon.brand.main,animation:`${M8(e)} 1.4s ease-in-out infinite`,animationDelay:`${t}s`})),R8=({isStreaming:e,statusText:t})=>{const n=t??"AI is typing";return!t&&!e?null:a.jsxs($,{direction:"row",gap:1,sx:{p:1,height:36,alignItems:"center",color:"text.secondary"},children:[a.jsxs(T,{sx:{display:"flex",gap:.5},role:"status","aria-label":n,children:[a.jsx(Xg,{delay:0}),a.jsx(Xg,{delay:.2}),a.jsx(Xg,{delay:.4})]}),!!t&&a.jsx(I,{variant:"body2",component:"span",children:t})]})},N8=({connectionState:e,loading:t})=>{switch(t){case"init":return"Initializing Chat...";case"history":return"Loading History...";case"connection":return"Setting up connection..."}switch(e){case"connecting":return"Connecting...";case"reconnecting":return"Reconnecting..."}return null},O8=()=>{const{watch:e}=Wr(),t=e("accumulatedText"),n=e("activeTools"),r=e("completedTools"),s=e("connectionState"),i=e("error"),o=e("isStreaming"),l=e("loading"),c=e("thinking"),d=N8({connectionState:s,loading:l}),u=m.useMemo(()=>r.map(({id:g,name:x})=>({displayName:x,id:g})),[r]),p=m.useMemo(()=>n.map(({name:g,id:x})=>({displayName:g,id:x})),[n]),h=!!t&&!d,f=h||!!c||!!u.length||!!p.length;return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:[f&&a.jsxs(Pd,{isUser:!1,children:[c&&a.jsx(T,{sx:{mb:1},children:a.jsx(jR,{thinking:c})}),h&&a.jsx(ms,{markdownText:t}),a.jsx(ny,{tools:u}),a.jsx(ny,{isActive:!0,tools:p})]}),a.jsx(R8,{isStreaming:o,statusText:d}),i&&a.jsx(A8,{error:i})]})},P8=e=>e&&Z().valueOf()-e<2e3?"warning":"tombstone",L8=({message:e})=>{const{llmAssistantName:t}=Wr(),[n,r]=m.useState(()=>P8(e.createdAt));return m.useEffect(()=>{if(n!=="warning")return;const s=Math.max(0,2e3-(Z().valueOf()-(e.createdAt??0))),i=setTimeout(()=>r("tombstone"),s);return()=>clearTimeout(i)},[n,e.createdAt]),n==="warning"?a.jsx(T,{role:"status","aria-live":"polite","data-job-id":e.jobId,sx:{"@keyframes pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.6}},animation:"pulse 1s ease-in-out infinite"},children:a.jsx(Pd,{isUser:!1,children:a.jsxs(T,{sx:{alignItems:"center",border:1,borderColor:"warning.main",borderRadius:1,display:"flex",gap:1,p:1.5},children:[a.jsx(Cj,{size:16}),a.jsx(I,{variant:"body2",sx:{color:"warning.main"},children:"Moving task to background..."})]})})}):a.jsx(T,{"data-job-id":e.jobId,role:"status",children:a.jsx(Pd,{isUser:!1,children:a.jsxs(T,{sx:{alignItems:"center",border:1,borderColor:"divider",borderRadius:1,borderStyle:"dashed",display:"flex",gap:1,px:2,py:1.5},children:[a.jsx(Cj,{size:14,color:"inherit"}),a.jsxs(T,{children:[a.jsxs(I,{variant:"body2",sx:{color:"text.secondary"},children:['Moved "',e.promptPreview,'" to background']}),a.jsxs(I,{variant:"caption",sx:{color:"text.disabled"},children:["Feel free to chat with ",t," about something else."]})]})]})})})};Z.extend(Nm);Z.extend(El);const F8=({containerRef:e,handleShowAlert:t=()=>{},handleScrollToLastMessage:n,registerJobResultRef:r})=>{const{metaData:s,watch:i}=Wr(),o=i("accumulatedText"),l=i("history"),c=i("loading"),d=i("sessionId"),u=ct(),p=m.useRef(null),h=m.useMemo(()=>s.find(({sessionId:_})=>_===d),[s,d]),[f=0,g=0]=bk(l.length),[x=0,b=0]=bk(l.filter(({role:_})=>_==="assistant").length),{isIntersecting:y,ref:v}=HD({root:e.current});m.useEffect(()=>
27{v(p.current)},[v]);const C=g>f||!!o,w=b>x&&C,S=y&&C,E=!x,k=!(h||l.length||c),j=m.useCallback(()=>{u()&&n()},[n,u]);return m.useEffect(()=>{if(E){n();return}S?setTimeout(()=>j(),500):w&&t()},[E,j,n,t,w,S]),a.jsx(T,{textAlign:"center",sx:{alignItems:"flex-end",display:"flex",flexGrow:1,height:"fit-content",justifyContent:"center",minHeight:"100%",pb:3,pt:2,px:3,width:"100%"},children:a.jsxs($,{rowGap:3,width:"100%",maxWidth:$C,height:"100%",sx:{position:"relative"},children:[k&&a.jsx(T8,{}),h?Z.utc(h.updatedAt).local().format("LLL"):null,l.length?l.map(_=>{switch(_.variant){case"tombstone":return a.jsx(L8,{message:_},_.messageId);case"job-result":case"job-error":return a.jsx(d8,{message:_,registerJobResultRef:r,sessionId:d},_.messageId);default:return a.jsx(D8,{message:_,sessionId:d},_.messageId)}}):null,a.jsx(O8,{}),a.jsx(T,{ref:p,sx:{bottom:0,height:"350px",maxHeight:"100%",pointerEvents:"none",position:"absolute",right:0,width:"100%"}})]})})},$8=({scrollRef:e,containerRef:t,visible:n,setVisible:r})=>{const{isIntersecting:s,ref:i}=HD({root:t.current});m.useEffect(()=>{i(e.current)},[i,e]);const o=()=>{e.current?.scrollIntoView({behavior:"smooth"})},l=m.useCallback(()=>{r(!1)},[r]);return m.useEffect(()=>{s&&l()},[l,s]),n?a.jsx(ut,{label:a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(Ie,{onClick:o,children:a.jsx(vs,{size:16})}),a.jsx(I,{sx:{cursor:"default"},children:"New Messages"}),a.jsx(Ie,{onClick:l,children:a.jsx(Jt,{size:16})})]}),color:"primary",sx:{position:"sticky",top:"10px",zIndex:10,left:"50%",transform:"translateX(-50%)"}}):null},z8=rt(eB)(()=>({"& .MuiBadge-badge":{right:3,top:5}})),ry=rt(Ie)(({theme:e})=>{const{primary:t}=e.palette;return{"&.MuiIconButton-sizeLarge":{padding:0,"&:hover":{background:"transparent",boxShadow:"none",color:t.dark},color:t.main}}});ry.defaultProps={...ry.defaultProps,id:"conversation-icon-button",size:"large"};const B8=mm` 28 0% {opacity: 50%} 29 50% {opacity: 100%} 30 100% {opacity: 50%} 31`,U8=({disabled:e,loading:t,onClick:n,title:r})=>{const{easing:s}=Re().transitions;return a.jsxs(He,{disabled:e||t,onClick:n,sx:{minWidth:0,borderRadius:1,p:.75,pr:.25,"&:hover":{bgcolor:"background.secondary.hovered"},transition:` 32 background-color 225ms ${s.easeInOut}, 33 color 225ms ${s.easeIn} 34 `,color:e?"text.secondary":"text.primary",animation:t?`${B8} 3s infinite ${s.easeInOut}`:""},children:[a.jsx(I,{variant:"subtitle1",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),a.jsx(tB,{sx:{ml:.5,opacity:e||t?"50%":"100%",transition:"all 225ms ease",transitionBehavior:"allow-discrete"},children:a.jsx(vs,{size:20})})]})},V8=()=>{const{deleteSession:e,dispatch:t,llmAssistantName:n,metaData:r,metaDataLoading:s,state:i,updatePinned:o,updateTitle:l,watch:c}=Wr(),d=c("sessionId"),{editingMetaData:u}=i,[p,h]=m.useState(null),[f,g]=m.useState(!1),[x,b]=m.useState(!1),y=m.useRef(null),v=!!p,C=m.useMemo(()=>r.find(_=>_.sessionId===d),[r,d]),w=()=>{h(null)},S=m.useCallback(_=>{if(d){const D=_.target.value;l({nextTitle:D,sessionId:d}),g(!1),t({type:"editingMetaData",value:!1})}},[t,d,l]);function E(_){_&&e({sessionId:_}),b(!1)}const k=m.useCallback(_=>{if(C)switch(_){case"rename":g(!0),t({type:"editingMetaData",value:!0});break;case"togglePinned":o({nextPinned:!C.pinned,sessionId:C.sessionId});break;case"delete":b(!0);break}},[t,C,o]);m.useEffect(()=>{f&&y.current?.focus()},[f]);let j=a.jsx(I,{variant:"subtitle1",children:n});return C&&(f?j=a.jsx(De,{defaultValue:C.sessionTitle,inputRef:y,onBlur:S,onKeyDown:_=>{_.code==="Enter"&&y.current?.blur()},sx:{height:36,width:300,".MuiInputBase-root":{height:36},".MuiInputBase-input":{lineHeight:"24px",px:1.5,py:.75}}}):j=a.jsxs(a.Fragment,{children:[a.jsx(U8,{disabled:u,loading:s,onClick:_=>{h(_.currentTarget)},title:C.sessionTitle}),a.jsx(bR,{anchorEl:p,onClickAction:k,onClose:w,open:v,pinned:C.pinned}),a.jsx(Cl,{bodyText:"Are you sure you want to delete this chat?",dialogProps:{sx:{zIndex:xR}},handleClose:()=>b(!1),handleDelete:()=>E(C.sessionId),open:x,title:"Delete chat?"})]})),a.jsxs($,{sx:{alignItems:"center",columnGap:1.5,flexDirection:"row",minWidth:0,pr:2},children:[a.jsx(T,{sx:{color:"icon.brand.main",height:24,width:24},children:a.jsx(PB,{})}),j]})},cp=({icon:e,id:t="control-button",onClick:n,sxProps:r={},tooltipTitle:s=""})=>e?a.jsx(be,{title:s,children:a.jsx(Ie,{sx:r,id:t,onClick:n,size:"small",children:e})}):null,W8=()=>{const{dispatch:e,state:t,handleOpenNewChat:n,handleOpenClose:r,watch:s}=Wr(),i=s("sessionId"),{historyOpen:o,isFullScreen:l}=t;return a.jsxs($,{direction:"row",justifyContent:"space-between",sx:{height:"100%",px:2.5,py:1.75,borderBottom:"1px solid",borderBottomColor:"border.default"},children:[a.jsx(V8,{}),a.jsxs($,{gap:1.5,direction:"row",children:[a.jsx(cp,{icon:i?a.jsx(qD,{}):null,id:"new-chat-button",onClick:n,tooltipTitle:"New Chat"}),a.jsx(cp,{icon:a.jsx(LB,{}),id:"view-history-button",onClick:()=>{e({type:"historyOpen",value:!o})},tooltipTitle:"History"}),a.jsx(St,{flexItem:!0,variant:"middle",orientation:"vertical"}),a.jsx(cp,{icon:l?a.jsx(FB,{}):a.jsx(GD,{}),id:"resize-window-button",onClick:()=>{e({type:"isFullScreen",value:!l})},tooltipTitle:l?"Collapse":"Expand"}),a.jsx(cp,{icon:a.jsx(Kv,{}),id:"close-window-button",onClick:r,tooltipTitle:"Minimize"})]})]})},kR=U.object({type:U.literal("file"),upload_id:U.string(),feature:U.string(),s3_uri:U.string(),filename:U.string(),mime_type:U.string().nullish(),size_bytes:U.number().nullish(),metadata:U.record(U.unknown()).nullish()}),H8=U.object({part_number:U.number(),url:U.string()}),q8=U.object({upload_id:U.string(),method:U.enum(["POST","MULTIPART"]),upload_url:U.string().nullish(),fields:U.record(U.string()).nullish(),s3_upload_id:U.string().nullish(),parts:U.array(H8).nullish(),part_size_bytes:U.number().nullish(),file_context:kR,expires_at:U.string()}),G8=U.object({upload_id:U.string(),status:U.string(),file_context:kR});var pc={},Lk;function Y8(){if(Lk)return pc;Lk=1;var e=Pt();Object.defineProperty(pc,"__esModule",{value:!0}),pc.default=void 0;var t=e(Lt()),n=Ot();return pc.default=(0,t.default)((0,n.jsx)("path",{d:"M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6z"}),"AttachFile"),pc}var K8=Y8();const Q8=dt(K8),J8=rt("input")({bottom:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,left:0,overflow:"hidden",position:"absolute",whiteSpace:"nowrap",width:1}),X8=({inputProps:e,isUploading:t,progress:n,error:r,warning:s,onDismissError:i,onDismissWarning:o,label:l="Upload file"})=>a.jsxs(T,{sx:{display:"flex",flexDirection:"column",gap:1,minWidth:0,width:"100%"},children:[a.jsx(J8,{"aria-label":l,...e}),t&&a.jsx(lo,{"aria-label":"Upload progress",value:n,variant:"determinate"}),r&&a.jsx(vn,{onClose:i,severity:"error",children:r}),s&&a.jsx(vn,{onClose:o,severity:"warning",children:s})]}),Z8="completed",e7=(e,t)=>{if(!(e instanceof qt)||e.step!=="transfer")return e;const n=Date.parse(t);return Number.isNaN(n)||Date.now()<=n?e:new qt("transfer",`${e.message} The upload link expired before the transfer finished; please try again.`,{errorCode:"UPLOAD_LINK_EXPIRED",cause:e})},t7=e=>Math.min(100,Math.max(0,Math.round(e))),Yh=(e,t,n)=>{if(!e)return;const r=n>0?t7(t/n*100):100;e(r)},n7=6e4,ER=e=>
34new Promise((t,n)=>{const r=new XMLHttpRequest;r.open(e.method,e.url,!0);let s,i=!1;const o=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},l=()=>{o(),s=setTimeout(()=>{i=!0,r.abort()},n7)};r.upload.onprogress=c=>{l(),c.lengthComputable&&e.onProgress?.(c.loaded)},r.upload.onload=l,r.onload=()=>{o(),r.status>=200&&r.status<300?t(r):n(new qt("transfer",`Storage rejected upload (${r.status})`))},r.onerror=()=>{o(),n(new qt("transfer","Network error during transfer"))},r.onabort=()=>{o(),n(new qt("transfer",i?"Transfer stalled and was abandoned":"Transfer was aborted"))},l(),r.send(e.body)}),r7=async(e,t,n)=>{if(!e.upload_url||!e.fields)throw new qt("transfer","Missing presigned POST form for POST transfer");const r=new FormData;Object.entries(e.fields).forEach(([s,i])=>{r.append(s,i)}),r.append("file",t),await ER({method:"POST",url:e.upload_url,body:r,onProgress:s=>Yh(n,s,t.size)}),Yh(n,t.size,t.size)},s7=async(e,t,n)=>{const{parts:r,part_size_bytes:s}=e;if(!r||r.length===0||!s)throw new qt("transfer","Missing multipart plan for transfer");const i=Math.max(1,Math.ceil(t.size/s));if(r.length!==i)throw new qt("transfer",`Multipart plan has ${r.length} parts, expected ${i}`);let o=0;const l=[...r].sort((d,u)=>d.part_number-u.part_number).map(d=>{const u=Math.min(o+s,t.size),p={part:d,start:o,end:u};return o=u,p}),c=[];for(const{part:d,start:u,end:p}of l){const f=(await ER({method:"PUT",url:d.url,body:t.slice(u,p),onProgress:g=>Yh(n,u+g,t.size)})).getResponseHeader("ETag");if(!f)throw new qt("transfer",`Missing ETag for part ${d.part_number}`);c.push({part_number:d.part_number,etag:f})}return Yh(n,t.size,t.size),c},i7=async({transport:e,feature:t,file:n,metadata:r,onProgress:s})=>{const i=await e.initiate({feature:t,filename:n.name,mime_type:n.type||null,size_bytes:n.size,metadata:r??null});let o;try{if(i.method==="MULTIPART")o=await s7(i,n,s);else if(i.method==="POST")await r7(i,n,s);else{const c=i.method;throw new qt("transfer",`Unsupported transfer method: ${String(c)}`)}}catch(c){throw e7(c,i.expires_at)}const l=await e.complete({upload_id:i.upload_id,feature:t,parts:o??[]});if(l.status!==Z8)throw new qt("complete",`Upload did not complete (status: ${l.status})`,{errorCode:"UPLOAD_NOT_COMPLETED"});return{fileContext:l.file_context,originalFilename:n.name}},Fk=e=>{const t=e/1048576;return t>=1?`${Number(t.toFixed(1))} MB`:`${Math.round(e/1024)} KB`},a7=(e,{accept:t,maxSizeBytes:n})=>{if(n!==void 0&&e.size>n)return`That file is ${Fk(e.size)}. The limit is ${Fk(n)}.`;const r=(t??"").split(",").map(s=>s.trim().toLowerCase()).filter(s=>s.startsWith("."));if(r.length>0){const s=e.name.toLowerCase();if(!r.some(i=>s.endsWith(i)))return`That file type is not accepted. Accepted types: ${r.join(", ")}.`}return null},o7=({transport:e,feature:t,onUploaded:n,onBeforeUpload:r,accept:s,maxSizeBytes:i,disabled:o=!1})=>{const l=m.useRef(null),[c,d]=m.useState(0),[u,p]=m.useState(!1),[h,f]=m.useState(null),[g,x]=m.useState(null),b=m.useCallback(()=>{l.current?.click()},[]),y=m.useCallback(async v=>{const C=v.target.files?.[0];if(!C)return;f(null),x(null),d(0);const w=a7(C,{accept:s,maxSizeBytes:i});if(w){f(w),l.current&&(l.current.value="");return}p(!0);try{await r?.(C);const S=await i7({feature:t,file:C,onProgress:d,transport:e});n(S)}catch(S){S instanceof qt?f(`Upload failed during ${S.step}: ${S.message}`):f("Upload failed due to an unexpected error.")}finally{p(!1),l.current&&(l.current.value="")}},[s,t,i,r,n,e]);return{dismissError:m.useCallback(()=>f(null),[]),dismissWarning:m.useCallback(()=>x(null),[]),error:h,inputProps:{accept:s,disabled:o||u,onChange:y,ref:l,type:"file"},isUploading:u,openPicker:b,progress:c,warning:g}},$k="Upload file",l7=e=>{const t=o7(e);return{isUploading:t.isUploading,item:{disabled:e.disabled||t.isUploading,icon:a.jsx(Q8,{fontSize:"small"}),id:"upload-file",label:$k,onSelect:t.openPicker},overlay:a.jsx(X8,{error:t.error,inputProps:t.inputProps,isUploading:t.isUploading,label:$k,onDismissError:t.dismissError,onDismissWarning:t.dismissWarning,progress:t.progress,warning:t.warning})}};class Kh{getSession;
34constructor(t){this.getSession=t}send(t,n){const r=this.getSession();if(!r)throw new qt(n,"No active WebSocket session for upload",{errorCode:"NO_ACTIVE_SESSION"});return r.request(t,n)}static parseReply(t,n,r){try{return t(n)}catch(s){throw new qt(r,"Malformed upload response from server",{errorCode:"INVALID_RESPONSE",cause:s})}}async initiate(t){const n=await this.send({type:"upload_initiate",...t},"initiate");return Kh.parseReply(r=>q8.parse(r),n,"initiate")}async complete(t){const n=await this.send({type:"upload_complete",...t},"complete");return Kh.parseReply(r=>G8.parse(r),n,"complete")}}const c7=".pdf,.txt,.csv,.md,.json,.tsv,.png,.jpg,.jpeg,.webp,.gif",d7="default_space",u7=25*1024*1024,p7=({disabled:e})=>{const{addAttachment:t,pendingAttachments:n,removeAttachment:r,sessionManagerRef:s}=Wr(),i=m.useRef(null),o=m.useMemo(()=>new Kh(()=>zi.peekSession(i.current??s.current.currentSessionId)),[s]),l=m.useCallback(async g=>{const x=await s.current.ensureUploadSession({sessionId:s.current.currentSessionId,title:g.name});if(!x)throw new qt("initiate","Could not start a session for this upload");i.current=x.sessionId},[s]),c=m.useCallback(g=>{const x=i.current;if(i.current=null,x!==null&&x!==s.current.currentSessionId){We(new Error(`Discarded an upload staged for session ${x}; the composer is now on ${s.current.currentSessionId||"(no session)"}`));return}t(g.fileContext,g.originalFilename)},[t,s]),{item:d,overlay:u,isUploading:p}=l7({accept:c7,disabled:e,feature:d7,maxSizeBytes:u7,onBeforeUpload:l,onUploaded:c,transport:o}),h=m.useMemo(()=>n.map(({displayName:g,fileContext:x})=>({id:x.upload_id,label:g})),[n]),f=m.useMemo(()=>[d],[d]);return{attachments:h,menuItems:f,onRemoveAttachment:r,overlay:u,sendDisabled:p}},h7=()=>{const{easing:e}=Re().transitions,{state:t,handleOpenClose:n,handleSendPrompt:r,llmAssistantName:s,textBoxRef:i,watch:o}=Wr(),l=o("thinking"),c=o("isStreaming"),d=o("loading"),u=o("sessionId"),[p,h]=m.useState(!1),{historyOpen:f,isFullScreen:g,isOpen:x}=t,b=!!l||c,y=m.useRef(null),v=m.useRef(null),C=m.useRef(new Map),w=m.useCallback((R,L)=>{L?C.current.set(R,L):C.current.delete(R)},[]),S=m.useCallback(R=>{C.current.get(R)?.scrollIntoView({behavior:"smooth",block:"center"})},[]),E=g?`calc(100vw - ${f?vk:0}px)`:`${wK}px`,k=`${f?vk:0}px`,{attachments:j,menuItems:_,onRemoveAttachment:D,overlay:M,sendDisabled:N}=p7({disabled:b}),O=m.useCallback(R=>{r({attachPending:!0,prompt:R,sessionId:u})},[r,u]);return a.jsxs(nB,{onClose:n,open:x,anchor:"right",sx:{zIndex:jK},PaperProps:{sx:{borderRadius:0,display:"grid",gridTemplateAreas:` 35 'top-controls top-controls' 36 'messages history' 37 'text-box history' 38 `,gridTemplateColumns:`${E} ${k}`,gridTemplateRows:"64px 1fr auto",overflow:"hidden",transition:` 39 grid-template-columns 225ms ${e.easeInOut}, 40 transform 225ms ${e.easeOut} 41 !important 42 `}},children:[a.jsx(T,{sx:{gridArea:"top-controls",overflow:"auto"},children:a.jsx(W8,{})}),a.jsxs(T,{ref:y,sx:{gridArea:"messages",overflow:"auto",position:"relative"},children:[a.jsx($8,{visible:p,scrollRef:v,containerRef:y,setVisible:h}),a.jsx(ZK,{scrollToJobResult:S}),a.jsx(F8,{containerRef:y,handleShowAlert:()=>h(!0),handleScrollToLastMessage:()=>{v.current?.scrollIntoView({behavior:"instant"})},registerJobResultRef:w}),a.jsx(T,{ref:v,sx:{height:"1px",width:"100%"}})]}),a.jsx(T,{sx:{display:"flex",gridArea:"text-box",justifyContent:"center",overflow:"auto",p:3},children:a.jsxs(T,{sx:{display:"flex",flexDirection:"column",maxWidth:$C,width:"100%"},children:[a.jsx(yR,{ref:i,attachments:j,disabled:b,handleSendQuestion:O,llmAssistantName:s,loading:!!d,menuItems:_,onRemoveAttachment:D,sendDisabled:N}),M]})}),a.jsx(T,{sx:{gridArea:"history",overflow:"auto"},children:a.jsx(KK,{showCloseButton:!0})})]})},f7=()=>{const{handleOpenClose:e,llmAssistantName:t,metaDataLoading:n,shouldRaiseButton:r,state:s}=Wr(),{easeInOut:i}=Re().transitions.easing,o=m.useMemo(()=>Array.from(s.unreadMessages.values()).reduce((l,c)=>l+c,0),[s.unreadMessages]);return a.jsxs(T,{sx:{position:"fixed",bottom:r?80:10,transition:`bottom 225ms ${i}`,right:10,zIndex:SK},children:[a.jsx(Nt,{isLoading:n,children:a.jsx(be,{title:`Ask ${t}`,PopperProps:{modifiers:[{name:"offset",options:{offset:[0,-10]}}]},children:a.jsx(ry,{onClick:e,children:a.jsx(z8,{badgeContent:o,color:"success",max:9,children:a.jsx($B,{})})})})}),a.jsx(h7,{})]})},zk=()=>{},m7=({accessToken:e,children:t,engagementId:n,feedbackMpTrack:r=zk,initialState:s,llmAssistantName:i,mpTrack:o=zk,onCanvasEvent:l,onJobNotification:c,providerNiceId:d,raiseConversationIcon:u,userGivenName:p})=>{const{data:h=[],isFetching:f}=vA(n,{skip:!n}),{data:g={examples:[],error:""},isLoading:x}=CA({engagement_id:n,include_inactive:!0},{skip:!n}),[b]=O5(),[y]=P5(),[v]=L5(),[C]=F5(),w=m.useCallback(async({sessionId:_})=>{o("clickedHistory",{sessionId:_});const{data:D}=await y({sessionId:_});return D??[]},[o,y]),S=m.useCallback(async({sessionId:_})=>{const{data:D}=await v({engagementId:n,sessionId:_});if(!D||!D?.websocketUrl||!e)return null;const{websocketUrl:M}=D;return{engagementId:n,sessionId:_,token:e,websocketUrl:M}},[e,n,v]),E=m.useCallback(async({title:_})=>{const D=await b({engagementId:n,provider_nice_id:d,title:_});if("error"in D||!D.data?.websocketUrl||!e)return null;const{sessionId:M,websocketUrl:N}=D.data;return o("newChat",{sessionId:M}),{engagementId:n,sessionId:M,token:e,websocketUrl:N}},[e,n,o,d,b]),k=m.useCallback(async({nextPinned:_,nextTitle:D,nextActive:M,sessionId:N})=>{const O={};_!==void 0&&(O.pinned=_),D!==void 0&&(O.session_title=D),M!==void 0&&(O.active=M),await C({body:O,engagementId:n,sessionId:N})},[n,C]),j=m.useCallback(()=>{o("openedUI")},[o]);return a.jsx(IK,{chatExamples:g,chatExamplesLoading:x,feedbackMpTrack:r,getChatHistory:w,getConfigForSession:S,initialState:s,initializeChat:E,llmAssistantName:i,metaData:h,metaDataLoading:f,onCanvasEvent:l,onJobNotification:c,onUpdateMeta:k,onOpenUI:j,shouldRaiseButton:u,username:p,children:t??a.jsx(f7,{})})},g7={clickedHistory:"Opened historical chat",newChat:"Started new chat",openedUI:"Opened chat window"},x7={dislikedChat:"Disliked chat",likedChat:"Liked chat"},Bk=/\[file:([^\]]+)\]/g;U.object({errorResponse:U.object({statusCode:U.literal(409)})});function rr(e){this.content=e}rr.prototype={constructor:rr,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return t==-1?void 0:this.content[t+1]},update:function(e,t,n){var r=n&&n!=e?this.remove(n):this,s=r.find(e),i=r.content.slice();return s==-1?i.push(n||e,t):(i[s+1]=t,n&&(i[s]=n)),new rr(i)},remove:function(e){var t=this.find(e);if(t==-1)return this;var n=this.content.slice();return n.splice(t,2),new rr(n)},addToStart:function(e,t){return new rr([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var n=this.remove(e).content.slice();return n.push(e,t),new rr(n)},addBefore:function(e,t,n){var r=this.remove(t),s=r.content.slice(),i=r.find(e);return s.splice(i==-1?s.length:i,0,t,n),new rr(s)}
vendor: 33,341 bytes, lines 42-43
42,forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return e=rr.from(e),e.size?new rr(e.content.concat(this.subtract(e).content)):this},append:function(e){return e=rr.from(e),e.size?new rr(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=rr.from(e);for(var n=0;n<e.content.length;n+=2)t=t.remove(e.content[n]);return t},toObject:function(){var e={};return this.forEach(function(t,n){e[t]=n}),e},get size(){return this.content.length>>1}};rr.from=function(e){if(e instanceof rr)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new rr(t)};function _R(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let s=e.child(r),i=t.child(r);if(s==i){n+=s.nodeSize;continue}if(!s.sameMarkup(i))return n;if(s.isText&&s.text!=i.text){for(let o=0;s.text[o]==i.text[o];o++)n++;return n}if(s.content.size||i.content.size){let o=_R(s.content,i.content,n+1);if(o!=null)return o}n+=s.nodeSize}}function TR(e,t,n,r){for(let s=e.childCount,i=t.childCount;;){if(s==0||i==0)return s==i?null:{a:n,b:r};let o=e.child(--s),l=t.child(--i),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;d<u&&o.text[o.text.length-d-1]==l.text[l.text.length-d-1];)d++,n--,r--;return{a:n,b:r}}if(o.content.size||l.content.size){let d=TR(o.content,l.content,n-1,r-1);if(d)return d}n-=c,r-=c}}class we{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let r=0;r<t.length;r++)this.size+=t[r].nodeSize}nodesBetween(t,n,r,s=0,i){for(let o=0,l=0;l<n;o++){let c=this.content[o],d=l+c.nodeSize;if(d>t&&r(c,s+l,i||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,t-u),Math.min(c.content.size,n-u),r,s+u)}l=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,s){let i="",o=!0;return this.nodesBetween(t,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(t,c)-c,n-c):l.isLeaf?s?typeof s=="function"?s(l):s:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:i+=r),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,s=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(s[s.length-1]=n.withText(n.text+r.text),i=1);i<t.content.length;i++)s.push(t.content[i]);return new we(s,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],s=0;if(n>t)for(let i=0,o=0;o<n;i++){let l=this.content[i],c=o+l.nodeSize;c>t&&((o<t||c>n)&&(l.isText?l=l.cut(Math.max(0,t-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,t-o-1),Math.min(l.content.size,n-o-1))),r.push(l),s+=l.nodeSize),o=c}return new we(r,s)}cutByIndex(t,n){return t==n?we.empty:t==0&&n==this.content.length?this:new we(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let s=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return s[t]=n,new we(s,i)}addToStart(t){return new we([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new we(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;n<this.content.length;n++)if(!this.content[n].eq(t.content[n]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let n=this.content[t];if(!n)throw new RangeError("Index "+t+" out of range for "+this);return n}maybeChild(t){return this.content[t]||null}forEach(t){for(let n=0,r=0;n<this.content.length;n++){let s=this.content[n];t(s,r,n),r+=s.nodeSize}}findDiffStart(t,n=0){return _R(this,t,n)}findDiffEnd(t,n=this.size,r=t.size){return TR(this,t,n,r)}findIndex(t){if(t==0)return dp(0,t);if(t==this.size)return dp(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,r=0;;n++){let s=this.child(n),i=r+s.nodeSize;if(i>=t)return i==t?dp(n+1,i):dp(n,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return we.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return we.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return we.empty;let n,r=0;for(let s=0;s<t.length;s++){let i=t[s];r+=i.nodeSize,s&&i.isText&&t[s-1].sameMarkup(i)?(n||(n=t.slice(0,s)),n[n.length-1]=i.withText(n[n.length-1].text+i.text)):n&&n.push(i)}return new we(n||t,r)}static from(t){if(!t)return we.empty;if(t instanceof we)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new we([t],t.nodeSize);throw new RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}we.empty=new we([],0);const Zg={index:0,offset:0};function dp(e,t){return Zg.index=e,Zg.offset=t,Zg}function Qh(e,t){if(e===t)return!0;if(!(e&&typeof e=="object")||!(t&&typeof t=="object"))return!1;let n=Array.isArray(e);if(Array.isArray(t)!=n)return!1;if(n){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!Qh(e[r],t[r]))return!1}else{for(let r in e)if(!(r in t)||!Qh(e[r],t[r]))return!1;for(let r in t)if(!(r in e))return!1}return!0}let dn=class sy{constructor(t,n){this.type=t,this.attrs=n}addToSet(t){let n,r=!1;for(let s=0;s<t.length;s++){let i=t[s];if(this.eq(i))return t;if(this.type.excludes(i.type))n||(n=t.slice(0,s));else{if(i.type.excludes(this.type))return t;!r&&i.type.rank>this.type.rank&&(n||(n=t.slice(0,s)),n.push(this),r=!0),n&&n.push(i)}}return n||(n=t.slice()),r||n.push(this),n}removeFromSet(t){for(let n=0;n<t.length;n++)if(this.eq(t[n]))return t.slice(0,n).concat(t.slice(n+1));return t}isInSet(t){for(let n=0;n<t.length;n++)if(this.eq(t[n]))return!0;return!1}eq(t){return this==t||this.type==t.type&&Qh(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Mark.fromJSON");let r=t.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);let s=r.create(n.attrs);return r.checkAttrs(s.attrs),s}static sameSet(t,n){if(t==n)return!0;if(t.length!=n.length)return!1;for(let r=0;r<t.length;r++)if(!t[r].eq(n[r]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return sy.none;if(t instanceof sy)return[t];let n=t.slice();return n.sort((r,s)=>r.type.rank-s.type.rank),n}};dn.none=[];class Jh extends Error{}class Te{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=DR(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new Te(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Te(IR(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return Te.empty;let r=n.openStart||0,s=n.openEnd||0;if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Te(we.fromJSON(t,n.content),r,s)}static maxOpen(t,n=!0){let r=0,s=0;for(let i=t.firstChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=t.lastChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.lastChild)s++;return new Te(t,r,s)}}Te.empty=new Te(we.empty,0,0);function IR(e,t,n){let{index:r,offset:s}=e.findIndex(t),i=e.maybeChild(r),{index:o,offset:l}=e.findIndex(n);if(s==t||i.isText){if(l!=n&&!e.child(o).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return e.replaceChild(r,i.copy(IR(i.content,t-s-1,n-s-1)))}function DR(e,t,n,r,s,i){let{index:o,offset:l}=e.findIndex(t),c=e.maybeChild(o);if(l==t||c.isText)return i&&r<=0&&s<=0&&!i.canReplace(o,o,n)?null:e.cut(0,t).append(n).append(e.cut(t));let d=DR(c.content,t-l-1,n,o==0?r-1:0,o==e.childCount-1?s-1:0,c);return d&&e.replaceChild(o,c.copy(d))}function b7(e,t,n){if(n.openStart>e.depth)throw new Jh("Inserted content deeper than insertion position");if(e.depth-n.openStart!=t.depth-n.openEnd)throw new Jh("Inconsistent open depths");return AR(e,t,n,0)}function AR(e,t,n,r){let s=e.index(r),i=e.node(r);if(s==t.index(r)&&r<e.depth-n.openStart){let o=AR(e,t,n,r+1);return i.copy(i.content.replaceChild(s,o))}else if(n.content.size)if(!n.openStart&&!n.openEnd&&e.depth==r&&t.depth==r){let o=e.parent,l=o.content;return Ba(o,l.cut(0,e.parentOffset).append(n.content).append(l.cut(t.parentOffset)))}else{let{start:o,end:l}=y7(n,e);return Ba(i,RR(e,o,l,t,r))}else return Ba(i,Xh(e,t,r))}function MR(e,t){if(!t.type.compatibleContent(e.type))throw new Jh("Cannot join "+t.type.name+" onto "+e.type.name)}function iy(e,t,n){let r=e.node(n);return MR(r,t.node(n)),r}function za(e,t){let n=t.length-1;n>=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function md(e,t,n,r){let s=(t||e).node(n),i=0,o=t?t.index(n):s.childCount;e&&(i=e.index(n),e.depth>n?i++:e.textOffset&&(za(e.nodeAfter,r),i++));for(let l=i;l<o;l++)za(s.child(l),r);t&&t.depth==n&&t.textOffset&&za(t.nodeBefore,r)}function Ba(e,t){return e.type.checkContent(t),e.copy(t)}function RR(e,t,n,r,s){let i=e.depth>s&&iy(e,t,s+1),o=r.depth>s&&iy(n,r,s+1),l=[];return md(null,e,s,l),i&&o&&t.index(s)==n.index(s)?(MR(i,o),za(Ba(i,RR(e,t,n,r,s+1)),l)):(i&&za(Ba(i,Xh(e,t,s+1)),l),md(t,n,s,l),o&&za(Ba(o,Xh(n,r,s+1)),l)),md(r,null,s,l),new we(l)}function Xh(e,t,n){let r=[];if(md(null,e,n,r),e.depth>n){let s=iy(e,t,n+1);za(Ba(s,Xh(e,t,n+1)),r)}return md(t,null,n,r),new we(r)}function y7(e,t){let n=t.depth-e.openStart,s=t.node(n).copy(e.content);for(let i=n-1;i>=0;i--)s=t.node(i).copy(we.from(s));return{start:s.resolveNoCache(e.openStart+n),end:s.resolveNoCache(s.content.size-e.openEnd-n)}}class Ld{constructor(t,n,r){this.pos=t,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,n=this.index(this.depth);if(n==t.childCount)return null;let r=this.pos-this.path[this.path.length-1],s=t.child(n);return r?t.child(n).cut(r):s}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let r=this.path[n*3],s=n==0?0:this.path[n*3-1]+1;for(let i=0;i<t;i++)s+=r.child(i).nodeSize;return s}marks(){let t=this.parent,n=this.index();if(t.content.size==0)return dn.none;if(this.textOffset)return t.child(n).marks;let r=t.maybeChild(n-1),s=t.maybeChild(n);if(!r){let l=r;r=s,s=l}let i=r.marks;for(var o=0;o<i.length;o++)i[o].type.spec.inclusive===!1&&(!s||!i[o].isInSet(s.marks))&&(i=i[o--].removeFromSet(i));return i}marksAcross(t){let n=this.parent.maybeChild(this.index());if(!n||!n.isInline)return null;let r=n.marks,s=t.parent.maybeChild(t.index());for(var i=0;i<r.length;i++)r[i].type.spec.inclusive===!1&&(!s||!r[i].isInSet(s.marks))&&(r=r[i--].removeFromSet(r));return r}sharedDepth(t){for(let n=this.depth;n>0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos<this.pos)return t.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==t.pos?1:0);r>=0;r--)if(t.pos<=this.end(r)&&(!n||n(this.node(r))))return new Zh(this,t,r);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos<this.pos?t:this}toString(){let t="";for(let n=1;n<=this.depth;n++)t+=(t?"/":"")+this.node(n).type.name+"_"+this.index(n-1);return t+":"+this.parentOffset}static resolve(t,n){if(!(n>=0&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let r=[],s=0,i=n;for(let o=t;;){let{index:l,offset:c}=o.content.findIndex(i),d=i-c;if(r.push(o,l,s+c),!d||(o=o.child(l),o.isText))break;i=d-1,s+=c+1}return new Ld(n,r,i)}static resolveCached(t,n){let r=Uk.get(t);if(r)for(let i=0;i<r.elts.length;i++){let o=r.elts[i];if(o.pos==n)return o}else Uk.set(t,r=new v7);let s=r.elts[r.i]=Ld.resolve(t,n);return r.i=(r.i+1)%C7,s}}class v7{constructor(){this.elts=[],this.i=0}}const C7=12,Uk=new WeakMap;class Zh{constructor(t,n,r){this.$from=t,this.$to=n,this.depth=r}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const w7=Object.create(null);let Ua=class ay{constructor(t,n,r,s=dn.none){this.type=t,this.attrs=n,this.marks=s,this.content=r||we.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(t){return this.content.child(t)}maybeChild(t){return this.content.maybeChild(t)}forEach(t){this.content.forEach(t)}nodesBetween(t,n,r,s=0){this.content.nodesBetween(t,n,r,s,this)}descendants(t){this.nodesBetween(0,this.content.size,t)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(t,n,r,s){return this.content.textBetween(t,n,r,s)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(t){return this==t||this.sameMarkup(t)&&this.content.eq(t.content)}sameMarkup(t){return this.hasMarkup(t.type,t.attrs,t.marks)}hasMarkup(t,n,r){return this.type==t&&Qh(this.attrs,n||t.defaultAttrs||w7)&&dn.sameSet(this.marks,r||dn.none)}copy(t=null){return t==this.content?this:new ay(this.type,this.attrs,t,this.marks)}mark(t){return t==this.marks?this:new ay(this.type,this.attrs,this.content,t)}cut(t,n=this.content.size){return t==0&&n==this.content.size?this:this.copy(this.content.cut(t,n))}slice(t,n=this.content.size,r=!1){if(t==n)return Te.empty;let s=this.resolve(t),i=this.resolve(n),o=r?0:s.sharedDepth(n),l=s.start(o),d=s.node(o).content.cut(s.pos-l,i.pos-l);return new Te(d,s.depth-o,i.depth-o)}replace(t,n,r){return b7(this.resolve(t),this.resolve(n),r)}nodeAt(t){for(let n=this;;){let{index:r,offset:s}=n.content.findIndex(t);if(n=n.maybeChild(r),!n)return null;if(s==t||n.isText)return n;t-=s+1}}childAfter(t){let{index:n,offset:r}=this.content.findIndex(t);return{node:this.content.maybeChild(n),index:n,offset:r}}childBefore(t){if(t==0)return{node:null,index:0,offset:0};let{index:n,offset:r}=this.content.findIndex(t);if(r<t)return{node:this.content.child(n),index:n,offset:r};let s=this.content.child(n-1);return{node:s,index:n-1,offset:r-s.nodeSize}}resolve(t){return Ld.resolveCached(this,t)}resolveNoCache(t){return Ld.resolve(this,t)}rangeHasMark(t,n,r){let s=!1;return n>t&&this.nodesBetween(t,n,i=>(r.isInSet(i.marks)&&(s=!0),!s)),s}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),NR(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,r=we.empty,s=0,i=r.childCount){let o=this.contentMatchAt(t).matchFragment(r,s,i),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=s;c<i;c++)if(!this.type.allowsMarks(r.child(c).marks))return!1;return!0}canReplaceWith(t,n,r,s){if(s&&!this.type.allowsMarks(s))return!1;let i=this.contentMatchAt(t).matchType(r),o=i&&i.matchFragment(this.content,n);return o?o.validEnd:!1}canAppend(t){return t.content.size?this.canReplace(this.childCount,this.childCount,t.content):this.type.compatibleContent(t.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let t=dn.none;for(let n=0;n<this.marks.length;n++){let r=this.marks[n];r.type.checkAttrs(r.attrs),t=r.addToSet(t)}if(!dn.sameSet(t,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(n=>n.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,r)}let s=we.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,s,r);return i.type.checkAttrs(i.attrs),i}};Ua.prototype.text=void 0;class ef extends Ua{constructor(t,n,r,s){if(super(t,n,null,s),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):NR(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new ef(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new ef(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function NR(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+"("+t+")";return t}class to{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new S7(t,n);if(r.next==null)return to.empty;let s=OR(r);r.next&&r.err("Unexpected trailing text");let i=D7(I7(s));return A7(i,r),i}matchType(t){for(let n=0;n<this.next.length;n++)if(this.next[n].type==t)return this.next[n].next;return null}matchFragment(t,n=0,r=t.childCount){let s=this;for(let i=n;s&&i<r;i++)s=s.matchType(t.child(i).type);return s}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:n}=this.next[t];if(!(n.isText||n.hasRequiredAttrs()))return n}return null}compatible(t){for(let n=0;n<this.next.length;n++)for(let r=0;r<t.next.length;r++)if(this.next[n].type==t.next[r].type)return!0;return!1}fillBefore(t,n=!1,r=0){let s=[this];function i(o,l){let c=o.matchFragment(t,r);if(c&&(!n||c.validEnd))return we.from(l.map(d=>d.createAndFill()));for(let d=0;d<o.next.length;d++){let{type:u,next:p}=o.next[d];if(!(u.isText||u.hasRequiredAttrs())&&s.indexOf(p)==-1){s.push(p);let h=i(p,l.concat(u));if(h)return h}}return null}return i(this,[])}findWrapping(t){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==t)return this.wrapCache[r+1];let n=this.computeWrapping(t);return this.wrapCache.push(t,n),n}computeWrapping(t){let n=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let s=r.shift(),i=s.match;if(i.matchType(t)){let o=[];for(let l=s;l.type;l=l.via)o.push(l.type);return o.reverse()}for(let o=0;o<i.next.length;o++){let{type:l,next:c}=i.next[o];!l.isLeaf&&!l.hasRequiredAttrs()&&!(l.name in n)&&(!s.type||c.validEnd)&&(r.push({match:l.contentMatch,type:l,via:s}),n[l.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function n(r){t.push(r);for(let s=0;s<r.next.length;s++)t.indexOf(r.next[s].next)==-1&&n(r.next[s].next)}return n(this),t.map((r,s)=>{let i=s+(r.validEnd?"*":" ")+" ";for(let o=0;o<r.next.length;o++)i+=(o?", ":"")+r.next[o].type.name+"->"+t.indexOf(r.next[o].next);return i}).join(` 43`)}}to.empty=new to(!0);class S7{constructor(t,n){this.string=t,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function OR(e){let t=[];do t.push(j7(e));while(e.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function j7(e){let t=[];do t.push(k7(e));while(e.next&&e.next!=")"&&e.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function k7(e){let t=T7(e);for(;;)if(e.eat("+"))t={type:"plus",expr:t};else if(e.eat("*"))t={type:"star",expr:t};else if(e.eat("?"))t={type:"opt",expr:t};else if(e.eat("{"))t=E7(e,t);else break;return t}function Vk(e){/\D/.test(e.next)&&e.err("Expected number, got '"+e.next+"'");let t=Number(e.next);return e.pos++,t}function E7(e,t){let n=Vk(e),r=n;return e.eat(",")&&(e.next!="}"?r=Vk(e):r=-1),e.eat("}")||e.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function _7(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let s=[];for(let i in n){let o=n[i];o.isInGroup(t)&&s.push(o)}return s.length==0&&e.err("No node type or group '"+t+"' found"),s}function T7(e){if(e.eat("(")){let t=OR(e);return e.eat(")")||e.err("Missing closing paren"),t}else if(/\W/.test(e.next))e.err("Unexpected token '"+e.next+"'");else{let t=_7(e,e.next).map(n=>(e.inline==null?e.inline=n.isInline:e.inline!=n.isInline&&e.err("Mixing inline and block content"),{type:"name",value:n}));return e.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function I7(e){let t=[[]];return s(i(e,0),n()),t;function n(){return t.push([])-1}function r(o,l,c){let d={term:c,to:l};return t[o].push(d),d}function s(o,l){o.forEach(c=>c.to=l)}function i(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(i(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=i(o.exprs[c],l);if(c==o.exprs.length-1)return d;s(d,l=n())}else if(o.type=="star"){let c=n();return r(l,c),s(i(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return s(i(o.expr,l),c),s(i(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(i(o.expr,l));if(o.type=="range"){let c=l;for(let d=0;d<o.min;d++){let u=n();s(i(o.expr,c),u),c=u}if(o.max==-1)s(i(o.expr,c),c);else for(let d=o.min;d<o.max;d++){let u=n();r(c,u),s(i(o.expr,c),u),c=u}return[r(c)]}else{if(o.type=="name")return[r(l,void 0,o.value)];throw new Error("Unknown expr type")}}}}function PR(e,t){return t-e}function Wk(e,t){let n=[];return r(t),n.sort(PR);function r(s){let i=e[s];if(i.length==1&&!i[0].term)return r(i[0].to);n.push(s);for(let o=0;o<i.length;o++){let{term:l,to:c}=i[o];!l&&n.indexOf(c)==-1&&r(c)}}}function D7(e){let t=Object.create(null);return n(Wk(e,0));function n(r){let s=[];r.forEach(o=>{e[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u<s.length;u++)s[u][0]==l&&(d=s[u][1]);Wk(e,c).forEach(u=>{d||s.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let i=t[r.join(",")]=new to(r.indexOf(e.length-1)>-1);for(let o=0;o<s.length;o++){let l=s[o][1].sort(PR);i.next.push({type:s[o][0],next:t[l.join(",")]||n(l)})}return i}}function A7(e,t){for(let n=0,r=[e];n<r.length;n++){let s=r[n],i=!s.validEnd,o=[];for(let l=0;l<s.next.length;l++){let{type:c,next:d}=s.next[l];o.push(c.name),i&&!(c.isText||c.hasRequiredAttrs())&&(i=!1),r.indexOf(d)==-1&&r.push(d)}i&&t.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function LR(e){let t=Object.create(null);for(let n in e){let r=e[n];if(!r.hasDefault)return null;t[n]=r.default}return t}function FR(e,t){let n=Object.create(null);for(let r in e){let s=t&&t[r];if(s===void 0){let i=e[r];if(i.hasDefault)s=i.default;else throw new RangeError("No value supplied for attribute "+r)}n[r]=s}return n}function $R(e,t,n,r){for(let s in t)if(!(s in e))throw new RangeError(`Unsupported attribute ${s} for ${n} of type ${s}`);for(let s in e){let i=e[s];i.validate&&i.validate(t[s])}}function zR(e,t){let n=Object.create(null);if(t)for(let r in t)n[r]=new R7(e,r,t[r]);return n}let Hk=class BR{constructor(t,n,r){this.name=t,this.schema=n,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=zR(t,r.attrs),this.defaultAttrs=LR(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||t=="text"),this.isText=t=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==to.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(t){return this.groups.indexOf(t)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:FR(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Ua(this,this.computeAttrs(t),we.from(n),dn.setFrom(r))}createChecked(t=null,n,r){return n=we.from(n),this.checkContent(n),new Ua(this,this.computeAttrs(t),n,dn.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=we.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let s=this.contentMatch.matchFragment(n),i=s&&s.fillBefore(we.empty,!0);return i?new Ua(this,t,n.append(i),dn.setFrom(r)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let r=0;r<t.childCount;r++)if(!this.allowsMarks(t.child(r).marks))return!1;return!0}checkContent(t){if(!this.validContent(t))throw new RangeError(`Invalid content for node ${this.name}: ${t.toString().slice(0,50)}`)}checkAttrs(t){$R(this.attrs,t,"node",this.name)}allowsMarkType(t){return this.markSet==null||this.markSet.indexOf(t)>-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;n<t.length;n++)if(!this.allowsMarkType(t[n].type))return!1;return!0}allowedMarks(t){if(this.markSet==null)return t;let n;for(let r=0;r<t.length;r++)this.allowsMarkType(t[r].type)?n&&n.push(t[r]):n||(n=t.slice(0,r));return n?n.length?n:dn.none:t}static compile(t,n){let r=Object.create(null);t.forEach((i,o)=>r[i]=new BR(i,n,o));let s=n.spec.topNode||"doc";if(!r[s])throw new RangeError("Schema is missing its top node type ('"+s+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let i in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function M7(e,t,n){let r=n.split("|");return s=>{let i=s===null?"null":typeof s;if(r.indexOf(i)<0)throw new RangeError(`Expected value of type ${r} for attribute ${t} on type ${e}, got ${i}`)}}class R7{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?M7(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class $m{constructor(t,n,r,s){this.name=t,this.rank=n,this.schema=r,this.spec=s,this.attrs=zR(t,s.attrs),this.excluded=null;let i=LR(this.attrs);this.instance=i?new dn(this,i):null}create(t=null){return!t&&this.instance?this.instance:new dn(this,FR(this.attrs,t))}static compile(t,n){let r=Object.create(null),s=0;return t.forEach((i,o)=>r[i]=new $m(i,s++,n,o)),r}removeFromSet(t){for(var n=0;n<t.length;n++)t[n].type==this&&(t=t.slice(0,n).concat(t.slice(n+1)),n--);return t}isInSet(t){for(let n=0;n<t.length;n++)if(t[n].type==this)return t[n]}checkAttrs(t){$R(this.attrs,t,"mark",this.name)}excludes(t){return this.excluded.indexOf(t)>-1}}class UR{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let s in t)n[s]=t[s];n.nodes=rr.from(t.nodes),n.marks=rr.from(t.marks||{}),this.nodes=Hk.compile(this.spec.nodes,this),this.marks=$m.compile(this.spec.marks,this);let r=Object.create(null);for(let s in this.nodes){if(s in this.marks)throw new RangeError(s+" can not be both a node and a mark");let i=this.nodes[s],o=i.spec.content||"",l=i.spec.marks;if(i.contentMatch=r[o]||(r[o]=to.parse(o,this.nodes)),i.inlineContent=i.contentMatch.inlineContent,i.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!i.isInline||!i.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=i}i.markSet=l=="_"?null:l?qk(this,l.split(" ")):l==""||!i.inlineContent?[]:null}for(let s in this.marks){let i=this.marks[s],o=i.spec.excludes;i.excluded=o==null?[i]:o==""?[]:qk(this,o.split(" "))}this.nodeFromJSON=s=>Ua.fromJSON(this,s),this.markFromJSON=s=>dn.fromJSON(this,s),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,r,s){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof Hk){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(n,r,s)}text(t,n){let r=this.nodes.text;return new ef(r,r.defaultAttrs,t,dn.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}}function qk(e,t){let n=[];for(let r=0;r<t.length;r++){let s=t[r],i=e.marks[s],o=i;if(i)n.push(i);else for(let l in e.marks){let c=e.marks[l];(s=="_"||c.spec.group&&c.spec.group.split(" ").indexOf(s)>-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+t[r]+"'")}return n}function N7(e){return e.tag!=null}function O7(e){return e.style!=null}class Xi{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(s=>{if(N7(s))this.tags.push(s);else if(O7(s)){let i=/[^=]*/.exec(s.style)[0];r.indexOf(i)<0&&r.push(i),this.styles.push(s)}}),this.normalizeLists=!this.tags.some(s=>{if(!/^(ul|ol)\b/.test(s.tag)||!s.node)return!1;let i=t.nodes[s.node];return i.contentMatch.matchType(i)})}parse(t,n={}){let r=new Yk(this,n,!1);return r.addAll(t,dn.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new Yk(this,n,!0);return r.addAll(t,dn.none,n.from,n.to),Te.maxOpen(r.finish())}matchTag(t,n,r){for(let s=r?this.tags.indexOf(r)+1:0;s<this.tags.length;s++){let i=this.tags[s];if(F7(t,i.tag)&&(i.namespace===void 0||t.namespaceURI==i.namespace)&&(!i.context||n.matchesContext(i.context))){if(i.getAttrs){let o=i.getAttrs(t);if(o===!1)continue;i.attrs=o||void 0}return i}}}matchStyle(t,n,r,s){for(let i=s?this.styles.indexOf(s)+1:0;i<this.styles.length;i++){let o=this.styles[i],l=o.style;if(!(l.indexOf(t)!=0||o.context&&!r.matchesContext(o.context)||l.length>t.length&&(l.charCodeAt(t.length)!=61||l.slice(t.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(t){let n=[];function r(s){let i=s.priority==null?50:s.priority,o=0;for(;o<n.length;o++){let l=n[o];if((l.priority==null?50:l.priority)<i)break}n.splice(o,0,s)}for(let s in t.marks){let i=t.marks[s].spec.parseDOM;i&&i.forEach(o=>{r(o=Kk(o)),o.mark||o.ignore||o.clearMark||(o.mark=s)})}for(let s in t.nodes){let i=t.nodes[s].spec.parseDOM;i&&i.forEach(o=>{r(o=Kk(o)),o.node||o.ignore||o.mark||(o.node=s)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Xi(t,Xi.schemaRules(t)))}}const VR={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},P7={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},WR={ol:!0,ul:!0},Fd=1,oy=2,gd=4;
vendor: 8,236 bytes, lines 43-45
43function Gk(e,t,n){return t!=null?(t?Fd:0)|(t==="full"?oy:0):e&&e.whitespace=="pre"?Fd|oy:n&~gd}class up{constructor(t,n,r,s,i,o){this.type=t,this.attrs=n,this.marks=r,this.solid=s,this.options=o,this.content=[],this.activeMarks=dn.none,this.match=i||(o&gd?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(we.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,s;return(s=r.findWrapping(t.type))?(this.match=r,s):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&Fd)){let r=this.content[this.content.length-1],s;if(r&&r.isText&&(s=/[ \t\r\n\u000c]+$/.exec(r.text))){let i=r;r.text.length==s[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-s[0].length))}}let n=we.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(we.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!VR.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Yk{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let s=n.topNode,i,o=Gk(null,n.preserveWhitespace,0)|(r?gd:0);s?i=new up(s.type,s.attrs,dn.none,!0,n.topMatch||s.type.contentMatch,o):r?i=new up(null,null,dn.none,!0,null,o):i=new up(t.schema.topNodeType,null,dn.none,!0,null,o),this.nodes=[i],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let r=t.nodeValue,s=this.top,i=s.options&oy?"full":this.localPreserveWS||(s.options&Fd)>0,{schema:o}=this.parser;if(i==="full"||s.inlineContext(t)||/[^ \t\r\n\u000c]/.test(r)){if(i)if(i==="full")r=r.replace(/\r\n?/g,` 44`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c<l.length;c++)c&&this.insertNode(o.linebreakReplacement.create(),n,!0),l[c]&&this.insertNode(o.text(l[c]),n,!/\S/.test(l[c]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let l=s.content[s.content.length-1],c=t.previousSibling;(!l||c&&c.nodeName=="BR"||l.isText&&/[ \t\r\n\u000c]$/.test(l.text))&&(r=r.slice(1))}r&&this.insertNode(o.text(r),n,!/\S/.test(r)),this.findInText(t)}else this.findInside(t)}addElement(t,n,r){let s=this.localPreserveWS,i=this.top;(t.tagName=="PRE"||/pre/.test(t.style&&t.style.whiteSpace))&&(this.localPreserveWS=!0);let o=t.nodeName.toLowerCase(),l;WR.hasOwnProperty(o)&&this.parser.normalizeLists&&L7(t);let c=this.options.ruleFromNode&&this.options.ruleFromNode(t)||(l=this.parser.matchTag(t,this,r));e:if(c?c.ignore:P7.hasOwnProperty(o))this.findInside(t),this.ignoreFallback(t,n);else if(!c||c.skip||c.closeParent){c&&c.closeParent?this.open=Math.max(0,this.open-1):c&&c.skip.nodeType&&(t=c.skip);let d,u=this.needsBlock;if(VR.hasOwnProperty(o))i.content.length&&i.content[0].isInline&&this.open&&(this.open--,i=this.top),d=!0,i.type||(this.needsBlock=!0);else if(!t.firstChild){this.leafFallback(t,n);break e}let p=c&&c.skip?n:this.readStyles(t,n);p&&this.addAll(t,p),d&&this.sync(i),this.needsBlock=u}else{let d=this.readStyles(t,n);d&&this.addElementByRule(t,c,d,c.consuming===!1?l:void 0)}this.localPreserveWS=s}leafFallback(t,n){t.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(t.ownerDocument.createTextNode(` 45`),n)}ignoreFallback(t,n){t.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(t,n){let r=t.style;if(r&&r.length)for(let s=0;s<this.parser.matchedStyles.length;s++){let i=this.parser.matchedStyles[s],o=r.getPropertyValue(i);if(o)for(let l=void 0;;){let c=this.parser.matchStyle(i,o,this,l);if(!c)break;if(c.ignore)return null;if(c.clearMark?n=n.filter(d=>!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(t,n,r,s){let i,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,t.nodeName=="BR")||this.leafFallback(t,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(i=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(t);else if(s)this.addElement(t,r,s);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c,r),this.findAround(t,c,!1)}i&&this.sync(l)&&this.open--}addAll(t,n,r,s){let i=r||0;for(let o=r?t.childNodes[r]:t.firstChild,l=s==null?null:t.childNodes[s];o!=l;o=o.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(o,n);this.findAtPoint(t,i)}findPlace(t,n,r){let s,i;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],d=c.findWrapping(t);if(d&&(!s||s.length>d.length+l)&&(s=d,i=c,!d.length))break;if(c.solid){if(r)break;l+=2}}if(!s)return null;this.sync(i);for(let o=0;o<s.length;o++)n=this.enterInner(s[o],null,n,!1);return n}insertNode(t,n,r){if(t.isInline&&this.needsBlock&&!this.top.type){let i=this.textblockFromContext();i&&(n=this.enterInner(i,null,n))}let s=this.findPlace(t,n,r);if(s){this.closeExtra();let i=this.top;i.match&&(i.match=i.match.matchType(t.type));let o=dn.none;for(let l of s.concat(t.marks))(i.type?i.type.allowsMarkType(l.type):Qk(l.type,t.type))&&(o=l.addToSet(o));return i.content.push(t.mark(o)),!0}return!1}enter(t,n,r,s){let i=this.findPlace(t.create(n),r,!1);return i&&(i=this.enterInner(t,n,r,!0,s)),i}enterInner(t,n,r,s=!1,i){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(t);let l=Gk(t,i,o.options);o.options&gd&&o.content.length==0&&(l|=gd);let c=dn.none;return r=r.filter(d=>(o.type?o.type.allowsMarkType(d.type):Qk(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new up(t,n,c,s,null,l)),this.open++,r}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Fd)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let s=r.length-1;s>=0;s--)t+=r[s].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==t&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&t.nodeType==1&&t.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(t,n,r){if(t!=n&&this.find)for(let s=0;s<this.find.length;s++)this.find[s].pos==null&&t.nodeType==1&&t.contains(this.find[s].node)&&n.compareDocumentPosition(this.find[s].node)&(r?2:4)&&(this.find[s].pos=this.currentPos)}findInText(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==t&&(this.find[n].pos=this.currentPos-(t.nodeValue.length-this.find[n].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,s=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),i=-(r?r.depth+1:0)+(s?0:1),o=(l,c)=>{for(;l>=0;l--){let d=n[l];if(d==""){if(l==n.length-1||l==0)continue;for(;c>=i;c--)if(o(l-1,c))return!0;return!1}else{let u=c>0||c==0&&s?this.nodes[c].type:r&&c>=i?r.node(c-i).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;
vendor: 15,523 bytes, line 45
45if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function L7(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&WR.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function F7(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function Kk(e){let t={};for(let n in e)t[n]=e[n];return t}function Qk(e,t){let n=t.schema.nodes;for(let r in n){let s=n[r];if(!s.allowsMarkType(e))continue;let i=[],o=l=>{i.push(l);for(let c=0;c<l.edgeCount;c++){let{type:d,next:u}=l.edge(c);if(d==t||i.indexOf(u)<0&&o(u))return!0}};if(o(s.contentMatch))return!0}}class zm{constructor(t,n){this.nodes=t,this.marks=n}serializeFragment(t,n={},r){r||(r=pp(n).createDocumentFragment());let s=r,i=[];return t.forEach(o=>{if(i.length||o.marks.length){let l=0,c=0;for(;l<i.length&&c<o.marks.length;){let d=o.marks[c];if(!this.marks[d.type.name]){c++;continue}if(!d.eq(i[l][0])||d.type.spec.spanning===!1)break;l++,c++}for(;l<i.length;)s=i.pop()[1];for(;c<o.marks.length;){let d=o.marks[c++],u=this.serializeMark(d,o.isInline,n);u&&(i.push([d,s]),s.appendChild(u.dom),s=u.contentDOM||u.dom)}}s.appendChild(this.serializeNodeInner(o,n))}),r}serializeNodeInner(t,n){if(t.isText)return pp(n).createTextNode(t.text);let{dom:r,contentDOM:s}=gh(pp(n),this.nodes[t.type.name](t),null,t.attrs);if(s){if(t.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(t.content,n,s)}return r}serializeNode(t,n={}){let r=this.serializeNodeInner(t,n);for(let s=t.marks.length-1;s>=0;s--){let i=this.serializeMark(t.marks[s],t.isInline,n);i&&((i.contentDOM||i.dom).appendChild(r),r=i.dom)}return r}serializeMark(t,n,r={}){let s=this.marks[t.type.name];return s&&gh(pp(r),s(t,n),null,t.attrs)}static renderSpec(t,n,r=null,s){return typeof n=="string"?{dom:t.createTextNode(n)}:gh(t,n,r,s)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new zm(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=Jk(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return Jk(t.marks)}}function Jk(e){let t={};for(let n in e){let r=e[n].spec.toDOM;r&&(t[n]=r)}return t}function pp(e){return e.document||window.document}const Xk=new WeakMap;function $7(e){let t=Xk.get(e);return t===void 0&&Xk.set(e,t=z7(e)),t}function z7(e){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let s=0;s<r.length;s++)n(r[s]);else for(let s in r)n(r[s])}return n(e),t}function gh(e,t,n,r){if(t.nodeType==1)return{dom:t};if(t.dom&&t.dom.nodeType==1)return t;let s=t[0],i;if(typeof s!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(i=$7(r))&&i.indexOf(t)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=s.indexOf(" ");o>0&&(n=s.slice(0,o),s=s.slice(o+1));let l,c=n?e.createElementNS(n,s):e.createElement(s),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let p in d)if(d[p]!=null){let h=p.indexOf(" ");h>0?c.setAttributeNS(p.slice(0,h),p.slice(h+1),d[p]):p=="style"&&c.style?c.style.cssText=d[p]:c.setAttribute(p,d[p])}}for(let p=u;p<t.length;p++){let h=t[p];if(h===0){if(p<t.length-1||p>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof h=="string")c.appendChild(e.createTextNode(h));else{let{dom:f,contentDOM:g}=gh(e,h,n,r);if(c.appendChild(f),g){if(l)throw new RangeError("Multiple content holes");l=g}}}return{dom:c,contentDOM:l}}const HR=65535,qR=Math.pow(2,16);function B7(e,t){return e+t*qR}function Zk(e){return e&HR}function U7(e){return(e-(e&HR))/qR}const GR=1,YR=2,xh=4,KR=8;class ly{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&KR)>0}get deletedBefore(){return(this.delInfo&(GR|xh))>0}get deletedAfter(){return(this.delInfo&(YR|xh))>0}get deletedAcross(){return(this.delInfo&xh)>0}}class Nr{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Nr.empty)return Nr.empty}recover(t){let n=0,r=Zk(t);if(!this.inverted)for(let s=0;s<r;s++)n+=this.ranges[s*3+2]-this.ranges[s*3+1];return this.ranges[r*3]+n+U7(t)}mapResult(t,n=1){return this._map(t,n,!1)}map(t,n=1){return this._map(t,n,!0)}_map(t,n,r){let s=0,i=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let c=this.ranges[l]-(this.inverted?s:0);if(c>t)break;let d=this.ranges[l+i],u=this.ranges[l+o],p=c+d;if(t<=p){let h=d?t==c?-1:t==p?1:n:n,f=c+s+(h<0?0:u);if(r)return f;let g=t==(n<0?c:p)?null:B7(l/3,t-c),x=t==c?YR:t==p?GR:xh;return(n<0?t!=c:t!=p)&&(x|=KR),new ly(f,x,g)}s+=u-d}return r?t+s:new ly(t+s,0,null)}touches(t,n){let r=0,s=Zk(n),i=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let c=this.ranges[l]-(this.inverted?r:0);if(c>t)break;let d=this.ranges[l+i],u=c+d;if(t<=u&&l==s*3)return!0;r+=this.ranges[l+o]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let s=0,i=0;s<this.ranges.length;s+=3){let o=this.ranges[s],l=o-(this.inverted?i:0),c=o+(this.inverted?0:i),d=this.ranges[s+n],u=this.ranges[s+r];t(l,l+d,c,c+u),i+=u-d}}invert(){return new Nr(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return t==0?Nr.empty:new Nr(t<0?[0,-t,0]:[0,0,t])}}Nr.empty=new Nr([]);class $d{constructor(t,n,r=0,s=t?t.length:0){this.mirror=n,this.from=r,this.to=s,this._maps=t||[],this.ownData=!(t||n)}get maps(){return this._maps}slice(t=0,n=this.maps.length){return new $d(this._maps,this.mirror,t,n)}appendMap(t,n){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(t),n!=null&&this.setMirror(this._maps.length-1,n)}appendMapping(t){for(let n=0,r=this._maps.length;n<t._maps.length;n++){let s=t.getMirror(n);this.appendMap(t._maps[n],s!=null&&s<n?r+s:void 0)}}getMirror(t){if(this.mirror){for(let n=0;n<this.mirror.length;n++)if(this.mirror[n]==t)return this.mirror[n+(n%2?-1:1)]}}setMirror(t,n){this.mirror||(this.mirror=[]),this.mirror.push(t,n)}appendMappingInverted(t){for(let n=t.maps.length-1,r=this._maps.length+t._maps.length;n>=0;n--){let s=t.getMirror(n);this.appendMap(t._maps[n].invert(),s!=null&&s>n?r-s-1:void 0)}}invert(){let t=new $d;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let r=this.from;r<this.to;r++)t=this._maps[r].map(t,n);return t}mapResult(t,n=1){return this._map(t,n,!1)}_map(t,n,r){let s=0;for(let i=this.from;i<this.to;i++){let o=this._maps[i],l=o.mapResult(t,n);if(l.recover!=null){let c=this.getMirror(i);if(c!=null&&c>i&&c<this.to){i=c,t=this._maps[c].recover(l.recover);continue}}s|=l.delInfo,t=l.pos}return r?t:new ly(t,s,null)}}const ex=Object.create(null);let ur=class{getMap(){return Nr.empty}merge(t){return null}static fromJSON(t,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=ex[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in ex)throw new RangeError("Duplicate use of step JSON ID "+t);return ex[t]=n,n.prototype.jsonID=t,n}};class Fn{constructor(t,n){this.doc=t,this.failed=n}static ok(t){return new Fn(t,null)}static fail(t){return new Fn(null,t)}static fromReplace(t,n,r,s){try{return Fn.ok(t.replace(n,r,s))}catch(i){if(i instanceof Jh)return Fn.fail(i.message);throw i}}}function zC(e,t,n){let r=[];for(let s=0;s<e.childCount;s++){let i=e.child(s);i.content.size&&(i=i.copy(zC(i.content,t,i))),i.isInline&&(i=t(i,n,s)),r.push(i)}return we.fromArray(r)}class Vi extends ur{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=t.resolve(this.from),s=r.node(r.sharedDepth(this.to)),i=new Te(zC(n.content,(o,l)=>!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),s),n.openStart,n.openEnd);return Fn.fromReplace(t,this.from,this.to,i)}invert(){return new ps(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Vi(n.pos,r.pos,this.mark)}merge(t){return t instanceof Vi&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Vi(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Vi(n.from,n.to,t.markFromJSON(n.mark))}}ur.jsonID("addMark",Vi);class ps extends ur{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new Te(zC(n.content,s=>s.mark(this.mark.removeFromSet(s.marks)),t),n.openStart,n.openEnd);return Fn.fromReplace(t,this.from,this.to,r)}invert(){return new Vi(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new ps(n.pos,r.pos,this.mark)}merge(t){return t instanceof ps&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new ps(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ps(n.from,n.to,t.markFromJSON(n.mark))}}ur.jsonID("removeMark",ps);class Wi extends ur{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Fn.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Fn.fromReplace(t,this.pos,this.pos+1,new Te(we.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let s=0;s<n.marks.length;s++)if(!n.marks[s].isInSet(r))return new Wi(this.pos,n.marks[s]);return new Wi(this.pos,this.mark)}}return new no(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new Wi(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new Wi(n.pos,t.markFromJSON(n.mark))}}ur.jsonID("addNodeMark",Wi);class no extends ur{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Fn.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Fn.fromReplace(t,this.pos,this.pos+1,new Te(we.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new Wi(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new no(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new no(n.pos,t.markFromJSON(n.mark))}}ur.jsonID("removeNodeMark",no);class Pn extends ur{constructor(t,n,r,s=!1){super(),this.from=t,this.to=n,this.slice=r,this.structure=s}apply(t){return this.structure&&cy(t,this.from,this.to)?Fn.fail("Structure replace would overwrite content"):Fn.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Nr([this.from,this.to-this.from,this.slice.size])}invert(t){return new Pn(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let n=t.mapResult(this.to,-1),r=this.from==this.to&&Pn.MAP_BIAS<0?n:t.mapResult(this.from,1);return r.deletedAcross&&n.deletedAcross?null:new Pn(r.pos,Math.max(r.pos,n.pos),this.slice,this.structure)}merge(t){if(!(t instanceof Pn)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let n=this.slice.size+t.slice.size==0?Te.empty:new Te(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new Pn(this.from,this.to+(t.to-t.from),n,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let n=this.slice.size+t.slice.size==0?Te.empty:new Te(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new Pn(t.from,this.to,n,this.structure)}else return null}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new Pn(n.from,n.to,Te.fromJSON(t,n.slice),!!n.structure)}}Pn.MAP_BIAS=1;ur.jsonID("replace",Pn);class Jn extends ur{constructor(t,n,r,s,i,o,l=!1){super(),this.from=t,this.to=n,this.gapFrom=r,this.gapTo=s,this.slice=i,this.insert=o,this.structure=l}apply(t){if(this.structure&&(cy(t,this.from,this.gapFrom)||cy(t,this.gapTo,this.to)))return Fn.fail("Structure gap-replace would overwrite content");let n=t.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Fn.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?Fn.fromReplace(t,this.from,this.to,r):Fn.fail("Content does not fit in gap")}getMap(){return new Nr([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let n=this.gapTo-this.gapFrom;return new Jn(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1),s=this.from==this.gapFrom?n.pos:t.map(this.gapFrom,-1),i=this.to==this.gapTo?r.pos:t.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||s<n.pos||i>r.pos?null:new Jn(n.pos,r.pos,s,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Jn(n.from,n.to,n.gapFrom,n.gapTo,Te.fromJSON(t,n.slice),n.insert,!!n.structure)}}ur.jsonID("replaceAround",Jn);function cy(e,t,n){let r=e.resolve(t),s=n-t,i=r.depth;for(;s>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,s--;if(s>0){let o=r.node(i).maybeChild(r.indexAfter(i));for(;s>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,s--}}return!1}function V7(e,t,n,r){let s=[],i=[],o,l;e.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let p=c.marks;if(!r.isInSet(p)&&u.type.allowsMarkType(r.type)){let h=Math.max(d,t),f=Math.min(d+c.nodeSize,n),g=r.addToSet(p);for(let x=0;x<p.length;x++)p[x].isInSet(g)||(o&&o.to==h&&o.mark.eq(p[x])?o.to=f:s.push(o=new ps(h,f,p[x])));l&&l.to==h?l.to=f:i.push(l=new Vi(h,f,r))}}
vendor: 4,085 bytes, lines 45-46
45),s.forEach(c=>e.step(c)),i.forEach(c=>e.step(c))}function W7(e,t,n,r){let s=[],i=0;e.doc.nodesBetween(t,n,(o,l)=>{if(!o.isInline)return;i++;let c=null;if(r instanceof $m){let d=o.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let d=Math.min(l+o.nodeSize,n);for(let u=0;u<c.length;u++){let p=c[u],h;for(let f=0;f<s.length;f++){let g=s[f];g.step==i-1&&p.eq(s[f].style)&&(h=g)}h?(h.to=d,h.step=i):s.push({style:p,from:Math.max(l,t),to:d,step:i})}}}),s.forEach(o=>e.step(new ps(o.from,o.to,o.style)))}function BC(e,t,n,r=n.contentMatch,s=!0){let i=e.doc.nodeAt(t),o=[],l=t+1;for(let c=0;c<i.childCount;c++){let d=i.child(c),u=l+d.nodeSize,p=r.matchType(d.type);if(!p)o.push(new Pn(l,u,Te.empty));else{r=p;for(let h=0;h<d.marks.length;h++)n.allowsMarkType(d.marks[h].type)||e.step(new ps(l,u,d.marks[h]));if(s&&d.isText&&n.whitespace!="pre"){let h,f=/\r?\n|\r/g,g;for(;h=f.exec(d.text);)g||(g=new Te(we.from(n.schema.text(" ",n.allowedMarks(d.marks))),0,0)),o.push(new Pn(l+h.index,l+h.index+h[0].length,g))}}l=u}if(!r.validEnd){let c=r.fillBefore(we.empty,!0);e.replace(l,l,new Te(c,0,0))}for(let c=o.length-1;c>=0;c--)e.step(o[c])}function H7(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function Ml(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let r=e.depth,s=0,i=0;;--r){let o=e.$from.node(r),l=e.$from.index(r)+s,c=e.$to.indexAfter(r)-i;if(r<e.depth&&o.canReplace(l,c,n))return r;if(r==0||o.type.spec.isolating||!H7(o,l,c))break;l&&(s=1),c<o.childCount&&(i=1)}return null}function q7(e,t,n){let{$from:r,$to:s,depth:i}=t,o=r.before(i+1),l=s.after(i+1),c=o,d=l,u=we.empty,p=0;for(let g=i,x=!1;g>n;g--)x||r.index(g)>0?(x=!0,u=we.from(r.node(g).copy(u)),p++):c--;let h=we.empty,f=0;for(let g=i,x=!1;g>n;g--)x||s.after(g+1)<s.end(g)?(x=!0,h=we.from(s.node(g).copy(h)),f++):d++;e.step(new Jn(c,d,o,l,new Te(u.append(h),p,f),u.size-p,!0))}function UC(e,t,n=null,r=e){let s=G7(e,t),i=s&&Y7(r,t);return i?s.map(e1).concat({type:t,attrs:n}).concat(i.map(e1)):null}function e1(e){return{type:e,attrs:null}}function G7(e,t){let{parent:n,startIndex:r,endIndex:s}=e,i=n.contentMatchAt(r).findWrapping(t);if(!i)return null;let o=i.length?i[0]:t;return n.canReplaceWith(r,s,o)?i:null}function Y7(e,t){let{parent:n,startIndex:r,endIndex:s}=e,i=n.child(r),o=t.contentMatch.findWrapping(i.type);if(!o)return null;let c=(o.length?o[o.length-1]:t).contentMatch;for(let d=r;c&&d<s;d++)c=c.matchType(n.child(d).type);return!c||!c.validEnd?null:o}function K7(e,t,n){let r=we.empty;for(let o=n.length-1;o>=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=we.from(n[o].type.create(n[o].attrs,r))}let s=t.start,i=t.end;e.step(new Jn(s,i,s,i,new Te(r,0,0),n.length,!0))}function Q7(e,t,n,r,s){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=e.steps.length;e.doc.nodesBetween(t,n,(o,l)=>{let c=typeof s=="function"?s(o):s;if(o.isTextblock&&!o.hasMarkup(r,c)&&J7(e.doc,e.mapping.slice(i).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!g?d=!1:!f&&g&&(d=!0)}d===!1&&JR(e,o,l,i),BC(e,e.mapping.slice(i).map(l,1),r,void 0,d===null);let u=e.mapping.slice(i),p=u.map(l,1),h=u.map(l+o.nodeSize,1);return e.step(new Jn(p,h,p+1,h-1,new Te(we.from(r.create(c,null,o.marks)),0,0),1,!0)),d===!0&&QR(e,o,l,i),!1}})}function QR(e,t,n,r){t.forEach((s,i)=>{if(s.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(s.text);){let c=e.mapping.slice(r).map(n+1+i+o.index);e.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function JR(e,t,n,r){t.forEach((s,i)=>{if(s.type==s.type.schema.linebreakReplacement){let o=e.mapping.slice(r).map(n+1+i);e.replaceWith(o,o+1,t.type.schema.text(` 46`))}})}function J7(e,t,n){let r=e.resolve(t),s=r.index();return r.parent.canReplaceWith(s,s+1,n)}
vendor: 8,456 bytes, line 46
46function X7(e,t,n,r,s){let i=e.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");n||(n=i.type);let o=n.create(r,null,s||i.marks);if(i.isLeaf)return e.replaceWith(t,t+i.nodeSize,o);if(!n.validContent(i.content))throw new RangeError("Invalid content for node type "+n.name);e.step(new Jn(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Te(we.from(o),0,0),1,!0))}function xi(e,t,n=1,r){let s=e.resolve(t),i=s.depth-n,o=r&&r[r.length-1]||s.parent;if(i<0||s.parent.type.spec.isolating||!s.parent.canReplace(s.index(),s.parent.childCount)||!o.type.validContent(s.parent.content.cutByIndex(s.index(),s.parent.childCount)))return!1;for(let d=s.depth-1,u=n-2;d>i;d--,u--){let p=s.node(d),h=s.index(d);if(p.type.spec.isolating)return!1;let f=p.content.cutByIndex(h,p.childCount),g=r&&r[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let x=r&&r[u]||p;if(!p.canReplace(h+1,p.childCount)||!x.type.validContent(f))return!1}let l=s.indexAfter(i),c=r&&r[0];return s.node(i).canReplaceWith(l,l,c?c.type:s.node(i+1).type)}function Z7(e,t,n=1,r){let s=e.doc.resolve(t),i=we.empty,o=we.empty;for(let l=s.depth,c=s.depth-n,d=n-1;l>c;l--,d--){i=we.from(s.node(l).copy(i));let u=r&&r[d];o=we.from(u?u.type.create(u.attrs,o):s.node(l).copy(o))}e.step(new Pn(t,t,new Te(i.append(o),n,n),!0))}function pa(e,t){let n=e.resolve(t),r=n.index();return XR(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function eQ(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:r}=e.type.schema;for(let s=0;s<t.childCount;s++){let i=t.child(s),o=i.type==r?e.type.schema.nodes.text:i.type;if(n=n.matchType(o),!n||!e.type.allowsMarks(i.marks))return!1}return n.validEnd}function XR(e,t){return!!(e&&t&&!e.isLeaf&&eQ(e,t))}function Bm(e,t,n=-1){let r=e.resolve(t);for(let s=r.depth;;s--){let i,o,l=r.index(s);if(s==r.depth?(i=r.nodeBefore,o=r.nodeAfter):n>0?(i=r.node(s+1),l++,o=r.node(s).maybeChild(l)):(i=r.node(s).maybeChild(l-1),o=r.node(s+1)),i&&!i.isTextblock&&XR(i,o)&&r.node(s).canReplace(l,l+1))return t;if(s==0)break;t=n<0?r.before(s):r.after(s)}}function tQ(e,t,n){let r=null,{linebreakReplacement:s}=e.doc.type.schema,i=e.doc.resolve(t-n),o=i.node().type;if(s&&o.inlineContent){let u=o.whitespace=="pre",p=!!o.contentMatch.matchType(s);u&&!p?r=!1:!u&&p&&(r=!0)}let l=e.steps.length;if(r===!1){let u=e.doc.resolve(t+n);JR(e,u.node(),u.before(),l)}o.inlineContent&&BC(e,t+n-1,o,i.node().contentMatchAt(i.index()),r==null);let c=e.mapping.slice(l),d=c.map(t-n);if(e.step(new Pn(d,c.map(t+n,-1),Te.empty,!0)),r===!0){let u=e.doc.resolve(d);QR(e,u.node(),u.before(),e.steps.length)}return e}function nQ(e,t,n){let r=e.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let s=r.depth-1;s>=0;s--){let i=r.index(s);if(r.node(s).canReplaceWith(i,i,n))return r.before(s+1);if(i>0)return null}if(r.parentOffset==r.parent.content.size)for(let s=r.depth-1;s>=0;s--){let i=r.indexAfter(s);if(r.node(s).canReplaceWith(i,i,n))return r.after(s+1);if(i<r.node(s).childCount)return null}return null}function ZR(e,t,n){let r=e.resolve(t);if(!n.content.size)return t;let s=n.content;for(let i=0;i<n.openStart;i++)s=s.firstChild.content;for(let i=1;i<=(n.openStart==0&&n.size?2:1);i++)for(let o=r.depth;o>=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,c=r.index(o)+(l>0?1:0),d=r.node(o),u=!1;if(i==1)u=d.canReplace(c,c,s);else{let p=d.contentMatchAt(c).findWrapping(s.firstChild.type);u=p&&d.canReplaceWith(c,c,p[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Um(e,t,n=t,r=Te.empty){if(t==n&&!r.size)return null;let s=e.resolve(t),i=e.resolve(n);return eN(s,i,r)?new Pn(t,n,r):new rQ(s,i,r).fit()}function eN(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}class rQ{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=we.empty;for(let s=0;s<=t.depth;s++){let i=t.node(s);this.frontier.push({type:i.type,match:i.contentMatchAt(t.indexAfter(s))})}for(let s=t.depth;s>0;s--)this.placed=we.from(t.node(s).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,s=this.close(t<0?this.$to:r.doc.resolve(t));if(!s)return null;let i=this.placed,o=r.depth,l=s.depth;for(;o&&l&&i.childCount==1;)i=i.firstChild.content,o--,l--;let c=new Te(i,o,l);return t>-1?new Jn(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Pn(r.pos,s.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,s=this.unplaced.openEnd;r<t;r++){let i=n.firstChild;if(n.childCount>1&&(s=0),i.type.spec.isolating&&s<=r){t=r;break}n=i.content}for(let n=1;n<=2;n++)for(let r=n==1?t:this.unplaced.openStart;r>=0;r--){let s,i=null;r?(i=tx(this.unplaced.content,r-1).firstChild,s=i.content):s=this.unplaced.content;let o=s.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:d}=this.frontier[l],u,p=null;if(n==1&&(o?d.matchType(o.type)||(p=d.fillBefore(we.from(o),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:r,frontierDepth:l,parent:i,inject:p};if(n==2&&o&&(u=d.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:i,wrap:u};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:n,openEnd:r}=this.unplaced,s=tx(t,n);return!s.childCount||s.firstChild.isLeaf?!1:(this.unplaced=new Te(t,n+1,Math.max(r,s.size+n>=t.size-r?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,s=tx(t,n);if(s.childCount<=1&&n>0){let i=t.size-n<=n+s.size;this.unplaced=new Te(rd(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Te(rd(t,n,1),n,r)}placeNodes({sliceDepth:t,frontierDepth:n,parent:r,inject:s,wrap:i}){for(;this.depth>n;)this.closeFrontierNode();if(i)for(let x=0;x<i.length;x++)this.openFrontierNode(i[x]);let o=this.unplaced,l=r?r.content:o.content,c=o.openStart-t,d=0,u=[],{match:p,type:h}=this.frontier[n];if(s){for(let x=0;x<s.childCount;x++)u.push(s.child(x));p=p.matchFragment(s)}let f=l.size+t-(o.content.size-o.openEnd);for(;d<l.childCount;){let x=l.child(d),b=p.matchType(x.type);if(!b)break;d++,(d>1||c==0||x.content.size)&&(p=b,u.push(tN(x.mark(h.allowedMarks(x.marks)),d==1?c:0,d==l.childCount?f:-1)))}let g=d==l.childCount;g||(f=-1),this.placed=sd(this.placed,n,we.from(u)),this.frontier[n].match=p,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let x=0,b=l;x<f;x++){let y=b.lastChild;this.frontier.push({type:y.type,match:y.contentMatchAt(y.childCount)}),b=y.content}this.unplaced=g?t==0?Te.empty:new Te(rd(o.content,t-1,1),t-1,f<0?o.openEnd:t-1):new Te(rd(o.content,t,d),o.openStart,o.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let t=this.frontier[this.depth],n;if(!t.type.isTextblock||!nx(this.$to,this.$to.depth,t.type,t.match,!1)||this.$to.depth==this.depth&&(n=this.findCloseLevel(this.$to))&&n.depth==this.depth)return-1;let{depth:r}=this.$to,s=this.$to.after(r);for(;r>1&&s==this.$to.end(--r);)++s;return s}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:r,type:s}=this.frontier[n],i=n<t.depth&&t.end(n+1)==t.pos+(t.depth-(n+1)),o=nx(t,n,s,r,i);if(o){for(let l=n-1;l>=0;l--){let{match:c,type:d}=this.frontier[l],u=nx(t,l,d,c,!0);if(!u||u.childCount)continue e}return{depth:n,fit:o,move:i?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=sd(this.placed,n.depth,n.fit)),t=n.move;for(let r=n.depth+1;r<=t.depth;r++){let s=t.node(r),i=s.type.contentMatch.fillBefore(s.content,!0,t.index(r));this.openFrontierNode(s.type,s.attrs,i)}return t}openFrontierNode(t,n=null,r){let s=this.frontier[this.depth];s.match=s.match.matchType(t),this.placed=sd(this.placed,this.depth,we.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(we.empty,!0);n.childCount&&(this.placed=sd(this.placed,this.frontier.length,n))}}function rd(e,t,n){return t==0?e.cutByIndex(n,e.childCount):e.replaceChild(0,e.firstChild.copy(rd(e.firstChild.content,t-1,n)))}function sd(e,t,n){return t==0?e.append(n):e.replaceChild(e.childCount-1,e.lastChild.copy(sd(e.last
vendor: 9,240 bytes, line 46
46Child.content,t-1,n)))}function tx(e,t){for(let n=0;n<t;n++)e=e.firstChild.content;return e}function tN(e,t,n){if(t<=0)return e;let r=e.content;return t>1&&(r=r.replaceChild(0,tN(r.firstChild,t-1,r.childCount==1?n-1:0))),t>0&&(r=e.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(e.type.contentMatch.matchFragment(r).fillBefore(we.empty,!0)))),e.copy(r)}function nx(e,t,n,r,s){let i=e.node(t),o=s?e.indexAfter(t):e.index(t);if(o==i.childCount&&!n.compatibleContent(i.type))return null;let l=r.fillBefore(i.content,!0,o);return l&&!sQ(n,i.content,o)?l:null}function sQ(e,t,n){for(let r=n;r<t.childCount;r++)if(!e.allowsMarks(t.child(r).marks))return!0;return!1}function iQ(e){return e.spec.defining||e.spec.definingForContent}function aQ(e,t,n,r){if(!r.size)return e.deleteRange(t,n);let s=e.doc.resolve(t),i=e.doc.resolve(n);if(eN(s,i,r))return e.step(new Pn(t,n,r));let o=rN(s,i);o[o.length-1]==0&&o.pop();let l=-(s.depth+1);o.unshift(l);for(let h=s.depth,f=s.pos-1;h>0;h--,f--){let g=s.node(h).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;o.indexOf(h)>-1?l=h:s.before(h)==f&&o.splice(1,0,-h)}let c=o.indexOf(l),d=[],u=r.openStart;for(let h=r.content,f=0;;f++){let g=h.firstChild;if(d.push(g),f==r.openStart)break;h=g.content}for(let h=u-1;h>=0;h--){let f=d[h],g=iQ(f.type);if(g&&!f.sameMarkup(s.node(Math.abs(l)-1)))u=h;else if(g||!f.type.isTextblock)break}for(let h=r.openStart;h>=0;h--){let f=(h+u+1)%(r.openStart+1),g=d[f];if(g)for(let x=0;x<o.length;x++){let b=o[(x+c)%o.length],y=!0;b<0&&(y=!1,b=-b);let v=s.node(b-1),C=s.index(b-1);if(v.canReplaceWith(C,C,g.type,g.marks))return e.replace(s.before(b),y?i.after(b):n,new Te(nN(r.content,0,r.openStart,f),f,r.openEnd))}}let p=e.steps.length;for(let h=o.length-1;h>=0&&(e.replace(t,n,r),!(e.steps.length>p));h--){let f=o[h];f<0||(t=s.before(f),n=i.after(f))}}function nN(e,t,n,r,s){if(t<n){let i=e.firstChild;e=e.replaceChild(0,i.copy(nN(i.content,t+1,n,r,i)))}if(t>r){let i=s.contentMatchAt(0),o=i.fillBefore(e).append(e);e=o.append(i.matchFragment(o).fillBefore(we.empty,!0))}return e}function oQ(e,t,n,r){if(!r.isInline&&t==n&&e.doc.resolve(t).parent.content.size){let s=nQ(e.doc,t,r.type);s!=null&&(t=n=s)}e.replaceRange(t,n,new Te(we.from(r),0,0))}function lQ(e,t,n){let r=e.doc.resolve(t),s=e.doc.resolve(n);if(r.parent.isTextblock&&s.parent.isTextblock&&r.start()!=s.start()&&r.parentOffset==0&&s.parentOffset==0){let o=r.sharedDepth(n),l=!1;for(let c=r.depth;c>o;c--)r.node(c).type.spec.isolating&&(l=!0);for(let c=s.depth;c>o;c--)s.node(c).type.spec.isolating&&(l=!0);if(!l){for(let c=r.depth;c>0&&t==r.start(c);c--)t=r.before(c);for(let c=s.depth;c>0&&n==s.start(c);c--)n=s.before(c);r=e.doc.resolve(t),s=e.doc.resolve(n)}}let i=rN(r,s);for(let o=0;o<i.length;o++){let l=i[o],c=o==i.length-1;if(c&&l==0||r.node(l).type.contentMatch.validEnd)return e.delete(r.start(l),s.end(l));if(l>0&&(c||r.node(l-1).canReplace(r.index(l-1),s.indexAfter(l-1))))return e.delete(r.before(l),s.after(l))}for(let o=1;o<=r.depth&&o<=s.depth;o++)if(t-r.start(o)==r.depth-o&&n>r.end(o)&&s.end(o)-n!=s.depth-o&&r.start(o-1)==s.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),s.index(o-1)))return e.delete(r.before(o),n);e.delete(t,n)}function rN(e,t){let n=[],r=Math.min(e.depth,t.depth);for(let s=r;s>=0;s--){let i=e.start(s);if(i<e.pos-(e.depth-s)||t.end(s)>t.pos+(t.depth-s)||e.node(s).type.spec.isolating||t.node(s).type.spec.isolating)break;(i==t.start(s)||s==e.depth&&s==t.depth&&e.parent.inlineContent&&t.parent.inlineContent&&s&&t.start(s-1)==i-1)&&n.push(s)}return n}class Yo extends ur{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Fn.fail("No node at attribute step's position");let r=Object.create(null);for(let i in n.attrs)r[i]=n.attrs[i];r[this.attr]=this.value;let s=n.type.create(r,null,n.marks);return Fn.fromReplace(t,this.pos,this.pos+1,new Te(we.from(s),0,n.isLeaf?0:1))}getMap(){return Nr.empty}invert(t){return new Yo(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new Yo(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Yo(n.pos,n.attr,n.value)}}ur.jsonID("attr",Yo);class zd extends ur{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let s in t.attrs)n[s]=t.attrs[s];n[this.attr]=this.value;let r=t.type.create(n,t.content,t.marks);return Fn.ok(r)}getMap(){return Nr.empty}invert(t){return new zd(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new zd(n.attr,n.value)}}ur.jsonID("docAttr",zd);let al=class extends Error{};al=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n};al.prototype=Object.create(Error.prototype);al.prototype.constructor=al;al.prototype.name="TransformError";class sN{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new $d}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new al(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let s=this.mapping.maps[r];r&&(t=s.map(t,1),n=s.map(n,-1)),s.forEach((i,o,l,c)=>{t=Math.min(t,l),n=Math.max(n,c)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,r=Te.empty){let s=Um(this.doc,t,n,r);return s&&this.step(s),this}replaceWith(t,n,r){return this.replace(t,n,new Te(we.from(r),0,0))}delete(t,n){return this.replace(t,n,Te.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return aQ(this,t,n,r),this}replaceRangeWith(t,n,r){return oQ(this,t,n,r),this}deleteRange(t,n){return lQ(this,t,n),this}lift(t,n){return q7(this,t,n),this}join(t,n=1){return tQ(this,t,n),this}wrap(t,n){return K7(this,t,n),this}setBlockType(t,n=t,r,s=null){return Q7(this,t,n,r,s),this}setNodeMarkup(t,n,r=null,s){return X7(this,t,n,r,s),this}setNodeAttribute(t,n,r){return this.step(new Yo(t,n,r)),this}setDocAttribute(t,n){return this.step(new zd(t,n)),this}addNodeMark(t,n){return this.step(new Wi(t,n)),this}removeNodeMark(t,n){let r=this.doc.nodeAt(t);if(!r)throw new RangeError("No node at position "+t);if(n instanceof dn)n.isInSet(r.marks)&&this.step(new no(t,n));else{let s=r.marks,i,o=[];for(;i=n.isInSet(s);)o.push(new no(t,i)),s=i.removeFromSet(s);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(t,n=1,r){return Z7(this,t,n,r),this}addMark(t,n,r){return V7(this,t,n,r),this}removeMark(t,n,r){return W7(this,t,n,r),this}clearIncompatible(t,n,r){return BC(this,t,n,r),this}}const rx=Object.create(null);class nt{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new iN(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n<t.length;n++)if(t[n].$from.pos!=t[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,n=Te.empty){let r=n.content.lastChild,s=null;for(let l=0;l<n.openEnd;l++)s=r,r=r.lastChild;let i=t.steps.length,o=this.ranges;for(let l=0;l<o.length;l++){let{$from:c,$to:d}=o[l],u=t.mapping.slice(i);t.replaceRange(u.map(c.pos),u.map(d.pos),l?Te.empty:n),l==0&&r1(t,i,(r?r.isInline:s&&s.isTextblock)?-1:1)}}replaceWith(t,n){let r=t.steps.length,s=this.ranges;for(let i=0;i<s.length;i++){let{$from:o,$to:l}=s[i],c=t.mapping.slice(r),d=c.map(o.pos),u=c.map(l.pos);i?t.deleteRange(d,u):(t.replaceRangeWith(d,u,n),r1(t,r,n.isInline?-1:1))}}static findFrom(t,n,r=!1){let s=t.parent.inlineContent?new Ke(t):$o(t.node(0),t.parent,t.pos,t.index(),n,r);if(s)return s;for(let i=t.depth-1;i>=0;i--){let o=n<0?$o(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):$o(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,n,r);if(o)return o}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new Lr(t.node(0))}static atStart(t){return $o(t,t,0,0,1)||new Lr(t)}static atEnd(t){return $o(t,t,t.content.size,t.childCount,-1)||new Lr(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=rx[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in rx)throw new RangeError("Duplicate use of selection JSON ID "+t);return rx[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Ke.between(this.$anchor,this.$head).getBookmark()}}nt.prototype.visible=!0;class iN{constructor(t,n){this.$from=t,this.$to=n}}let t1=!1;function n1(e){!t1&&!e.parent.inlineContent&&(t1=!0,console.warn("TextSelection endpoint not pointing into a
46node with inline content ("+e.parent.type.name+")"))}class Ke extends nt{constructor(t,n=t){n1(t),n1(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return nt.near(r);let s=t.resolve(n.map(this.anchor));return new Ke(s.parent.inlineContent?s:r,r)}replace(t,n=Te.empty){if(super.replace(t,n),n==Te.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Ke&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Vm(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Ke(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let s=t.resolve(n);return new this(s,r==n?s:t.resolve(r))}static between(t,n,r){let s=t.pos-n.pos;if((!r||s)&&(r=s>=0?1:-1),!n.parent.inlineContent){let i=nt.findFrom(n,r,!0)||nt.findFrom(n,-r,!0);if(i)n=i.$head;else return nt.near(n,r)}return t.parent.inlineContent||(s==0?t=n:(t=(nt.findFrom(t,-r,!0)||nt.findFrom(t,r,!0)).$anchor,t.pos<n.pos!=s<0&&(t=n))),new Ke(t,n)}}nt.jsonID("text",Ke);class Vm{constructor(t,n){this.anchor=t,this.head=n}map(t){return new Vm(t.map(this.anchor),t.map(this.head))}resolve(t){return Ke.between(t.resolve(this.anchor),t.resolve(this.head))}}class Ye extends nt{constructor(t){let n=t.nodeAfter,r=t.node(0).resolve(t.pos+n.nodeSize);super(t,r),this.node=n}map(t,n){let{deleted:r,pos:s}=n.mapResult(this.anchor),i=t.resolve(s);return r?nt.near(i):new Ye(i)}content(){return new Te(we.from(this.node),0,0)}eq(t){return t instanceof Ye&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new VC(this.anchor)}static fromJSON(t,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Ye(t.resolve(n.anchor))}static create(t,n){return new Ye(t.resolve(n))}static isSelectable(t){return!t.isText&&t.type.spec.selectable!==!1}}Ye.prototype.visible=!1;nt.jsonID("node",Ye);class VC{constructor(t){this.anchor=t}map(t){let{deleted:n,pos:r}=t.mapResult(this.anchor);return n?new Vm(r,r):new VC(r)}resolve(t){let n=t.resolve(this.anchor),r=n.nodeAfter;return r&&Ye.isSelectable(r)?new Ye(n):nt.near(n)}}class Lr extends nt{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,n=Te.empty){if(n==Te.empty){t.delete(0,t.doc.content.size);let r=nt.atStart(t.doc);r.eq(t.selection)||t.setSelection(r)}else super.replace(t,n)}toJSON(){return{type:"all"}}static fromJSON(t){return new Lr(t)}map(t){return new Lr(t)}eq(t){return t instanceof Lr}getBookmark(){return cQ}}nt.jsonID("all",Lr);const cQ={map(){return this},resolve(e){return new Lr(e)}};function $o(e,t,n,r,s,i=!1){if(t.inlineContent)return Ke.create(e,n);for(let o=r-(s>0?0:1);s>0?o<t.childCount:o>=0;o+=s){let l=t.child(o);if(l.isAtom){if(!i&&Ye.isSelectable(l))return Ye.create(e,n-(s<0?l.nodeSize:0))}else{let c=$o(e,l,n+s,s<0?l.childCount:0,s,i);if(c)return c}n+=l.nodeSize*s}return null}function r1(e,t,n){let r=e.steps.length-1;if(r<t)return;let s=e.steps[r];if(!(s instanceof Pn||s instanceof Jn))return;let i=e.mapping.maps[r],o;i.forEach((l,c,d,u)=>{o==null&&(o=u)}),e.setSelection(nt.near(e.doc.resolve(o),n))}function s1(e,t){return!t||!e?e:e.bind(t)}class hp{constructor(t,n,r){this.name=t,this.init=s1(n.init,r),this.apply=s1(n.apply,r)}}new hp("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new hp("selection",{init(e,t){return e.selection||nt.atStart(t.doc)},apply(e){return e.selection}}),new hp("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,r){return r.selection.$cursor?e.storedMarks:null}}),new hp("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}});function aN(e,t,n){for(let r in e){let s=e[r];s instanceof Function?s=s.bind(t):r=="handleDOMEvents"&&(s=aN(s,t,{})),n[r]=s}return n}class pn{constructor(t){this.spec=t,this.props={},t.props&&aN(t.props,this,this.props),this.key=t.key?t.key.key:oN("plugin")}getState(t){return t[this.key]}}const sx=Object.create(null);function oN(e){return e in sx?e+"$"+ ++sx[e]:(sx[e]=0,e+"$")}class hn{constructor(t="key"){this.key=oN(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const lN=(e,t)=>e.selection.empty?!1:(t&&t(e.tr.deleteSelection().scrollIntoView()),!0);function cN(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock("backward",e):n.parentOffset>0)?null:n}const dN=(e,t,n)=>{let r=cN(e,n);if(!r)return!1;let s=WC(r);if(!s){let o=r.blockRange(),l=o&&Ml(o);return l==null?!1:(t&&t(e.tr.lift(o,l).scrollIntoView()),!0)}let i=s.nodeBefore;if(yN(e,s,t,-1))return!0;
vendor: 10,539 bytes, lines 46-47
46if(r.parent.content.size==0&&(ol(i,"end")||Ye.isSelectable(i)))for(let o=r.depth;;o--){let l=Um(e.doc,r.before(o),r.after(o),Te.empty);if(l&&l.slice.size<l.to-l.from){if(t){let c=e.tr.step(l);c.setSelection(ol(i,"end")?nt.findFrom(c.doc.resolve(c.mapping.map(s.pos,-1)),-1):Ye.create(c.doc,s.pos-i.nodeSize)),t(c.scrollIntoView())}return!0}if(o==1||r.node(o-1).childCount>1)break}return i.isAtom&&s.depth==r.depth-1?(t&&t(e.tr.delete(s.pos-i.nodeSize,s.pos).scrollIntoView()),!0):!1},dQ=(e,t,n)=>{let r=cN(e,n);if(!r)return!1;let s=WC(r);return s?uN(e,s,t):!1},uQ=(e,t,n)=>{let r=hN(e,n);if(!r)return!1;let s=HC(r);return s?uN(e,s,t):!1};function uN(e,t,n){let r=t.nodeBefore,s=r,i=t.pos-1;for(;!s.isTextblock;i--){if(s.type.spec.isolating)return!1;let u=s.lastChild;if(!u)return!1;s=u}let o=t.nodeAfter,l=o,c=t.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let d=Um(e.doc,i,c,Te.empty);if(!d||d.from!=i||d instanceof Pn&&d.slice.size>=c-i)return!1;if(n){let u=e.tr.step(d);u.setSelection(Ke.create(u.doc,i)),n(u.scrollIntoView())}return!0}function ol(e,t,n=!1){for(let r=e;r;r=t=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const pN=(e,t,n)=>{let{$head:r,empty:s}=e.selection,i=r;if(!s)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",e):r.parentOffset>0)return!1;i=WC(r)}let o=i&&i.nodeBefore;return!o||!Ye.isSelectable(o)?!1:(t&&t(e.tr.setSelection(Ye.create(e.doc,i.pos-o.nodeSize)).scrollIntoView()),!0)};function WC(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){if(e.index(t)>0)return e.doc.resolve(e.before(t+1));if(e.node(t).type.spec.isolating)break}return null}function hN(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock("forward",e):n.parentOffset<n.parent.content.size)?null:n}const fN=(e,t,n)=>{let r=hN(e,n);if(!r)return!1;let s=HC(r);if(!s)return!1;let i=s.nodeAfter;if(yN(e,s,t,1))return!0;if(r.parent.content.size==0&&(ol(i,"start")||Ye.isSelectable(i))){let o=Um(e.doc,r.before(),r.after(),Te.empty);if(o&&o.slice.size<o.to-o.from){if(t){let l=e.tr.step(o);l.setSelection(ol(i,"start")?nt.findFrom(l.doc.resolve(l.mapping.map(s.pos)),1):Ye.create(l.doc,l.mapping.map(s.pos))),t(l.scrollIntoView())}return!0}}return i.isAtom&&s.depth==r.depth-1?(t&&t(e.tr.delete(s.pos,s.pos+i.nodeSize).scrollIntoView()),!0):!1},mN=(e,t,n)=>{let{$head:r,empty:s}=e.selection,i=r;if(!s)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",e):r.parentOffset<r.parent.content.size)return!1;i=HC(r)}let o=i&&i.nodeAfter;return!o||!Ye.isSelectable(o)?!1:(t&&t(e.tr.setSelection(Ye.create(e.doc,i.pos)).scrollIntoView()),!0)};function HC(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){let n=e.node(t);if(e.index(t)+1<n.childCount)return e.doc.resolve(e.after(t+1));if(n.type.spec.isolating)break}return null}const pQ=(e,t)=>{let n=e.selection,r=n instanceof Ye,s;if(r){if(n.node.isTextblock||!pa(e.doc,n.from))return!1;s=n.from}else if(s=Bm(e.doc,n.from,-1),s==null)return!1;if(t){let i=e.tr.join(s);r&&i.setSelection(Ye.create(i.doc,s-e.doc.resolve(s).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},hQ=(e,t)=>{let n=e.selection,r;if(n instanceof Ye){if(n.node.isTextblock||!pa(e.doc,n.to))return!1;r=n.to}else if(r=Bm(e.doc,n.to,1),r==null)return!1;return t&&t(e.tr.join(r).scrollIntoView()),!0},fQ=(e,t)=>{let{$from:n,$to:r}=e.selection,s=n.blockRange(r),i=s&&Ml(s);return i==null?!1:(t&&t(e.tr.lift(s,i).scrollIntoView()),!0)},gN=(e,t)=>{let{$head:n,$anchor:r}=e.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(e.tr.insertText(` 47`).scrollIntoView()),!0)};function qC(e){for(let t=0;t<e.edgeCount;t++){let{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}const mQ=(e,t)=>{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let s=n.node(-1),i=n.indexAfter(-1),o=qC(s.contentMatchAt(i));if(!o||!s.canReplaceWith(i,i,o))return!1;if(t){let l=n.after(),c=e.tr.replaceWith(l,l,o.createAndFill());c.setSelection(nt.near(c.doc.resolve(l),1)),t(c.scrollIntoView())}return!0},xN=(e,t)=>{let n=e.selection,{$from:r,$to:s}=n;if(n instanceof Lr||r.parent.inlineContent||s.parent.inlineContent)return!1;let i=qC(s.parent.contentMatchAt(s.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let o=(!r.parentOffset&&s.index()<s.parent.childCount?r:s).pos,l=e.tr.insert(o,i.createAndFill());l.setSelection(Ke.create(l.doc,o+1)),t(l.scrollIntoView())}return!0},bN=(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let i=n.before();if(xi(e.doc,i))return t&&t(e.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),s=r&&Ml(r);return s==null?!1:(t&&t(e.tr.lift(r,s).scrollIntoView()),!0)};function gQ(e){return(t,n)=>{let{$from:r,$to:s}=t.selection;if(t.selection instanceof Ye&&t.selection.node.isBlock)return!r.parentOffset||!xi(t.doc,r.pos)?!1:(n&&n(t.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let i=[],o,l,c=!1,d=!1;for(let f=r.depth;;f--)if(r.node(f).isBlock){c=r.end(f)==r.pos+(r.depth-f),d=r.start(f)==r.pos-(r.depth-f),l=qC(r.node(f-1).contentMatchAt(r.indexAfter(f-1))),i.unshift(c&&l?{type:l}:null),o=f;break}else{if(f==1)return!1;i.unshift(null)}let u=t.tr;(t.selection instanceof Ke||t.selection instanceof Lr)&&u.deleteSelection();let p=u.mapping.map(r.pos),h=xi(u.doc,p,i.length,i);if(h||(i[0]=l?{type:l}:null,h=xi(u.doc,p,i.length,i)),!h)return!1;if(u.split(p,i.length,i),!c&&d&&r.node(o).type!=l){let f=u.mapping.map(r.before(o)),g=u.doc.resolve(f);l&&r.node(o-1).canReplaceWith(g.index(),g.index()+1,l)&&u.setNodeMarkup(u.mapping.map(r.before(o)),l)}return n&&n(u.scrollIntoView()),!0}}const xQ=gQ(),bQ=(e,t)=>{let{$from:n,to:r}=e.selection,s,i=n.sharedDepth(r);return i==0?!1:(s=n.before(i),t&&t(e.tr.setSelection(Ye.create(e.doc,s))),!0)};function yQ(e,t,n){let r=t.nodeBefore,s=t.nodeAfter,i=t.index();return!r||!s||!r.type.compatibleContent(s.type)?!1:!r.content.size&&t.parent.canReplace(i-1,i)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(s.isTextblock||pa(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function yN(e,t,n,r){let s=t.nodeBefore,i=t.nodeAfter,o,l,c=s.type.spec.isolating||i.type.spec.isolating;if(!c&&yQ(e,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(o=(l=s.contentMatchAt(s.childCount)).findWrapping(i.type))&&l.matchType(o[0]||i.type).validEnd){if(n){let f=t.pos+i.nodeSize,g=we.empty;for(let y=o.length-1;y>=0;y--)g=we.from(o[y].create(null,g));g=we.from(s.copy(g));let x=e.tr.step(new Jn(t.pos-1,f,t.pos,f,new Te(g,1,0),o.length,!0)),b=x.doc.resolve(f+2*o.length);b.nodeAfter&&b.nodeAfter.type==s.type&&pa(x.doc,b.pos)&&x.join(b.pos),n(x.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:nt.findFrom(t,1),p=u&&u.$from.blockRange(u.$to),h=p&&Ml(p);if(h!=null&&h>=t.depth)return n&&n(e.tr.lift(p,h).scrollIntoView()),!0;if(d&&ol(i,"start",!0)&&ol(s,"end")){let f=s,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let x=i,b=1;for(;!x.isTextblock;x=x.firstChild)b++;if(f.canReplace(f.childCount,f.childCount,x.content)){if(n){let y=we.empty;for(let C=g.length-1;C>=0;C--)y=we.from(g[C].copy(y));let v=e.tr.step(new Jn(t.pos-g.length,t.pos+i.nodeSize,t.pos+b,t.pos+i.nodeSize-b,new Te(y,g.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function vN(e){return function(t,n){let r=t.selection,s=e<0?r.$from:r.$to,i=s.depth;for(;s.node(i).isInline;){if(!i)return!1;i--}return s.node(i).isTextblock?(n&&n(t.tr.setSelection(Ke.create(t.doc,e<0?s.start(i):s.end(i)))),!0):!1}}const vQ=vN(-1),CQ=vN(1);function wQ(e,t=null){return function(n,r){let{$from:s,$to:i}=n.selection,o=s.blockRange(i),l=o&&UC(o,e,t);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function i1(e,t=null){return function(n,r){let s=!1;for(let i=0;i<n.selection.ranges.length&&!s;i++){let{$from:{pos:o},$to:{pos:l}}=n.selection.ranges[i];n.doc.nodesBetween(o,l,(c,d)=>{if(s)return!1;if(!(!c.isTextblock||c.hasMarkup(e,t)))if(c.type==e)s=!0;else{let u=n.doc.resolve(d),p=u.index();s=u.parent.canReplaceWith(p,p+1,e)}})}if(!s)return!1;if(r){let i=n.tr;for(let o=0;o<n.selection.ranges.length;o++){let{$from:{pos:l},$to:{pos:c}}=n.selection.ranges[o];i.setBlockType(l,c,e,t)}r(i.scrollIntoView())}return!0}}function GC(...e){return function(t,n,r){for(let s=0;s<e.length;s++)if(e[s](t,n,r))return!0;return!1}}GC(lN,dN,pN);GC(lN,fN,mN);GC(gN,xN,bN,xQ);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function SQ(e,t=null){return function(n,r){let{$from:s,$to:i}=n.selection,o=s.blockRange(i);if(!o)return!1;let l=r?n.tr:null;return jQ(l,o,e,t)?(r&&r(l.scrollIntoView()),!0):!1}}function jQ(e,t,n,r=null){let s=!1,i=t,o=t.$from.doc;if(t.depth>=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=o.resolve(t.start-2);i=new Zh(c,c,t.depth),t.endIndex<t.parent.childCount&&(t=new Zh(t.$from,o.resolve(t.$to.end(t.depth)),t.depth)),s=!0}let l=UC(i,n,r,t);return l?(e&&kQ(e,t,l,s,n),!0):!1}function kQ(e,t,n,r,s){let i=we.empty;for(let u=n.length-1;u>=0;u--)i=we.from(n[u].type.create(n[u].attrs,i));e.step(new Jn(t.start-(r?2:0),t.end,t.start,t.end,new Te(i,0,0),n.length,!0));let o=0;for(let u=0;u<n.length;u++)n[u].type==s&&(o=u+1);let l=n.length-o,c=t.start+n.length-(r?2:0),d=t.parent;for(let u=t.startIndex,p=t.endIndex,h=!0;u<p;u++,h=!1)!h&&xi(e.doc,c,l)&&(e.split(c,l),c+=2*l),c+=d.child(u).nodeSize;return e}function EQ(e){return function(t,n){let{$from:r,$to:s}=t.selection,i=r.blockRange(s,o=>o.childCount>0&&o.firstChild.type==e);return i?n?r.node(i.depth-1).type==e?_Q(t,n,e,i):TQ(t,n,i):!0:!1}}function _Q(e,t,n,r){let s=e.tr,i=r.end,o=r.$to.end(r.depth);i<o&&(s.step(new Jn(i-1,o,i,o,new Te(we.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new Zh(s.doc.resolve(r.$from.pos),s.doc.resolve(o),r.depth));const l=Ml(r);if(l==null)return!1;s.lift(r,l);let c=s.doc.resolve(s.mapping.map(i,-1)-1);return pa(s.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&s.join(c.pos),t(s.scrollIntoView()),!0}function TQ(e,t,n){let r=e.tr,s=n.parent;for(let f=n.end,g=n.endIndex-1,x=n.startIndex;g>x;g--)f-=s.child(g).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(n.start),o=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==s.childCount,d=i.node(-1),u=i.index(-1);
47if(!d.canReplace(u+(l?0:1),u+1,o.content.append(c?we.empty:we.from(s))))return!1;let p=i.pos,h=p+o.nodeSize;return r.step(new Jn(p-(l?1:0),h+(c?1:0),p+1,h-1,new Te((l?we.empty:we.from(s.copy(we.empty))).append(c?we.empty:we.from(s.copy(we.empty))),l?0:1,c?0:1),l?0:1)),t(r.scrollIntoView()),!0}function IQ(e){return function(t,n){let{$from:r,$to:s}=t.selection,i=r.blockRange(s,d=>d.childCount>0&&d.firstChild.type==e);if(!i)return!1;let o=i.startIndex;if(o==0)return!1;let l=i.parent,c=l.child(o-1);if(c.type!=e)return!1;if(n){let d=c.lastChild&&c.lastChild.type==l.type,u=we.from(d?e.create():null),p=new Te(we.from(e.create(null,we.from(l.type.create(null,u)))),d?3:1,0),h=i.start,f=i.end;n(t.tr.step(new Jn(h-(d?3:1),f,h,f,p,1,!0)).scrollIntoView())}return!0}}const mo=function(e){for(var t=0;;t++)if(e=e.previousSibling,!e)return t},CN=function(e,t,n,r){return n&&(a1(e,t,n,r,-1)||a1(e,t,n,r,1))},DQ=/^(img|br|input|textarea|hr)$/i;function a1(e,t,n,r,s){for(var i;;){if(e==n&&t==r)return!0;if(t==(s<0?0:tf(e))){let o=e.parentNode;if(!o||o.nodeType!=1||YC(e)||DQ.test(e.nodeName)||e.contentEditable=="false")return!1;t=mo(e)+(s<0?0:1),e=o}else if(e.nodeType==1){let o=e.childNodes[t+(s<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((i=o.pmViewDesc)===null||i===void 0)&&i.ignoreForSelection)t+=s;else return!1;else e=o,t=s<0?tf(e):0}else return!1}}function tf(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function AQ(e,t,n){for(let r=t==0,s=t==tf(e);r||s;){if(e==n)return!0;let i=mo(e);if(e=e.parentNode,!e)return!1;r=r&&i==0,s=s&&i==tf(e)}}function YC(e){let t;for(let n=e;n&&!(t=n.pmViewDesc);n=n.parentNode);return t&&t.node&&t.node.isBlock&&(t.dom==e||t.contentDOM==e)}const wN=function(e){return e.focusNode&&CN(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)};function SN(e,t){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=e,n.key=n.code=t,n}const Hs=typeof navigator<"u"?navigator:null,o1=typeof document<"u"?document:null,ha=Hs&&Hs.userAgent||"",dy=/Edge\/(\d+)/.exec(ha),jN=/
vendor: 43,488 bytes, lines 47-50
47MSIE \d/.exec(ha),uy=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(ha),Eu=!!(jN||uy||dy),kN=jN?document.documentMode:uy?+uy[1]:dy?+dy[1]:0,Wm=!Eu&&/gecko\/(\d+)/i.test(ha);Wm&&+(/Firefox\/(\d+)/.exec(ha)||[0,0])[1];const py=!Eu&&/Chrome\/(\d+)/.exec(ha),ki=!!py,EN=py?+py[1]:0,go=!Eu&&!!Hs&&/Apple Computer/.test(Hs.vendor),KC=go&&(/Mobile\/\w+/.test(ha)||!!Hs&&Hs.maxTouchPoints>2),Qr=KC||(Hs?/Mac/.test(Hs.platform):!1),_N=Hs?/Win/.test(Hs.platform):!1,_u=/Android \d/.test(ha),QC=!!o1&&"webkitFontSmoothing"in o1.documentElement.style,MQ=QC?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function RQ(e,t=null){let n=e.domSelectionRange(),r=e.state.doc;if(!n.focusNode)return null;let s=e.docView.nearestDesc(n.focusNode),i=s&&s.size==0,o=e.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,d;if(wN(n)){for(c=o;s&&!s.node;)s=s.parent;let p=s.node;if(s&&p.isAtom&&Ye.isSelectable(p)&&s.parent&&!(p.isInline&&AQ(n.focusNode,n.focusOffset,s.dom))){let h=s.posBefore;d=new Ye(o==h?l:r.resolve(h))}}else{if(n instanceof e.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let p=o,h=o;for(let f=0;f<n.rangeCount;f++){let g=n.getRangeAt(f);p=Math.min(p,e.docView.posFromDOM(g.startContainer,g.startOffset,1)),h=Math.max(h,e.docView.posFromDOM(g.endContainer,g.endOffset,-1))}if(p<0)return null;[c,o]=h==e.state.selection.anchor?[h,p]:[p,h],l=r.resolve(o)}else c=e.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(c<0)return null}let u=r.resolve(c);if(!d){let p=t=="pointer"||e.state.selection.head<l.pos&&!i?1:-1;d=IN(e,u,l,p)}return d}function TN(e){return e.editable?e.hasFocus():LQ(e)&&document.activeElement&&document.activeElement.contains(e.dom)}function JC(e,t=!1){let n=e.state.selection;if(PQ(e,n),!!TN(e)){if(!t&&e.input.mouseDown&&e.input.mouseDown.allowDefault&&ki){let r=e.domSelectionRange(),s=e.domObserver.currentSelection;if(r.anchorNode&&s.anchorNode&&CN(r.anchorNode,r.anchorOffset,s.anchorNode,s.anchorOffset)){e.input.mouseDown.delayedSelectionSync=!0,e.domObserver.setCurSelection();return}}if(e.domObserver.disconnectSelection(),e.cursorWrapper)OQ(e);else{let{anchor:r,head:s}=n,i,o;l1&&!(n instanceof Ke)&&(n.$from.parent.inlineContent||(i=c1(e,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(o=c1(e,n.to))),e.docView.setSelection(r,s,e,t),l1&&(i&&d1(i),o&&d1(o)),n.visible?e.dom.classList.remove("ProseMirror-hideselection"):(e.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&NQ(e))}e.domObserver.setCurSelection(),e.domObserver.connectSelection()}}const l1=go||ki&&EN<63;function c1(e,t){let{node:n,offset:r}=e.docView.domFromPos(t,0),s=r<n.childNodes.length?n.childNodes[r]:null,i=r?n.childNodes[r-1]:null;if(go&&s&&s.contentEditable=="false")return ix(s);if((!s||s.contentEditable=="false")&&(!i||i.contentEditable=="false")){if(s)return ix(s);if(i)return ix(i)}}function ix(e){return e.contentEditable="true",go&&e.draggable&&(e.draggable=!1,e.wasDraggable=!0),e}function d1(e){e.contentEditable="false",e.wasDraggable&&(e.draggable=!0,e.wasDraggable=null)}function NQ(e){let t=e.dom.ownerDocument;t.removeEventListener("selectionchange",e.input.hideSelectionGuard);let n=e.domSelectionRange(),r=n.anchorNode,s=n.anchorOffset;t.addEventListener("selectionchange",e.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=s)&&(t.removeEventListener("selectionchange",e.input.hideSelectionGuard),setTimeout(()=>{(!TN(e)||e.state.selection.visible)&&e.dom.classList.remove("ProseMirror-hideselection")},20))})}function OQ(e){let t=e.domSelection();if(!t)return;let n=e.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,mo(n)+1):t.collapse(n,0),!r&&!e.state.selection.visible&&Eu&&kN<=11&&(n.disabled=!0,n.disabled=!1)}function PQ(e,t){if(t instanceof Ye){let n=e.docView.descAt(t.from);n!=e.lastSelectedViewDesc&&(u1(e),n&&n.selectNode(),e.lastSelectedViewDesc=n)}else u1(e)}function u1(e){e.lastSelectedViewDesc&&(e.lastSelectedViewDesc.parent&&e.lastSelectedViewDesc.deselectNode(),e.lastSelectedViewDesc=void 0)}function IN(e,t,n,r){return e.someProp("createSelectionBetween",s=>s(e,t,n))||Ke.between(t,n,r)}function LQ(e){let t=e.domSelectionRange();if(!t.anchorNode)return!1;try{return e.dom.contains(t.anchorNode.nodeType==3?t.anchorNode.parentNode:t.anchorNode)&&(e.editable||e.dom.contains(t.focusNode.nodeType==3?t.focusNode.parentNode:t.focusNode))}catch{return!1}}function hy(e,t){let{$anchor:n,$head:r}=e.selection,s=t>0?n.max(r):n.min(r),i=s.parent.inlineContent?s.depth?e.doc.resolve(t>0?s.after():s.before()):null:s;return i&&nt.findFrom(i,t)}function Pi(e,t){return e.dispatch(e.state.tr.setSelection(t).scrollIntoView()),!0}function p1(e,t,n){let r=e.state.selection;if(r instanceof Ke)if(n.indexOf("s")>-1){let{$head:s}=r,i=s.textOffset?null:t<0?s.nodeBefore:s.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let o=e.state.doc.resolve(s.pos+i.nodeSize*(t<0?-1:1));return Pi(e,new Ke(r.$anchor,o))}else if(r.empty){if(e.endOfTextblock(t>0?"forward":"backward")){let s=hy(e.state,t);return s&&s instanceof Ye?Pi(e,s):!1}else if(!(Qr&&n.indexOf("m")>-1)){let s=r.$head,i=s.textOffset?null:t<0?s.nodeBefore:s.nodeAfter,o;if(!i||i.isText)return!1;let l=t<0?s.pos-i.nodeSize:s.pos;return i.isAtom||(o=e.docView.descAt(l))&&!o.contentDOM?Ye.isSelectable(i)?Pi(e,new Ye(t<0?e.state.doc.resolve(s.pos-i.nodeSize):s)):QC?Pi(e,new Ke(e.state.doc.resolve(t<0?l:l+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Ye&&r.node.isInline)return Pi(e,new Ke(t>0?r.$to:r.$from));{let s=hy(e.state,t);return s?Pi(e,s):!1}}}function nf(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function xd(e,t){let n=e.pmViewDesc;return n&&n.size==0&&(t<0||e.nextSibling||e.nodeName!="BR")}function Do(e,t){return t<0?FQ(e):$Q(e)}function FQ(e){let t=e.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let s,i,o=!1;for(Wm&&n.nodeType==1&&r<nf(n)&&xd(n.childNodes[r],-1)&&(o=!0);;)if(r>0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(xd(l,-1))s=n,i=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(DN(n))break;{let l=n.previousSibling;for(;l&&xd(l,-1);)s=n.parentNode,i=mo(l),l=l.previousSibling;if(l)n=l,r=nf(n);else{if(n=n.parentNode,n==e.dom)break;r=0}}}o?fy(e,n,r):s&&fy(e,s,i)}function $Q(e){let t=e.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let s=nf(n),i,o;for(;;)if(r<s){if(n.nodeType!=1)break;let l=n.childNodes[r];if(xd(l,1))i=n,o=++r;else break}else{if(DN(n))break;{let l=n.nextSibling;for(;l&&xd(l,1);)i=l.parentNode,o=mo(l)+1,l=l.nextSibling;if(l)n=l,r=0,s=nf(n);else{if(n=n.parentNode,n==e.dom)break;r=s=0}}}i&&fy(e,i,o)}function DN(e){let t=e.pmViewDesc;return t&&t.node&&t.node.isBlock}function zQ(e,t){for(;e&&t==e.childNodes.length&&!YC(e);)t=mo(e)+1,e=e.parentNode;for(;e&&t<e.childNodes.length;){let n=e.childNodes[t];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;e=n,t=0}}function BQ(e,t){for(;e&&!t&&!YC(e);)t=mo(e),e=e.parentNode;for(;e&&t;){let n=e.childNodes[t-1];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;e=n,t=e.childNodes.length}}function fy(e,t,n){if(t.nodeType!=3){let i,o;(o=zQ(t,n))?(t=o,n=0):(i=BQ(t,n))&&(t=i,n=i.nodeValue.length)}let r=e.domSelection();if(!r)return;if(wN(r)){let i=document.createRange();i.setEnd(t,n),i.setStart(t,n),r.removeAllRanges(),r.addRange(i)}else r.extend&&r.extend(t,n);e.domObserver.setCurSelection();let{state:s}=e;setTimeout(()=>{e.state==s&&JC(e)},50)}function h1(e,t){let n=e.state.doc.resolve(t);if(!(ki||_N)&&n.parent.inlineContent){let s=e.coordsAtPos(t);if(t>n.start()){let i=e.coordsAtPos(t-1),o=(i.top+i.bottom)/2;if(o>s.top&&o<s.bottom&&Math.abs(i.left-s.left)>1)return i.left<s.left?"ltr":"rtl"}if(t<n.end()){let i=e.coordsAtPos(t+1),o=(i.top+i.bottom)/2;if(o>s.top&&o<s.bottom&&Math.abs(i.left-s.left)>1)return i.left>s.left?"ltr":"rtl"}}return getComputedStyle(e.dom).direction=="rtl"?"rtl":"ltr"}function f1(e,t,n){let r=e.state.selection;if(r instanceof Ke&&!r.empty||n.indexOf("s")>-1||Qr&&n.indexOf("m")>-1)return!1;let{$from:s,$to:i}=r;if(!s.parent.inlineContent||e.endOfTextblock(t<0?"up":"down")){let o=hy(e.state,t);if(o&&o instanceof Ye)return Pi(e,o)}if(!s.parent.inlineContent){let o=t<0?s:i,l=r instanceof Lr?nt.near(o,t):nt.findFrom(o,t);return l?Pi(e,l):!1}return!1}function m1(e,t){if(!(e.state.selection instanceof Ke))return!0;let{$head:n,$anchor:r,empty:s}=e.state.selection;if(!n.sameParent(r))return!0;if(!s)return!1;if(e.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!n.textOffset&&(t<0?n.nodeBefore:n.nodeAfter);if(i&&!i.isText){let o=e.state.tr;return t<0?o.delete(n.pos-i.nodeSize,n.pos):o.delete(n.pos,n.pos+i.nodeSize),e.dispatch(o),!0}return!1}function g1(e,t,n){e.domObserver.stop(),t.contentEditable=n,e.domObserver.start()}function UQ(e){if(!go||e.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:n}=e.domSelectionRange();if(t&&t.nodeType==1&&n==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let r=t.firstChild;g1(e,r,"true"),setTimeout(()=>g1(e,r,"false"),20)}return!1}function VQ(e){let t="";return e.ctrlKey&&(t+="c"),e.metaKey&&(t+="m"),e.altKey&&(t+="a"),e.shiftKey&&(t+="s"),t}function WQ(e,t){let n=t.keyCode,r=VQ(t);if(n==8||Qr&&n==72&&r=="c")return m1(e,-1)||Do(e,-1);if(n==46&&!t.shiftKey||Qr&&n==68&&r=="c")return m1(e,1)||Do(e,1);if(n==13||n==27)return!0;if(n==37||Qr&&n==66&&r=="c"){let s=n==37?h1(e,e.state.selection.from)=="ltr"?-1:1:-1;return p1(e,s,r)||Do(e,s)}else if(n==39||Qr&&n==70&&r=="c"){let s=n==39?h1(e,e.state.selection.from)=="ltr"?1:-1:1;return p1(e,s,r)||Do(e,s)}else{if(n==38||Qr&&n==80&&r=="c")return f1(e,-1,r)||Do(e,-1);if(n==40||Qr&&n==78&&r=="c")return UQ(e)||f1(e,1,r)||Do(e,1);if(r==(Qr?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function AN(e,t){e.someProp("transformCopied",f=>{t=f(t,e)});let n=[],{content:r,openStart:s,openEnd:i}=t;for(;s>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){s--,i--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=e.someProp("clipboardSerializer")||zm.fromSchema(e.state.schema),l=LN(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let d=c.firstChild,u,p=0;for(;d&&d.nodeType==1&&(u=PN[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=l.createElement(u[f]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),p++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${s} ${i}${p?` -${p}`:""} ${JSON.stringify(n)}`);let h=e.someProp("clipboardTextSerializer",f=>f(t,e))||t.content.textBetween(0,t.content.size,` 48 49`);return{dom:c,text:h,slice:t}}function MN(e,t,n,r,s){let i=s.parent.type.spec.code,o,l;if(!n&&!t)return null;let c=!!t&&(r||i||!n);if(c){if(e.someProp("transformPastedText",h=>{t=h(t,i||r,e)}),i)return l=new Te(we.from(e.state.schema.text(t.replace(/\r\n?/g,` 50`))),0,0),e.someProp("transformPasted",h=>{l=h(l,e,!0)}),l;let p=e.someProp("clipboardTextParser",h=>h(t,s,r,e));if(p)l=p;else{let h=s.marks(),{schema:f}=e.state,g=zm.fromSchema(f);o=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(x=>{let b=o.appendChild(document.createElement("p"));x&&b.appendChild(g.serializeNode(f.text(x,h)))})}}else e.someProp("transformPastedHTML",p=>{n=p(n,e)}),o=YQ(n),QC&&KQ(o);let d=o&&o.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let p=+u[3];p>0;p--){let h=o.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;o=h}if(l||(l=(e.someProp("clipboardParser")||e.someProp("domParser")||Xi.fromSchema(e.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||u),context:s,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!HQ.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)l=QQ(x1(l,+u[1],+u[2]),u[4]);else if(l=Te.maxOpen(qQ(l.content,s),!0),l.openStart||l.openEnd){let p=0,h=0;for(let f=l.content.firstChild;p<l.openStart&&!f.type.spec.isolating;p++,f=f.firstChild);for(let f=l.content.lastChild;h<l.openEnd&&!f.type.spec.isolating;h++,f=f.lastChild);l=x1(l,p,h)}return e.someProp("transformPasted",p=>{l=p(l,e,c)}),l}const HQ=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function qQ(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let s=t.node(n).contentMatchAt(t.index(n)),i,o=[];if(e.forEach(l=>{if(!o)return;let c=s.findWrapping(l.type),d;if(!c)return o=null;if(d=o.length&&i.length&&NN(c,i,l,o[o.length-1],0))o[o.length-1]=d;else{o.length&&(o[o.length-1]=ON(o[o.length-1],i.length));let u=RN(l,c);o.push(u),s=s.matchType(u.type),i=c}}),o)return we.from(o)}return e}function RN(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,we.from(e));return e}function NN(e,t,n,r,s){if(s<e.length&&s<t.length&&e[s]==t[s]){let i=NN(e,t,n,r.lastChild,s+1);if(i)return r.copy(r.content.replaceChild(r.childCount-1,i));if(r.contentMatchAt(r.childCount).matchType(s==e.length-1?n.type:e[s+1]))return r.copy(r.content.append(we.from(RN(n,e,s+1))))}}function ON(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,ON(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(we.empty,!0);return e.copy(n.append(r))}function my(e,t,n,r,s,i){let o=t<0?e.firstChild:e.lastChild,l=o.content;return e.childCount>1&&(i=0),s<r-1&&(l=my(l,t,n,r,s+1,i)),s>=n&&(l=t<0?o.contentMatchAt(0).fillBefore(l,i<=s).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(we.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,o.copy(l))}function x1(e,t,n){return t<e.openStart&&(e=new Te(my(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new Te(my(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}const PN={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};let b1=null;function LN(){return b1||(b1=document.implementation.createHTMLDocument("title"))}let ax=null;function GQ(e){let t=window.trustedTypes;return t?(ax||(ax=t.defaultPolicy||t.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),ax.createHTML(e)):e}function YQ(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let n=LN().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(e),s;if((s=r&&PN[r[1].toLowerCase()])&&(e=s.map(i=>"<"+i+">").join("")+e+s.map(i=>"</"+i+">").reverse().join("")),n.innerHTML=GQ(e),s)for(let i=0;i<s.length;i++)n=n.querySelector(s[i])||n;return n}function KQ(e){let t=e.querySelectorAll(ki?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<t.length;n++){let r=t[n];r.childNodes.length==1&&r.textContent=="Â "&&r.parentNode&&r.parentNode.replaceChild(e.ownerDocument.createTextNode(" "),r)}}function QQ(e,t){if(!e.size)return e;let n=e.content.firstChild.type.schema,r;try{r=JSON.parse(t)}catch{return e}let{content:s,openStart:i,openEnd:o}=e;for(let l=r.length-2;l>=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;s=we.from(c.create(r[l+1],s)),i++,o++}return new Te(s,i,o)}const ws={},Ur={};function Hi(e,t){e.input.lastSelectionOrigin=t,e.input.lastSelectionTime=Date.now()}Ur.keydown=(e,t)=>{let n=t;if(e.input.shiftKey=n.keyCode==16||n.shiftKey,!$N(e,n)&&(e.input.lastKeyCode=n.keyCode,e.input.lastKeyCodeTime=Date.now(),!(_u&&ki&&n.keyCode==13)))if(n.keyCode!=229&&e.domObserver.forceFlush(),KC&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();e.input.lastIOSEnter=r,e.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{e.input.lastIOSEnter==r&&(e.someProp("handleKeyDown",s=>s(e,SN(13,"Enter"))),e.input.lastIOSEnter=0)},200)}else e.someProp("handleKeyDown",r=>r(e,n))||WQ(e,n)?n.preventDefault():Hi(e,"key")};Ur.keyup=(e,t)=>{t.keyCode==16&&(e.input.shiftKey=!1)};Ur.keypress=(e,t)=>{let n=t;if($N(e,n)||!n.charCode||n.ctrlKey&&!n.altKey||Qr&&n.metaKey)return;if(e.someProp("handleKeyPress",s=>s(e,n))){n.preventDefault();return}let r=e.state.selection;if(!(r instanceof Ke)||!r.$from.sameParent(r.$to)){let s=String.fromCharCode(n.charCode),i=()=>e.state.tr.insertText(s).scrollIntoView();!/[\r\n]/.test(s)&&!e.someProp("handleTextInput",o=>o(e,r.$from.pos,r.$to.pos,s,i))&&e.dispatch(i()),n.preventDefault()}};function Hm(e){return{left:e.clientX,top:e.clientY}}function JQ(e,t){let n=t.x-e.clientX,r=t.y-e.clientY;return n*n+r*r<100}function XC(e,t,n,r,s){if(r==-1)return!1;let i=e.state.doc.resolve(r);for(let o=i.depth+1;o>0;o--)if(e.someProp(t,l=>o>i.depth?l(e,n,i.nodeAfter,i.before(o),s,!0):l(e,n,i.node(o),i.before(o),s,!1)))return!0;return!1}function Ko(e,t,n){if(e.focused||e.focus(),e.state.selection.eq(t))return;let r=e.state.tr.setSelection(t);r.setMeta("pointer",!0),e.dispatch(r)}function XQ(e,t){if(t==-1)return!1;let n=e.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Ye.isSelectable(r)?(Ko(e,new Ye(n)),!0):!1}function ZQ(e,t){if(t==-1)return!1;let n=e.state.selection,r,s;n instanceof Ye&&(r=n.node);let i=e.state.doc.resolve(t);for(let o=i.depth+1;o>0;o--){let l=o>i.depth?i.nodeAfter:i.node(o);if(Ye.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&i.before(n.$from.depth+1)==n.$from.pos?s=i.before(n.$from.depth):s=i.before(o);break}}return s!=null?(Ko(e,Ye.create(e.state.doc,s)),!0):!1}function e9(e,t,n,r,s){return XC(e,"handleClickOn",t,n,r)||e.someProp("handleClick",i=>i(e,t,r))||(s?ZQ(e,n):XQ(e,n))}function t9(e,t,n,r){return XC(e,"handleDoubleClickOn",t,n,r)||e.someProp("handleDoubleClick",s=>s(e,t,r))}function n9(e,t,n,r){return XC(e,"handleTripleClickOn",t,n,r)||e.someProp("handleTripleClick",s=>s(e,t,r))||r9(e,n,r)}function r9(e,t,n){if(n.button!=0)return!1;let r=e.state.doc;if(t==-1)return r.inlineContent?(Ko(e,Ke.create(r,0,r.content.size)),!0):!1;let s=r.resolve(t);for(let i=s.depth+1;i>0;i--){let o=i>s.depth?s.nodeAfter:s.node(i),l=s.before(i);if(o.inlineContent)Ko(e,Ke.create(r,l+1,l+1+o.content.size));else if(Ye.isSelectable(o))Ko(e,Ye.create(r,l));else continue;return!0}}function ZC(e){return rf(e)}const FN=Qr?"metaKey":"ctrlKey";ws.mousedown=(e,t)=>{let n=t;e.input.shiftKey=n.shiftKey;let r=ZC(e),s=Date.now(),i="singleClick";s-e.input.lastClick.time<500&&JQ(n,e.input.lastClick)&&!n[FN]&&e.input.lastClick.button==n.button&&(e.input.lastClick.type=="singleClick"?i="doubleClick":e.input.lastClick.type=="doubleClick"&&(i="tripleClick")),e.input.lastClick={time:s,x:n.clientX,y:n.clientY,type:i,button:n.button};let o=e.posAtCoords(Hm(n));o&&(i=="singleClick"?(e.input.mouseDown&&e.input.mouseDown.done(),e.input.mouseDown=new s9(e,o,n,!!r)):(i=="doubleClick"?t9:n9)(e,o.pos,o.inside,n)?n.preventDefault():Hi(e,"pointer"))};class s9{constructor(t,n,r,s){this.view=t,this.pos=n,this.event=r,this.flushed=s,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!r[FN],this.allowDefault=r.shiftKey;let i,o;if(n.inside>-1)i=t.state.doc.nodeAt(n.inside),o=n.inside;else{let u=t.state.doc.resolve(n.pos);i=u.parent,o=u.depth?u.before():0}const l=s?null:r.target,c=l?t.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Ye&&d.from<=o&&d.to>o)&&(this.mightDrag={node:i,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Wm&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this)),Hi(t,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>JC(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Hm(t))),this.updateAllowDefault(t),this.allowDefault||!n?Hi(this.view,"pointer"):e9(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||go&&this.mightDrag&&!this.mightDrag.node.isAtom||ki&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(Ko(this.view,nt.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):Hi(this.view,"pointer")}move(t){this.updateAllowDefault(t),Hi(this.view,"pointer"),t.buttons==0&&this.done()}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}}ws.touchstart=e=>{e.input.lastTouch=Date.now(),ZC(e),Hi(e,"pointer")};ws.touchmove=e=>{e.input.lastTouch=Date.now(),Hi(e,"pointer")};ws.contextmenu=e=>ZC(e);function $N(e,t){return e.composing?!0:go&&Math.abs(t.timeStamp-e.input.compositionEndedAt)<500?(e.input.compositionEndedAt=-2e8,!0):!1}const i9=_u?5e3:-1;Ur.compositionstart=Ur.compositionupdate=e=>{if(!e.composing){e.domObserver.flush();let{state:t}=e,n=t.selection.$to;if(t.selection instanceof Ke&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||ki&&_N&&a9(e)))e.markCursor=e.state.storedMarks||n.marks(),rf(e,!0),e.markCursor=null;else if(rf(e,!t.selection.empty),Wm&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=e.domSelectionRange();for(let s=r.focusNode,i=r.focusOffset;s&&s.nodeType==1&&i!=0;){let o=i<0?s.lastChild:s.childNodes[i-1];if(!o)break;if(o.nodeType==3){let l=e.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else s=o,i=-1}}e.input.composing=!0}zN(e,i9)};function a9(e){let{focusNode:t,focusOffset:n}=e.domSelectionRange();if(!t||t.nodeType!=1||n>=t.childNodes.length)return!1;let r=t.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Ur.compositionend=(e,t)=>{e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=t.timeStamp,e.input.compositionPendingChanges=e.domObserver.pendingRecords().length?e.input.compositionID:0,e.input.compositionNode=null,e.input.badSafariComposition?e.domObserver.forceFlush():e.input.compositionPendingChanges&&Promise.resolve().then(()=>e.domObserver.flush()),e.input.compositionID++,zN(e,20))};function zN(e,t){clearTimeout(e.input.composingTimeout),t>-1&&(e.input.composingTimeout=setTimeout(()=>rf(e),t))}function o9(e){for(e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=l9());e.input.compositionNodes.length>0;)e.input.compositionNodes.pop().markParentsDirty()}function l9(){let e=document.createEvent("Event");return e.initEvent("event",!0,!0),e.timeStamp}function rf(e,t=!1){if(!(_u&&e.domObserver.flushingSoon>=0)){if(e.domObserver.forceFlush(),o9(e),t||e.docView&&e.docView.dirty){let n=RQ(e),r=e.state.selection;return n&&!n.eq(r)?e.dispatch(e.state.tr.setSelection(n)):(e.markCursor||t)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?e.dispatch(e.state.tr.deleteSelection()):e.updateState(e.state),!0}return!1}}function c9(e,t){if(!e.dom.parentNode)return;let n=e.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(t),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),s=document.createRange();s.selectNodeContents(t),e.dom.blur(),r.removeAllRanges(),r.addRange(s),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),e.focus()},50)}const Bd=Eu&&kN<15||KC&&MQ<604;ws.copy=Ur.cut=(e,t)=>{let n=t,r=e.state.selection,s=n.type=="cut";if(r.empty)return;let i=Bd?null:n.clipboardData,o=r.content(),{dom:l,text:c}=AN(e,o);i?(n.preventDefault(),i.clearData(),i.setData("text/html",l.innerHTML),i.setData("text/plain",c)):c9(e,l),s&&e.dispatch(e.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function d9(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function u9(e,t){if(!e.dom.parentNode)return;let n=e.input.shiftKey||e.state.selection.$from.parent.type.spec.code,r=e.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let s=e.input.shiftKey&&e.input.lastKeyCode!=45;setTimeout(()=>{e.focus(),r.parentNode&&r.parentNode.removeChild(r),n?gy(e,r.value,null,s,t):gy(e,r.textContent,r.innerHTML,s,t)},50)}function gy(e,t,n,r,s){let i=MN(e,t,n,r,e.state.selection.$from);if(e.someProp("handlePaste",c=>c(e,s,i||Te.empty)))return!0;if(!i)return!1;let o=d9(i),l=o?e.state.tr.replaceSelectionWith(o,r):e.state.tr.replaceSelection(i);return e.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function BN(e){let t=e.getData("text/plain")||e.getData("Text");if(t)return t;let n=e.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Ur.paste=(e,t)=>{let n=t;if(e.composing&&!_u)return;let r=Bd?null:n.clipboardData,s=e.input.shiftKey&&e.input.lastKeyCode!=45;r&&gy(e,BN(r),r.getData("text/html"),s,n)?n.preventDefault():u9(e,n)};class p9{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const h9=Qr?"altKey":"ctrlKey";function UN(e,t){let n;return e.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[h9]}ws.dragstart=(e,t)=>{let n=t,r=e.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let s=e.state.selection,i=s.empty?null:e.posAtCoords(Hm(n)),o;if(!(i&&i.pos>=s.from&&i.pos<=(s instanceof Ye?s.to-1:s.to))){if(r&&r.mightDrag)o=Ye.create(e.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let p=e.docView.nearestDesc(n.target,!0);p&&p.node.type.spec.draggable&&p!=e.docView&&(o=Ye.create(e.state.doc,p.posBefore))}}let l=(o||e.state.selection).content(),{dom:c,text:d,slice:u}=AN(e,l);(!n.dataTransfer.files.length||!ki||EN>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Bd?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",Bd||n.dataTransfer.setData("text/plain",d),e.dragging=new p9(u,UN(e,n),o)};ws.dragend=e=>{let t=e.dragging;window.setTimeout(()=>{e.dragging==t&&(e.dragging=null)},50)};Ur.dragover=Ur.dragenter=(e,t)=>t.preventDefault();Ur.drop=(e,t)=>{try{f9(e,t,e.dragging)}finally{e.dragging=null}};function f9(e,t,n){if(!t.dataTransfer)return;let r=e.posAtCoords(Hm(t));if(!r)return;let s=e.state.doc.resolve(r.pos),i=n&&n.slice;i?e.someProp("transformPasted",f=>{i=f(i,e,!1)}):i=MN(e,BN(t.dataTransfer),Bd?null:t.dataTransfer.getData("text/html"),!1,s);let o=!!(n&&UN(e,t));if(e.someProp("handleDrop",f=>f(e,t,i||Te.empty,o))){t.preventDefault();return}if(!i)return;t.preventDefault();let l=i?ZR(e.state.doc,s.pos,i):s.pos;l==null&&(l=s.pos);let c=e.state.tr;if(o){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(l),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,p=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(p))return;let h=c.doc.resolve(d);if(u&&Ye.isSelectable(i.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Ye(h));else{let f=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((g,x,b,y)=>f=y),c.setSelection(IN(e,h,c.doc.resolve(f)))}e.focus(),e.dispatch(c.setMeta("uiEvent","drop"))}ws.focus=e=>{e.input.lastFocus=Date.now(),e.focused||(e.domObserver.stop(),e.dom.classList.add("ProseMirror-focused"),e.domObserver.start(),e.focused=!0,setTimeout(()=>{e.docView&&e.hasFocus()&&!e.domObserver.currentSelection.eq(e.domSelectionRange())&&JC(e)},20))};ws.blur=(e,t)=>{let n=t;e.focused&&(e.domObserver.stop(),e.dom.classList.remove("ProseMirror-focused"),e.domObserver.start(),n.relatedTarget&&e.dom.contains(n.relatedTarget)&&e.domObserver.currentSelection.clear(),e.focused=!1)};ws.beforeinput=(e,t)=>{if(ki&&_u&&t.inputType=="deleteContentBackward"){e.domObserver.flushSoon();let{domChangeCount:r}=e.input;setTimeout(()=>{if(e.input.domChangeCount!=r||(e.dom.blur(),e.focus(),e.someProp("handleKeyDown",i=>i(e,SN(8,"Backspace")))))return;let{$cursor:s}=e.state.selection;s&&s.pos>0&&e.dispatch(e.state.tr.delete(s.pos-1,s.pos).scrollIntoView())},50)}};for(let e in Ur)ws[e]=Ur[e];function Ud(e,t){if(e==t)return!0;for(let n in e)if(e[n]!==t[n])return!1;for(let n in t)if(!(n in e))return!1;return!0}class sf{constructor(t,n){this.toDOM=t,this.spec=n||Va,this.side=this.spec.side||0}map(t,n,r,s){let{pos:i,deleted:o}=t.mapResult(n.from+s,this.side<0?-1:1);return o?null:new Qn(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof sf&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&Ud(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class Zi{constructor(t,n){this.attrs=t,this.spec=n||Va}map(t,n,r,s){let i=t.map(n.from+s,this.spec.inclusiveStart?-1:1)-r,o=t.map(n.to+s,this.spec.inclusiveEnd?1:-1)-r;return i>=o?null:new Qn(i,o,this)}valid(t,n){return n.from<n.to}eq(t){return this==t||t instanceof Zi&&Ud(this.attrs,t.attrs)&&Ud(this.spec,t.spec)}static is(t){return t.type instanceof Zi}destroy(){}}class e0{constructor(t,n){this.attrs=t,this.spec=n||Va}map(t,n,r,s){let i=t.mapResult(n.from+s,1);if(i.deleted)return null;let o=t.mapResult(n.to+s,-1);return o.deleted||o.pos<=i.pos?null:new Qn(i.pos-r,o.pos-r,this)}valid(t,n){let{index:r,offset:s}=t.content.findIndex(n.from),i;return s==n.from&&!(i=t.child(r)).isText&&s+i.nodeSize==n.to}eq(t){return this==t||t instanceof e0&&Ud(this.attrs,t.attrs)&&Ud(this.spec,t.spec)}destroy(){}}class Qn{constructor(t,n,r){this.from=t,this.to=n,this.type=r}copy(t,n){return new Qn(t,n,this.type)}eq(t,n=0){return this.type.eq(t.type)&&this.from+n==t.from&&this.to+n==t.to}map(t,n,r){return this.type.map(t,this,n,r)}static widget(t,n,r){return new Qn(t,t,new sf(n,r))}static inline(t,n,r,s){return new Qn(t,n,new Zi(r,s))}static node(t,n,r,s){return new Qn(t,n,new e0(r,s))}get spec(){return this.type.spec}get inline(){return this.type instanceof Zi}get widget(){return this.type instanceof sf}}const zo=[],Va={};class Bt{constructor(t,n){this.local=t.length?t:zo,this.children=n.length?n:zo}static create(t,n){return n.length?af(n,t,0,Va):yr}find(t,n,r){let s=[];return this.findInner(t??0,n??1e9,s,0,r),s}findInner(t,n,r,s,i){for(let o=0;o<this.local.length;o++){let l=this.local[o];l.from<=n&&l.to>=t&&(!i||i(l.spec))&&r.push(l.copy(l.from+s,l.to+s))}for(let o=0;o<this.children.length;o+=3)if(this.children[o]<n&&this.children[o+1]>t){let l=this.children[o]+1;this.children[o+2].findInner(t-l,n-l,r,s+l,i)}}map(t,n,r){return this==yr||t.maps.length==0?this:this.mapInner(t,n,0,0,r||Va)}mapInner(t,n,r,s,i){let o;for(let l=0;l<this.local.length;l++){let c=this.local[l].map(t,r,s);c&&c.type.valid(n,c)?(o||(o=[])).push(c):i.onRemove&&i.onRemove(this.local[l].spec)}return this.children.length?m9(this.children,o||[],t,n,r,s,i):o?new Bt(o.sort(Wa),zo):yr}add(t,n){return n.length?this==yr?Bt.create(t,n):this.addInner(t,n,0):this}addInner(t,n,r){let s,i=0;t.forEach((l,c)=>{let d=c+r,u;if(u=WN(n,l,d)){for(s||(s=this.children.slice());i<s.length&&s[i]<c;)i+=3;s[i]==c?s[i+2]=s[i+2].addInner(l,u,d+1):s.splice(i,0,c,c+l.nodeSize,af(u,l,d+1,Va)),i+=3}});let o=VN(i?HN(n):n,-r);for(let l=0;l<o.length;l++)o[l].type.valid(t,o[l])||o.splice(l--,1);return new Bt(o.length?this.local.concat(o).sort(Wa):this.local,s||this.children)}remove(t){return t.length==0||this==yr?this:this.removeInner(t,0)}removeInner(t,n){let r=this.children,s=this.local;for(let i=0;i<r.length;i+=3){let o,l=r[i]+n,c=r[i+1]+n;for(let u=0,p;u<t.length;u++)(p=t[u])&&p.from>l&&p.to<c&&(t[u]=null,(o||(o=[])).push(p));if(!o)continue;r==this.children&&(r=this.children.slice());let d=r[i+2].removeInner(o,l+1);d!=yr?r[i+2]=d:(r.splice(i,3),i-=3)}if(s.length){for(let i=0,o;i<t.length;i++)if(o=t[i])for(let l=0;l<s.length;l++)s[l].eq(o,n)&&(s==this.local&&(s=this.local.slice()),s.splice(l--,1))}return r==this.children&&s==this.local?this:s.length||r.length?new Bt(s,r):yr}forChild(t,n){if(this==yr)return this;if(n.isLeaf)return Bt.empty;let r,s;for(let l=0;l<this.children.length;l+=3)if(this.children[l]>=t){this.children[l]==t&&(r=this.children[l+2]);break}let i=t+1,o=i+n.content.size;for(let l=0;l<this.local.length;l++){let c=this.local[l];if(c.from<o&&c.to>i&&c.type instanceof Zi){let d=Math.max(i,c.from)-i,u=Math.min(o,c.to)-i;d<u&&(s||(s=[])).push(c.copy(d,u))}}if(s){let l=new Bt(s.sort(Wa),zo);return r?new Da([l,r]):l}return r||yr}eq(t){if(this==t)return!0;if(!(t instanceof Bt)||this.local.length!=t.local.length||this.children.length!=t.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(t.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=t.children[n]||this.children[n+1]!=t.children[n+1]||!this.children[n+2].eq(t.children[n+2]))return!1;return!0}locals(t){return t0(this.localsInner(t))}localsInner(t){if(this==yr)return zo;if(t.inlineContent||!this.local.some(Zi.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof Zi||n.push(this.local[r]);return n}forEachSet(t){t(this)}}Bt.empty=new Bt([],[]);Bt.removeOverlap=t0;const yr=Bt.empty;class Da{constructor(t){this.members=t}map(t,n){const r=this.members.map(s=>s.map(t,n,Va));return Da.from(r)}forChild(t,n){if(n.isLeaf)return Bt.empty;let r=[];for(let s=0;s<this.members.length;s++){let i=this.members[s].forChild(t,n);i!=yr&&(i instanceof Da?r=r.concat(i.members):r.push(i))}return Da.from(r)}eq(t){if(!(t instanceof Da)||t.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(t.members[n]))return!1;return!0}locals(t){let n,r=!0;for(let s=0;s<this.members.length;s++){let i=this.members[s].localsInner(t);if(i.length)if(!n)n=i;else{r&&(n=n.slice(),r=!1);for(let o=0;o<i.length;o++)n.push(i[o])}}return n?t0(r?n:n.sort(Wa)):zo}static from(t){switch(t.length){case 0:return yr;case 1:return t[0];default:return new Da(t.every(n=>n instanceof Bt)?t:t.reduce((n,r)=>n.concat(r instanceof Bt?r:r.members),[]))}}forEachSet(t){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(t)}}function m9(e,t,n,r,s,i,o){let l=e.slice();for(let d=0,u=i;d<n.maps.length;d++){let p=0;n.maps[d].forEach((h,f,g,x)=>{let b=x-g-(f-h);for(let y=0;y<l.length;y+=3){let v=l[y+1];if(v<0||h>v+u-p)continue;let C=l[y]+u-p;f>=C?l[y+1]=h<=C?-2:-1:h>=u&&b&&(l[y]+=b,l[y+1]+=b)}p+=b}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d<l.length;d+=3)if(l[d+1]<0){if(l[d+1]==-2){c=!0,l[d+1]=-1;continue}let u=n.map(e[d]+i),p=u-s;if(p<0||p>=r.content.size){c=!0;continue}let h=n.map(e[d+1]+i,-1),f=h-s,{index:g,offset:x}=r.content.findIndex(p),b=r.maybeChild(g);if(b&&x==p&&x+b.nodeSize==f){let y=l[d+2].mapInner(n,b,u+1,e[d]+i+1,o);y!=yr?(l[d]=p,l[d+1]=f,l[d+2]=y):(l[d+1]=-2,c=!0)}else c=!0}if(c){let d=g9(l,e,t,n,s,i,o),u=af(d,r,0,o);t=u.local;for(let p=0;p<l.length;p+=3)l[p+1]<0&&(l.splice(p,3),p-=3);for(let p=0,h=0;p<u.children.length;p+=3){let f=u.children[p];for(;h<l.length&&l[h]<f;)h+=3;l.splice(h,0,u.children[p],u.children[p+1],u.children[p+2])}}return new Bt(t.sort(Wa),l)}function VN(e,t){if(!t||!e.length)return e;let n=[];for(let r=0;r<e.length;r++){let s=e[r];n.push(new Qn(s.from+t,s.to+t,s.type))}return n}function g9(e,t,n,r,s,i,o){function l(c,d){for(let u=0;u<c.local.length;u++){let p=c.local[u].map(r,s,d);p?n.push(p):o.onRemove&&o.onRemove(c.local[u].spec)}for(let u=0;u<c.children.length;u+=3)l(c.children[u+2],c.children[u]+d+1)}for(let c=0;c<e.length;c+=3)e[c+1]==-1&&l(e[c+2],t[c]+i+1);return n}function WN(e,t,n){if(t.isLeaf)return null;let r=n+t.nodeSize,s=null;for(let i=0,o;i<e.length;i++)(o=e[i])&&o.from>n&&o.to<r&&((s||(s=[])).push(o),e[i]=null);return s}function HN(e){let t=[];for(let n=0;n<e.length;n++)e[n]!=null&&t.push(e[n]);return t}function af(e,t,n,r){let s=[],i=!1;t.forEach((l,c)=>{let d=WN(e,l,c+n);if(d){i=!0;let u=af(d,l,n+c+1,r);u!=yr&&s.push(c,c+l.nodeSize,u)}});let o=VN(i?HN(e):e,-n).sort(Wa);for(let l=0;l<o.length;l++)o[l].type.valid(t,o[l])||(r.onRemove&&r.onRemove(o[l].spec),o.splice(l--,1));return o.length||s.length?new Bt(o,s):yr}function Wa(e,t){return e.from-t.from||e.to-t.to}function t0(e){let t=e;for(let n=0;n<t.length-1;n++){let r=t[n];if(r.from!=r.to)for(let s=n+1;s<t.length;s++){let i=t[s];if(i.from==r.from){i.to!=r.to&&(t==e&&(t=e.slice()),t[s]=i.copy(i.from,r.to),y1(t,s+1,i.copy(r.to,i.to)));continue}else{i.from<r.to&&(t==e&&(t=e.slice()),t[n]=r.copy(r.from,i.from),y1(t,s,r.copy(i.from,r.to)));break}}}return t}function y1(e,t,n){for(;t<e.length&&Wa(n,e[t])>0;)t++;e.splice(t,0,n)}var ia={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},of={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},x9=typeof navigator<"u"&&/Mac/.test(navigator.platform),b9=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var sr=0;sr<10;sr++)ia[48+sr]=ia[96+sr]=String(sr);for(var sr=1;sr<=24;sr++)ia[sr+111]="F"+sr;for(var sr=65;sr<=90;sr++)ia[sr]=String.fromCharCode(sr+32),of[sr]=String.fromCharCode(sr);for(var ox in ia)of.hasOwnProperty(ox)||(of[ox]=ia[ox]);function y9(e){var t=x9&&e.metaKey&&e.shiftKey&&!e.ctrlKey&&!e.altKey||b9&&e.shiftKey&&e.key&&e.key.length==1||e.key=="Unidentified",n=!t&&e.key||(e.shiftKey?of:ia)[e.keyCode]||e.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const v9=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),C9=typeof navigator<"u"&&/Win/.test(navigator.platform);function w9(e){let t=e.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let r,s,i,o;for(let l=0;l<t.length-1;l++){let c=t[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))s=!0;else if(/^s(hift)?$/i.test(c))i=!0;else if(/^mod$/i.test(c))v9?o=!0:s=!0;else throw new Error("Unrecognized modifier name: "+c)}return r&&(n="Alt-"+n),s&&(n="Ctrl-"+n),o&&(n="Meta-"+n),i&&(n="Shift-"+n),n}function S9(e){let t=Object.create(null);for(let n in e)t[w9(n)]=e[n];return t}function lx(e,t,n=!0){return t.altKey&&(e="Alt-"+e),t.ctrlKey&&(e="Ctrl-"+e),t.metaKey&&(e="Meta-"+e),n&&t.shiftKey&&(e="Shift-"+e),e}function qN(e){let t=S9(e);return function(n,r){let s=y9(r),i,o=t[lx(s,r)];if(o&&o(n.state,n.dispatch,n))return!0;if(s.length==1&&s!=" "){if(r.shiftKey){let l=t[lx(s,r,!1)];if(l&&l(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(C9&&r.ctrlKey&&r.altKey)&&(i=ia[r.keyCode])&&i!=s){let l=t[lx(i,r)];if(l&&l(n.state,n.dispatch,n))return!0}}return!1}}var j9=Object.defineProperty,n0=(e,t)=>{for(var n in t)j9(e,n,{get:t[n],enumerable:!0})};function GN(e){const{state:t,transaction:n}=e;let{selection:r}=n,{doc:s}=n,{storedMarks:i}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return r},get doc(){return s},get tr(){return r=n.selection,s=n.doc,i=n.storedMarks,n}}}var k9=class{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:e,editor:t,state:n}=this,{view:r}=t,{tr:s}=n,i=this.buildProps(s);return Object.fromEntries(Object.entries(e).map(([o,l])=>[o,(...d)=>{const u=l(...d)(i);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:n,editor:r,state:s}=this,{view:i}=r,o=[],l=!!e,c=e||s.tr,d=()=>(!l&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(c),o.every(p=>p===!0)),u={...Object.fromEntries(Object.entries(n).map(([p,h])=>[p,(...g)=>{const x=this.buildProps(c,t),b=h(...g)(x);return o.push(b),u}])),run:d};return u}createCan(e){const{rawCommands:t,state:n}=this,r=!1,s=e||n.tr,i=this.buildProps(s,r);return{...Object.fromEntries(Object.entries(t).map(([l,c])=>[l,(...d)=>c(...d)({...i,dispatch:void 0})])),chain:()=>this.createChain(s,r)}}buildProps(e,t=!0){const{rawCommands:n,editor:r,state:s}=this,{view:i}=r,o={tr:e,editor:r,view:i,state:GN({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(...d)=>c(...d)(o)]))}};return o}},ss={};n0(ss,{blur:()=>E9,clearContent:()=>_9,clearNodes:()=>T9,command:()=>I9,createParagraphNear:()=>D9,cut:()=>A9,deleteCurrentNode:()=>M9,deleteNode:()=>R9,deleteRange:()=>N9,deleteSelection:()=>L9,enter:()=>F9,exitCode:()=>$9,extendMarkRange:()=>B9,first:()=>U9,focus:()=>H9,forEach:()=>q9,insertContent:()=>G9,insertContentAt:()=>Q9,joinBackward:()=>Z9,joinDown:()=>X9,joinForward:()=>eJ,joinItemBackward:()=>tJ,joinItemForward:()=>nJ,joinTextblockBackward:()=>rJ,joinTextblockForward:()=>sJ,joinUp:()=>J9,keyboardShortcut:()=>aJ,lift:()=>oJ,liftEmptyBlock:()=>lJ,liftListItem:()=>cJ,newlineInCode:()=>dJ,resetAttributes:()=>uJ,scrollIntoView:()=>pJ,selectAll:()=>hJ,selectNodeBackward:()=>fJ,selectNodeForward:()=>mJ,selectParentNode:()=>gJ,selectTextblockEnd:()=>xJ,selectTextblockStart:()=>bJ,setContent:()=>vJ,setMark:()=>WJ,setMeta:()=>HJ,setNode:()=>qJ,setNodeSelection:()=>GJ,setTextDirection:()=>YJ,setTextSelection:()=>KJ,sinkListItem:()=>QJ,splitBlock:()=>JJ,splitListItem:()=>XJ,toggleList:()=>eX,toggleMark:()=>tX,toggleNode:()=>nX,toggleWrap:()=>rX,undoInputRule:()=>sX,unsetAllMarks:()=>iX,unsetMark:()=>aX,unsetTextDirection:()=>oX,updateAttributes:()=>lX,wrapIn:()=>cX,wrapInList:()=>dX});var E9=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{var n;e.isDestroyed||(t.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),_9=(e=!0)=>({commands:t})=>t.setContent("",{emitUpdate:e}),T9=()=>({state:e,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:s}=r;return n&&s.forEach(({$from:i,$to:o})=>{e.doc.nodesBetween(i.pos,o.pos,(l,c)=>{if(l.type.isText)return;const{doc:d,mapping:u}=t,p=d.resolve(u.map(c)),h=d.resolve(u.map(c+l.nodeSize)),f=p.blockRange(h);if(!f)return;const g=Ml(f);if(l.type.isTextblock){const{defaultType:x}=p.parent.contentMatchAt(p.index());t.setNodeMarkup(f.start,x)}(g||g===0)&&t.lift(f,g)})}),!0},I9=e=>t=>e(t),D9=()=>({state:e,dispatch:t})=>xN(e,t),A9=(e,t)=>
50({editor:n,tr:r})=>{const{state:s}=n,i=s.doc.slice(e.from,e.to);r.deleteRange(e.from,e.to);const o=r.mapping.map(t);return r.insert(o,i.content),r.setSelection(new Ke(r.doc.resolve(Math.max(o-1,0)))),!0},M9=()=>({tr:e,dispatch:t})=>{const{selection:n}=e,r=n.$anchor.node();if(r.content.size>0)return!1;const s=e.selection.$anchor;for(let i=s.depth;i>0;i-=1)if(s.node(i).type===r.type){if(t){const l=s.before(i),c=s.after(i);e.delete(l,c).scrollIntoView()}return!0}return!1};function qn(e,t){if(typeof e=="string"){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}var R9=e=>({tr:t,state:n,dispatch:r})=>{const s=qn(e,n.schema),i=t.selection.$anchor;for(let o=i.depth;o>0;o-=1)if(i.node(o).type===s){if(r){const c=i.before(o),d=i.after(o);t.delete(c,d).scrollIntoView()}return!0}return!1},N9=e=>({tr:t,dispatch:n})=>{const{from:r,to:s}=e;return n&&t.delete(r,s),!0},O9=e=>e.content?/^text(\*|\+)/.test(e.content):!1,v1=(e,t,n)=>{if(!e.parent.isInline||n==="left"&&e.pos>e.start()||n==="right"&&e.pos<e.end())return e.pos;const r=t.nodes[e.parent.type.name].spec;return O9(r)?n==="left"?e.start()-1:e.end()+1:e.pos},P9=(e,t,n)=>{const r=v1(e,n,"left"),s=v1(t,n,"right");return{from:r,to:s}},L9=()=>({state:e,dispatch:t})=>{const{$from:n,$to:r}=e.selection;if(e.selection.empty)return!1;const{from:s,to:i}=P9(n,r,e.schema);return t&&(e.tr.deleteRange(s,i).scrollIntoView(),t(e.tr)),!0},F9=()=>({commands:e})=>e.keyboardShortcut("Enter"),$9=()=>({state:e,dispatch:t})=>mQ(e,t);function z9(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function lf(e,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(s=>n.strict?t[s]===e[s]:z9(t[s])?t[s].test(e[s]):t[s]===e[s]):!0}function YN(e,t,n={}){return e.find(r=>r.type===t&&lf(Object.fromEntries(Object.keys(n).map(s=>[s,r.attrs[s]])),n))}function C1(e,t,n={}){return!!YN(e,t,n)}function r0(e,t,n){if(!e||!t)return;let r=e.parent.childAfter(e.parentOffset);if((!r.node||!r.node.marks.some(d=>d.type===t))&&(r=e.parent.childBefore(e.parentOffset)),!r.node||!r.node.marks.some(d=>d.type===t))return;if(!n){const d=r.node.marks.find(u=>u.type===t);d&&(n=d.attrs)}if(!YN([...r.node.marks],t,n))return;let i=r.index,o=e.start()+r.offset,l=i+1,c=o+r.node.nodeSize;for(;i>0&&C1([...e.parent.child(i-1).marks],t,n);)i-=1,o-=e.parent.child(i).nodeSize;for(;l<e.parent.childCount&&C1([...e.parent.child(l).marks],t,n);)c+=e.parent.child(l).nodeSize,l+=1;return{from:o,to:c}}function fa(e,t){if(typeof e=="string"){if(!t.marks[e])throw Error(`There is no mark type named '${e}'. Maybe you forgot to add the extension?`);return t.marks[e]}return e}var B9=(e,t)=>({tr:n,state:r,dispatch:s})=>{const i=fa(e,r.schema),{doc:o,selection:l}=n,{$from:c,from:d,to:u}=l;if(s){const p=r0(c,i,t);if(p&&p.from<=d&&p.to>=u){const h=Ke.create(o,p.from,p.to);n.setSelection(h)}}return!0},U9=e=>t=>{const n=typeof e=="function"?e(t):e;for(let r=0;r<n.length;r+=1)if(n[r](t))return!0;return!1};function s0(e){return e instanceof Ke}function Na(e=0,t=0,n=0){return Math.min(Math.max(e,t),n)}function V9(e,t=null){if(!t)return null;const n=nt.atStart(e),r=nt.atEnd(e);if(t==="start"||t===!0)return n;if(t==="end")return r;const s=n.from,i=r.to;return t==="all"?Ke.create(e,Na(0,s,i),Na(e.content.size,s,i)):Ke.create(e,Na(t,s,i),Na(t,s,i))}function xy(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function Vd(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function W9(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var H9=(e=null,t={})=>({editor:n,view:r,tr:s,dispatch:i})=>{t={scrollIntoView:!0,...t};const o=()=>{(Vd()||xy())&&r.dom.focus(),W9()&&!Vd()&&!xy()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),t?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&e===null||e===!1)return!0}catch{return!1}if(i&&e===null&&!s0(n.state.selection))return o(),!0;const l=V9(s.doc,e)||n.state.selection,c=n.state.selection.eq(l);return i&&(c||s.setSelection(l),c&&s.storedMarks&&s.setStoredMarks(s.storedMarks),o()),!0},q9=(e,t)=>
vendor: 9,557 bytes, line 50
50n=>e.every((r,s)=>t(r,{...n,index:s})),G9=(e,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},e,t),KN=e=>{const t=e.childNodes;for(let n=t.length-1;n>=0;n-=1){const r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?e.removeChild(r):r.nodeType===1&&KN(r)}return e};function id(e){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const t=`<body>${e}</body>`,n=new window.DOMParser().parseFromString(t,"text/html").body;return KN(n)}function Wd(e,t,n){if(e instanceof Ua||e instanceof we)return e;n={slice:!0,parseOptions:{},...n};const r=typeof e=="object"&&e!==null,s=typeof e=="string";if(r)try{if(Array.isArray(e)&&e.length>0)return we.fromArray(e.map(l=>t.nodeFromJSON(l)));const o=t.nodeFromJSON(e);return n.errorOnInvalidContent&&o.check(),o}catch(i){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",e,"Error:",i),Wd("",t,n)}if(s){if(n.errorOnInvalidContent){let o=!1,l="";const c=new UR({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:d=>(o=!0,l=typeof d=="string"?d:d.outerHTML,null)}]}})});if(n.slice?Xi.fromSchema(c).parseSlice(id(e),n.parseOptions):Xi.fromSchema(c).parse(id(e),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const i=Xi.fromSchema(t);return n.slice?i.parseSlice(id(e),n.parseOptions).content:i.parse(id(e),n.parseOptions)}return Wd("",t,n)}function Y9(e,t,n){const r=e.steps.length-1;if(r<t)return;const s=e.steps[r];if(!(s instanceof Pn||s instanceof Jn))return;const i=e.mapping.maps[r];let o=0;i.forEach((l,c,d,u)=>{o===0&&(o=u)}),e.setSelection(nt.near(e.doc.resolve(o),n))}var K9=e=>!("type"in e),Q9=(e,t,n)=>({tr:r,dispatch:s,editor:i})=>{var o;if(s){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=b=>{i.emit("contentError",{editor:i,error:b,disableCollaboration:()=>{"collaboration"in i.storage&&typeof i.storage.collaboration=="object"&&i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{Wd(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{l=Wd(t,i.schema,{parseOptions:d,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:i.options.enableContentCheck})}catch(b){return c(b),!1}let{from:u,to:p}=typeof e=="number"?{from:e,to:e}:{from:e.from,to:e.to},h=!0,f=!0;if((K9(l)?l:[l]).forEach(b=>{b.check(),h=h?b.isText&&b.marks.length===0:!1,f=f?b.isBlock:!1}),u===p&&f){const{parent:b}=r.doc.resolve(u);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(u-=1,p+=1)}let x;if(h){if(Array.isArray(t))x=t.map(b=>b.text||"").join("");else if(t instanceof we){let b="";t.forEach(y=>{y.text&&(b+=y.text)}),x=b}else typeof t=="object"&&t&&t.text?x=t.text:x=t;r.insertText(x,u,p)}else{x=l;const b=r.doc.resolve(u),y=b.node(),v=b.parentOffset===0,C=y.isText||y.isTextblock,w=y.content.size>0;v&&C&&w&&f&&(u=Math.max(0,u-1)),r.replaceWith(u,p,x)}n.updateSelection&&Y9(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:x}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:x})}return!0},J9=()=>({state:e,dispatch:t})=>pQ(e,t),X9=()=>({state:e,dispatch:t})=>hQ(e,t),Z9=()=>({state:e,dispatch:t})=>dN(e,t),eJ=()=>({state:e,dispatch:t})=>fN(e,t),tJ=()=>({state:e,dispatch:t,tr:n})=>{try{const r=Bm(e.doc,e.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},nJ=()=>({state:e,dispatch:t,tr:n})=>{try{const r=Bm(e.doc,e.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},rJ=()=>({state:e,dispatch:t})=>dQ(e,t),sJ=()=>({state:e,dispatch:t})=>uQ(e,t);function QN(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function iJ(e){const t=e.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,s,i,o;for(let l=0;l<t.length-1;l+=1){const c=t[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))s=!0;else if(/^s(hift)?$/i.test(c))i=!0;else if(/^mod$/i.test(c))Vd()||QN()?o=!0:s=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),s&&(n=`Ctrl-${n}`),o&&(n=`Meta-${n}`),i&&(n=`Shift-${n}`),n}var aJ=e=>({editor:t,view:n,tr:r,dispatch:s})=>{const i=iJ(e).split(/-(?!$)/),o=i.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,l))});return c?.steps.forEach(d=>{const u=d.map(r.mapping);u&&s&&r.maybeStep(u)}),!0};function ll(e,t,n={}){const{from:r,to:s,empty:i}=e.selection,o=t?qn(t,e.schema):null,l=[];e.doc.nodesBetween(r,s,(p,h)=>{if(p.isText)return;const f=Math.max(r,h),g=Math.min(s,h+p.nodeSize);l.push({node:p,from:f,to:g})});const c=s-r,d=l.filter(p=>o?o.name===p.node.type.name:!0).filter(p=>lf(p.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((p,h)=>p+h.to-h.from,0)>=c}var oJ=(e,t={})=>({state:n,dispatch:r})=>{const s=qn(e,n.schema);return ll(n,s,t)?fQ(n,r):!1},lJ=()=>({state:e,dispatch:t})=>bN(e,t),cJ=e=>({state:t,dispatch:n})=>{const r=qn(e,t.schema);return EQ(r)(t,n)},dJ=()=>({state:e,dispatch:t})=>gN(e,t);function i0(e,t){return t.nodes[e]?"node":t.marks[e]?"mark":null}function w1(e,t){const n=typeof t=="string"?[t]:t;return Object.keys(e).reduce((r,s)=>(n.includes(s)||(r[s]=e[s]),r),{})}var uJ=(e,t)=>({tr:n,state:r,dispatch:s})=>{let i=null,o=null;const l=i0(typeof e=="string"?e:e.name,r.schema);if(!l)return!1;l==="node"&&(i=qn(e,r.schema)),l==="mark"&&(o=fa(e,r.schema));let c=!1;return n.selection.ranges.forEach(d=>{r.doc.nodesBetween(d.$from.pos,d.$to.pos,(u,p)=>{i&&i===u.type&&(c=!0,s&&n.setNodeMarkup(p,void 0,w1(u.attrs,t))),o&&u.marks.length&&u.marks.forEach(h=>{o===h.type&&(c=!0,s&&n.addMark(p,p+u.nodeSize,o.create(w1(h.attrs,t))))})})}),c},pJ=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),hJ=()=>({tr:e,dispatch:t})=>{if(t){const n=new Lr(e.doc);e.setSelection(n)}return!0},fJ=()=>({state:e,dispatch:t})=>pN(e,t),mJ=()=>({state:e,dispatch:t})=>mN(e,t),gJ=()=>({state:e,dispatch:t})=>bQ(e,t),xJ=()=>({state:e,dispatch:t})=>CQ(e,t),bJ=()=>({state:e,dispatch:t})=>vQ(e,t);function yJ(e,t,n={},r={}){return Wd(e,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var vJ=(e,{errorOnInvalidContent:t,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:s,tr:i,dispatch:o,commands:l})=>{const{doc:c}=i;if(r.preserveWhitespace!=="full"){const d=yJ(e,s.schema,r,{errorOnInvalidContent:t??s.options.enableContentCheck});return o&&i.replaceWith(0,c.content.size,d).setMeta("preventUpdate",!n),!0}return o&&i.setMeta("preventUpdate",!n),l.insertContentAt({from:0,to:c.content.size},e,{parseOptions:r,errorOnInvalidContent:t??s.options.enableContentCheck})};function JN(e,t){const n=fa(t,e.schema),{from:r,to:s,empty:i}=e.selection,o=[];i?(e.storedMarks&&o.push(...e.storedMarks),o.push(...e.selection.$head.marks())):e.doc.nodesBetween(r,s,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function XN(e,t){const n=new sN(e);return t.forEach(r=>{r.steps.forEach(s=>{n.step(s)})}),n}function CJ(e){for(let t=0;t<e.edgeCount;t+=1){const{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function wJ(e,t,n){const r=[];return e.nodesBetween(t.from,t.to,(s,i)=>{n(s)&&r.push({node:s,pos:i})}),r}function ZN(e,t){for(let n=e.depth;n>0;n-=1){const r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function qm(e){return t=>ZN(t.$from,e)}function st(e,t,n){return e.config[t]===void 0&&e.parent?st(e.parent,t,n):typeof e.config[t]=="function"?e.config[t].bind({...n,parent:e.parent?st(e.parent,t,n):null}):e.config[t]}function a0(e){return e.map(t=>{const n={name:t.name,options:t.options,storage:t.storage},r=st(t,"addExtensions",n);return r?[t,...a0(r())]:t}).flat(10)}function SJ(e){return typeof e=="function"}function It(e,t=void 0,...n){return SJ(e)?t?e.bind(t)(...n):e(...n):e}function jJ(e={}){return Object.keys(e).length===0&&e.constructor===Object}function Gm(e){const t=e.filter(s=>s.type==="extension"),n=e.filter(s=>s.type==="node"),r=e.filter(s=>s.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function kJ(e){const t=[],{nodeExtensions:n,markExtensions:r}=Gm(e),s=[...n,...r],i={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=n.filter(d=>d.name!=="text").map(d=>d.name),l=r.map(d=>d.name),c=[...o,...l];return e.forEach(d=>{const u={name:d.name,options:d.options,storage:d.storage,extensions:s},p=st(d,"addGlobalAttributes",u);if(!p)return;p().forEach(f=>{let g;Array.isArray(f.types)?g=f.types:f.types==="*"?g=c:f.types==="nodes"?g=o:f.types==="marks"?g=l:g=[],g.forEach(x=>{Object.entries(f.attributes).forEach(([b,y])=>{t.push({type:x,name:b,attribute:{...i,...y}})})})})}),s.forEach(d=>{const u={name:d.name,options:d.options,storage:d.storage},p=st(d,"addAttributes",u);if(!p)return;const h=p();
50Object.entries(h).forEach(([f,g])=>{const x={...i,...g};typeof x?.default=="function"&&(x.default=x.default()),x?.isRequired&&x?.default===void 0&&delete x.default,t.push({type:d.name,name:f,attribute:x})})}),t}function EJ(e){const t=[];let n="",r=!1,s=!1,i=0;const o=e.length;for(let l=0;l<o;l+=1){const c=e[l];if(c==="'"&&!s){r=!r,n+=c;continue}if(c==='"'&&!r){s=!s,n+=c;continue}if(!r&&!s){if(c==="("){i+=1,n+=c;continue}if(c===")"&&i>0){i-=1,n+=c;continue}if(c===";"&&i===0){t.push(n),n="";continue}}n+=c}return n&&t.push(n),t}function S1(e){const t=[],n=EJ(e||""),r=n.length;for(let s=0;s<r;s+=1){const i=n[s],o=i.indexOf(":");if(o===-1)continue;const l=i.slice(0,o).trim(),c=i.slice(o+1).trim();l&&c&&t.push([l,c])}return t}function an(...e){return e.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([s,i])=>{if(!r[s]){r[s]=i;return}if(s==="class"){const l=i?String(i).split(" "):[],c=r[s]?r[s].split(" "):[],d=l.filter(u=>!c.includes(u));r[s]=[...c,...d].join(" ")}else if(s==="style"){const l=new Map([...S1(r[s]),...S1(i)]);r[s]=Array.from(l.entries()).map(([c,d])=>`${c}: ${d}`).join("; ")}else r[s]=i}),r},{})}function cf(e,t){return t.filter(n=>n.type===e.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(e.attrs)||{}:{[n.name]:e.attrs[n.name]}).reduce((n,r)=>an(n,r),{})}function _J(e){return typeof e!="string"?e:e.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(e):e==="true"?!0:e==="false"?!1:e}function j1(e,t){return"style"in e?e:{...e,getAttrs:n=>{const r=e.getAttrs?e.getAttrs(n):e.attrs;if(r===!1)return!1;const s=t.reduce((i,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):_J(n.getAttribute(o.name));return l==null?i:{...i,[o.name]:l}},{});return{...r,...s}}}}function k1(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t==="attrs"&&jJ(n)?!1:n!=null))}function E1(e){var t,n;const r={};return!((t=e?.attribute)!=null&&t.isRequired)&&"default"in(e?.attribute||{})&&(r.default=e.attribute.default),((n=e?.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=e.attribute.validate),[e.name,r]}function TJ(e,t){var n;const r=kJ(e),{nodeExtensions:s,markExtensions:i}=Gm(e),o=(n=s.find(d=>st(d,"topNode")))==null?void 0:n.name,l=Object.fromEntries(s.map(d=>{const u=r.filter(y=>y.type===d.name),p={name:d.name,options:d.options,storage:d.storage,editor:t},h=e.reduce((y,v)=>{const C=st(v,"extendNodeSchema",p);return{...y,...C?C(d):{}}},{}),f=k1({...h,content:It(st(d,"content",p)),marks:It(st(d,"marks",p)),group:It(st(d,"group",p)),inline:It(st(d,"inline",p)),atom:It(st(d,"atom",p)),selectable:It(st(d,"selectable",p)),draggable:It(st(d,"draggable",p)),code:It(st(d,"code",p)),whitespace:It(st(d,"whitespace",p)),linebreakReplacement:It(st(d,"linebreakReplacement",p)),defining:It(st(d,"defining",p)),isolating:It(st(d,"isolating",p)),attrs:Object.fromEntries(u.map(E1))}),g=It(st(d,"parseHTML",p));g&&(f.parseDOM=g.map(y=>j1(y,u)));const x=st(d,"renderHTML",p);x&&(f.toDOM=y=>x({node:y,HTMLAttributes:cf(y,u)}));const b=st(d,"renderText",p);return b&&(f.toText=b),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(b=>b.type===d.name),p={name:d.name,options:d.options,storage:d.storage,editor:t},h=e.reduce((b,y)=>{const v=st(y,"extendMarkSchema",p);return{...b,...v?v(d):{}}},{}),f=k1({...h,inclusive:It(st(d,"inclusive",p)),excludes:It(st(d,"excludes",p)),group:It(st(d,"group",p)),spanning:It(st(d,"spanning",p)),code:It(st(d,"code",p)),attrs:Object.fromEntries(u.map(E1))}),g=It(st(d,"parseHTML",p));g&&(f.parseDOM=g.map(b=>j1(b,u)));const x=st(d,"renderHTML",p);return x&&(f.toDOM=b=>x({mark:b,HTMLAttributes:cf(b,u)})),[d.name,f]}));return new UR({topNode:o,nodes:l,marks:c})}function IJ(e){const t=e.filter((n,r)=>e.indexOf(n)!==r);return Array.from(new Set(t))}function eO(e){return e.sort((n,r)=>{const s=st(n,"priority")||100,i=st(r,"priority")||100;return s>i?-1:s<i?1:0})}function DJ(e){const t=eO(a0(e)),n=IJ(t.map(r=>r.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),t}function tO(e,t){const n=DJ(e);return TJ(n,t)}function AJ(e,t){const n=tO(t),r=id(e);
vendor: 5,573 bytes, lines 50-52
50return Xi.fromSchema(n).parse(r).toJSON()}function MJ(e,t,n){const{from:r,to:s}=t,{blockSeparator:i=` 51 52`,textSerializers:o={}}=n||{};let l="";return e.nodesBetween(r,s,(c,d,u,p)=>{var h;c.isBlock&&d>r&&(l+=i);const f=o?.[c.type.name];if(f)return u&&(l+=f({node:c,pos:d,parent:u,index:p,range:t})),!1;c.isText&&(l+=(h=c?.text)==null?void 0:h.slice(Math.max(r,d)-d,s-d))}),l}function RJ(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}function NJ(e,t){const n=qn(t,e.schema),{from:r,to:s}=e.selection,i=[];e.doc.nodesBetween(r,s,l=>{i.push(l)});const o=i.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function OJ(e,t){const n=i0(typeof t=="string"?t:t.name,e.schema);return n==="node"?NJ(e,t):n==="mark"?JN(e,t):{}}function PJ(e,t=JSON.stringify){const n={};return e.filter(r=>{const s=t(r);return Object.prototype.hasOwnProperty.call(n,s)?!1:n[s]=!0})}function LJ(e){const t=PJ(e);return t.length===1?t:t.filter((n,r)=>!t.filter((i,o)=>o!==r).some(i=>n.oldRange.from>=i.oldRange.from&&n.oldRange.to<=i.oldRange.to&&n.newRange.from>=i.newRange.from&&n.newRange.to<=i.newRange.to))}function nO(e){const{mapping:t,steps:n}=e,r=[];return t.maps.forEach((s,i)=>{const o=[];if(s.ranges.length)s.forEach((l,c)=>{o.push({from:l,to:c})});else{const{from:l,to:c}=n[i];if(l===void 0||c===void 0)return;o.push({from:l,to:c})}o.forEach(({from:l,to:c})=>{const d=t.slice(i).map(l,-1),u=t.slice(i).map(c),p=t.invert().map(d,-1),h=t.invert().map(u);r.push({oldRange:{from:p,to:h},newRange:{from:d,to:u}})})}),LJ(r)}function o0(e,t,n){const r=[];return e===t?n.resolve(e).marks().forEach(s=>{const i=n.resolve(e),o=r0(i,s.type);o&&r.push({mark:s,...o})}):n.nodesBetween(e,t,(s,i)=>{!s||s?.nodeSize===void 0||r.push(...s.marks.map(o=>({from:i,to:i+s.nodeSize,mark:o})))}),r}var FJ=(e,t,n,r=20)=>{const s=e.doc.resolve(n);let i=r,o=null;for(;i>0&&o===null;){const l=s.node(i);l?.type.name===t?o=l:i-=1}return[o,i]};function bh(e,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const s=e.find(i=>i.type===t&&i.name===r);return s?s.attribute.keepOnSplit:!1}))}function $J(e,t,n={}){const{empty:r,ranges:s}=e.selection,i=t?fa(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(p=>i?i.name===p.type.name:!0).find(p=>lf(p.attrs,n,{strict:!1}));let o=0;const l=[];if(s.forEach(({$from:p,$to:h})=>{const f=p.pos,g=h.pos;e.doc.nodesBetween(f,g,(x,b)=>{if(i&&x.inlineContent&&!x.type.allowsMarkType(i))return!1;if(!x.isText&&!x.marks.length)return;const y=Math.max(f,b),v=Math.min(g,b+x.nodeSize),C=v-y;o+=C,l.push(...x.marks.map(w=>({mark:w,from:y,to:v})))})}),o===0)return!1;const c=l.filter(p=>i?i.name===p.mark.type.name:!0).filter(p=>lf(p.mark.attrs,n,{strict:!1})).reduce((p,h)=>p+h.to-h.from,0),d=l.filter(p=>i?p.mark.type!==i&&p.mark.type.excludes(i):!0).reduce((p,h)=>p+h.to-h.from,0);return(c>0?c+d:c)>=o}var zJ=(e,t)=>{const{$from:n,$to:r,$anchor:s}=e.selection;if(t){const i=qm(l=>l.type.name===t)(e.selection);if(!i)return!1;const o=e.doc.resolve(i.pos+1);return s.pos+1===o.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},BJ=e=>{const{$from:t,$to:n}=e.selection;return!(t.parentOffset>0||t.pos!==n.pos)};function cx(e,t){const{nodeExtensions:n}=Gm(t),r=n.find(o=>o.name===e);if(!r)return!1;const s={name:r.name,options:r.options,storage:r.storage},i=It(st(r,"group",s));return typeof i!="string"?!1:i.split(" ").includes("list")}function df(e,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(e.type.name==="hardBreak")return!0;if(e.isText)return!/\S/.test((r=e.text)!=null?r:"")}if(e.isText)return!e.text;if(e.isAtom||e.isLeaf)return!1;if(e.content.childCount===0)return!0;if(t){let s=!0;return e.content.forEach(i=>{s!==!1&&(df(i,{ignoreWhitespace:n,checkChildren:t})||(s=!1))}),s}return!1}function rO(e){return e instanceof Ye}function UJ({selection:e,pos:t,nodeSize:n,selectedOnTextSelection:r=!1}){const{from:s,to:i}=e;return!!(s<=t&&i>=t+n||r&&s0(e)&&s>t&&i<t+n)}function VJ(e,t,n){var r;const{selection:s}=t;let i=null;if(s0(s)&&(i=s.$cursor),i){const l=(r=e.storedMarks)!=null?r:i.marks();return i.parent.type.allowsMarkType(n)&&(!!n.isInSet(l)||!l.some(d=>d.type.excludes(n)))}const{ranges:o}=s;return o.some(({$from:l,$to:c})=>{let d=l.depth===0?e.doc.inlineContent&&e.doc.type.allowsMarkType(n):!1;return e.doc.nodesBetween(l.pos,c.pos,(u,p,h)=>{if(d)return!1;if(u.isInline){const f=!h||h.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(x=>x.type.excludes(n));d=f&&g}return!d}),d})}var WJ=(e,t={})=>({tr:n,state:r,dispatch:s})=>{const{selection:i}=n,{empty:o,ranges:l}=i,c=fa(e,r.schema);if(s)if(o){const d=JN(r,c);n.addStoredMark(c.create({...d,...t}))}else l.forEach(d=>{const u=d.$from.pos,p=d.$to.pos;r.doc.nodesBetween(u,p,(h,f)=>{const g=Math.max(f,u),x=Math.min(f+h.nodeSize,p);h.marks.find(y=>y.type===c)?h.marks.forEach(y=>{c===y.type&&n.addMark(g,x,c.create({...y.attrs,...t}))}):n.addMark(g,x,c.create(t))})});return VJ(r,n,c)},HJ=(e,t)=>({tr:n})=>(n.setMeta(e,t),!0),qJ=(e,t={})=>({state:n,dispatch:r,chain:s})=>{const i=qn(e,n.schema);let o;return n.selection.$anchor.sameParent(n.selection.$head)&&(o=n.selection.$anchor.parent.attrs),i.isTextblock?s().command(({commands:l})=>i1(i,{...o,...t})(n)?!0:l.clearNodes()).command(({state:l})=>i1(i,{...o,...t})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},GJ=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,s=Na(e,0,r.content.size),i=Ye.create(r,s);t.setSelection(i)}return!0},YJ=(e,t)=>
52({tr:n,state:r,dispatch:s})=>{const{selection:i}=r;let o,l;return typeof t=="number"?(o=t,l=t):t&&"from"in t&&"to"in t?(o=t.from,l=t.to):(o=i.from,l=i.to),s&&n.doc.nodesBetween(o,l,(c,d)=>{c.isText||n.setNodeMarkup(d,void 0,{...c.attrs,dir:e})}),!0},KJ=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:s,to:i}=typeof e=="number"?{from:e,to:e}:e,o=Ke.atStart(r).from,l=Ke.atEnd(r).to,c=Na(s,o,l),d=Na(i,o,l),u=Ke.create(r,c,d);t.setSelection(u)}return!0},QJ=e=>({state:t,dispatch:n})=>{const r=qn(e,t.schema);return IQ(r)(t,n)};function _1(e,t){const n=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();if(n){const r=n.filter(s=>t?.includes(s.type.name));e.tr.ensureMarks(r)}}var JJ=({keepMarks:e=!0}={})=>({tr:t,state:n,dispatch:r,editor:s})=>{const{selection:i,doc:o}=t,{$from:l,$to:c}=i,d=s.extensionManager.attributes,u=bh(d,l.node().type.name,l.node().attrs);if(i instanceof Ye&&i.node.isBlock)return!l.parentOffset||!xi(o,l.pos)?!1:(r&&(e&&_1(n,s.extensionManager.splittableMarks),t.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const p=c.parentOffset===c.parent.content.size,h=l.depth===0?void 0:CJ(l.node(-1).contentMatchAt(l.indexAfter(-1)));let f=p&&h?[{type:h,attrs:u}]:void 0,g=xi(t.doc,t.mapping.map(l.pos),1,f);if(!f&&!g&&xi(t.doc,t.mapping.map(l.pos),1,h?[{type:h}]:void 0)&&(g=!0,f=h?[{type:h,attrs:u}]:void 0),r){if(g&&(i instanceof Ke&&t.deleteSelection(),t.split(t.mapping.map(l.pos),1,f),h&&!p&&!l.parentOffset&&l.parent.type!==h)){const x=t.mapping.map(l.before()),b=t.doc.resolve(x);l.node(-1).canReplaceWith(b.index(),b.index()+1,h)&&t.setNodeMarkup(t.mapping.map(l.before()),h)}e&&_1(n,s.extensionManager.splittableMarks),t.scrollIntoView()}return g},XJ=(e,t={})=>({tr:n,state:r,dispatch:s,editor:i})=>{var o;const l=qn(e,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const p=c.node(-1);if(p.type!==l)return!1;const h=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==l||c.index(-2)!==c.node(-2).childCount-1)return!1;if(s){let y=we.empty;const v=c.index(-1)?1:c.index(-2)?2:3;for(let j=c.depth-v;j>=c.depth-3;j-=1)y=we.from(c.node(j).copy(y));const C=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,w={...bh(h,c.node().type.name,c.node().attrs),...t},S=((o=l.contentMatch.defaultType)==null?void 0:o.createAndFill(w))||void 0;y=y.append(we.from(l.createAndFill(null,S)||void 0));const E=c.before(c.depth-(v-1));n.replace(E,c.after(-C),new Te(y,4-v,0));let k=-1;n.doc.nodesBetween(E,n.doc.content.size,(j,_)=>{if(k>-1)return!1;j.isTextblock&&j.content.size===0&&(k=_+1)}),k>-1&&n.setSelection(Ke.near(n.doc.resolve(k))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?p.contentMatchAt(0).defaultType:null,g={...bh(h,p.type.name,p.attrs),...t},x={...bh(h,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const b=f?[{type:l,attrs:g},{type:f,attrs:x}]:[{type:l,attrs:g}];if(!xi(n.doc,c.pos,2))return!1;if(s){const{selection:y,storedMarks:v}=r,{splittableMarks:C}=i.extensionManager,w=v||y.$to.parentOffset&&y.$from.marks();if(n.split(c.pos,2,b).scrollIntoView(),!w||!s)return!0;const S=w.filter(E=>C.includes(E.type.name));n.ensureMarks(S)}return!0},dx=(e,t)=>{const n=qm(o=>o.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const s=e.doc.nodeAt(r);return n.node.type===s?.type&&pa(e.doc,n.pos)&&e.join(n.pos),!0},ux=(e,t)=>{const n=qm(o=>o.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const s=e.doc.nodeAt(r);return n.node.type===s?.type&&pa(e.doc,r)&&e.join(r),!0};function ZJ(e){const t=e.doc,n=t.firstChild;if(!n)return null;const r=t.resolve(1),s=t.resolve(n.nodeSize-1);return Ke.between(r,s)}var eX=(e,t,n,r={})=>({editor:s,tr:i,state:o,dispatch:l,chain:c,commands:d,can:u})=>{const{extensions:p,splittableMarks:h}=s.extensionManager,f=qn(e,o.schema),g=qn(t,o.schema),{selection:x,storedMarks:b}=o,{$from:y,$to:v}=x,C=y.blockRange(v),w=b||x.$to.parentOffset&&x.$from.marks();if(!C)return!1;const S=qm(O=>cx(O.type.name,p))(x),E=x.from===0&&x.to===o.doc.content.size,k=o.doc.content.content,j=k.length===1?k[0]:null,_=E&&j&&cx(j.type.name,p)?{node:j,pos:0}:null,D=S??_,M=!!S&&C.depth>=1&&C.depth-S.depth<=1,N=!!_;if((M||N)&&D){if(D.node.type===f)return E&&N?c().command(({tr:O,dispatch:R})=>{const L=ZJ(O);return L?(O.setSelection(L),R&&R(O),!0):!1}).liftListItem(g).run():d.liftListItem(g);
vendor: 5,615 bytes, line 52
52if(cx(D.node.type.name,p)&&f.validContent(D.node.content))return c().command(()=>(i.setNodeMarkup(D.pos,f),!0)).command(()=>dx(i,f)).command(()=>ux(i,f)).run()}return!n||!w||!l?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>dx(i,f)).command(()=>ux(i,f)).run():c().command(()=>{const O=u().wrapInList(f,r),R=w.filter(L=>h.includes(L.type.name));return i.ensureMarks(R),O?!0:d.clearNodes()}).wrapInList(f,r).command(()=>dx(i,f)).command(()=>ux(i,f)).run()},tX=(e,t={},n={})=>({state:r,commands:s})=>{const{extendEmptyMarkRange:i=!1}=n,o=fa(e,r.schema);return $J(r,o,t)?s.unsetMark(o,{extendEmptyMarkRange:i}):s.setMark(o,t)},nX=(e,t,n={})=>({state:r,commands:s})=>{const i=qn(e,r.schema),o=qn(t,r.schema),l=ll(r,i,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?s.setNode(o,c):s.setNode(i,{...c,...n})},rX=(e,t={})=>({state:n,commands:r})=>{const s=qn(e,n.schema);return ll(n,s,t)?r.lift(s):r.wrapIn(s,t)},sX=()=>({state:e,dispatch:t})=>{const n=e.plugins;for(let r=0;r<n.length;r+=1){const s=n[r];let i;if(s.spec.isInputRules&&(i=s.getState(e))){if(t){const o=e.tr,l=i.transform;for(let c=l.steps.length-1;c>=0;c-=1)o.step(l.steps[c].invert(l.docs[c]));if(i.text){const c=o.doc.resolve(i.from).marks();o.replaceWith(i.from,i.to,e.schema.text(i.text,c))}else o.delete(i.from,i.to)}return!0}}return!1},iX=()=>({tr:e,dispatch:t})=>{const{selection:n}=e,{empty:r,ranges:s}=n;return r||t&&s.forEach(i=>{e.removeMark(i.$from.pos,i.$to.pos)}),!0},aX=(e,t={})=>({tr:n,state:r,dispatch:s})=>{var i;const{extendEmptyMarkRange:o=!1}=t,{selection:l}=n,c=fa(e,r.schema),{$from:d,empty:u,ranges:p}=l;if(!s)return!0;if(u&&o){let{from:h,to:f}=l;const g=(i=d.marks().find(b=>b.type===c))==null?void 0:i.attrs,x=r0(d,c,g);x&&(h=x.from,f=x.to),n.removeMark(h,f,c)}else p.forEach(h=>{n.removeMark(h.$from.pos,h.$to.pos,c)});return n.removeStoredMark(c),!0},oX=e=>({tr:t,state:n,dispatch:r})=>{const{selection:s}=n;let i,o;return typeof e=="number"?(i=e,o=e):e&&"from"in e&&"to"in e?(i=e.from,o=e.to):(i=s.from,o=s.to),r&&t.doc.nodesBetween(i,o,(l,c)=>{if(l.isText)return;const d={...l.attrs};delete d.dir,t.setNodeMarkup(c,void 0,d)}),!0},lX=(e,t={})=>({tr:n,state:r,dispatch:s})=>{let i=null,o=null;const l=i0(typeof e=="string"?e:e.name,r.schema);if(!l)return!1;l==="node"&&(i=qn(e,r.schema)),l==="mark"&&(o=fa(e,r.schema));let c=!1;return n.selection.ranges.forEach(d=>{const u=d.$from.pos,p=d.$to.pos;let h,f,g,x;n.selection.empty?r.doc.nodesBetween(u,p,(b,y)=>{i&&i===b.type&&(c=!0,g=Math.max(y,u),x=Math.min(y+b.nodeSize,p),h=y,f=b)}):r.doc.nodesBetween(u,p,(b,y)=>{y<u&&i&&i===b.type&&(c=!0,g=Math.max(y,u),x=Math.min(y+b.nodeSize,p),h=y,f=b),y>=u&&y<=p&&(i&&i===b.type&&(c=!0,s&&n.setNodeMarkup(y,void 0,{...b.attrs,...t})),o&&b.marks.length&&b.marks.forEach(v=>{if(o===v.type&&(c=!0,s)){const C=Math.max(y,u),w=Math.min(y+b.nodeSize,p);n.addMark(C,w,o.create({...v.attrs,...t}))}}))}),f&&(h!==void 0&&s&&n.setNodeMarkup(h,void 0,{...f.attrs,...t}),o&&f.marks.length&&f.marks.forEach(b=>{o===b.type&&s&&n.addMark(g,x,o.create({...b.attrs,...t}))}))}),c},cX=(e,t={})=>({state:n,dispatch:r})=>{const s=qn(e,n.schema);return wQ(s,t)(n,r)},dX=(e,t={})=>({state:n,dispatch:r})=>{const s=qn(e,n.schema);return SQ(s,t)(n,r)},Ym=class{constructor(e){var t;this.find=e.find,this.handler=e.handler,this.undoable=(t=e.undoable)!=null?t:!0}};function uX(e){return Object.prototype.toString.call(e).slice(8,-1)}function fp(e){return uX(e)!=="Object"?!1:e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function sO(e,t){const n={...e};return fp(e)&&fp(t)&&Object.keys(t).forEach(r=>{fp(t[r])&&fp(e[r])?n[r]=sO(e[r],t[r]):n[r]=t[r]}),n}var l0=class{constructor(e={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...e},this.name=this.config.name}get options(){return{...It(st(this,"addOptions",{name:this.name}))}}get storage(){return{...It(st(this,"addStorage",{name:this.name,options:this.options}))}}configure(e={}){const t=this.extend({...this.config,addOptions:()=>sO(this.options,e)});return t.name=this.name,t.parent=this.parent,this.child=null,t}extend(e={}){const t=new this.constructor({...this.config,...e});return t.parent=this,this.child=t,t.name="name"in e?e.name:t.parent.name,t}},Rl=class iO extends l0{constructor(){super(...arguments),this.type="mark"}static create(t={}){const n=typeof t=="function"?t():t;return new iO(n)}static handleExit({editor:t,mark:n}){const{tr:r}=t.state,s=t.state.selection.$from;if(s.pos===s.end()){const o=s.marks();if(!!!o.find(d=>d?.type.name===n.name))return!1;const c=o.find(d=>d?.type.name===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",s.pos),t.view.dispatch(r),!0}return!1}configure(t){return super.configure(t)}extend(t){const n=typeof t=="function"?t():t;return super.extend(n)}},pX=class{constructor(e){this.find=e.find,this.handler=e.handler}},hX={};n0(hX,{ClipboardTextSerializer:()=>fX,Commands:()=>mX,Delete:()=>gX,Drop:()=>xX,Editable:()=>bX,FocusEvents:()=>yX,Keymap:()=>vX,Paste:()=>CX,Tabindex:()=>wX,TextDirection:()=>SX,focusEventsPluginKey:()=>oO});var ln=class aO extends l0{constructor(){super(...arguments),this.type="extension"}static create(t={}){const n=typeof t=="function"?t():t;return new aO(n)}configure(t){return super.configure(t)}extend(t){const n=typeof t=="function"?t():t;return super.extend(n)}},fX=ln.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new pn({key:new hn("clipboardTextSeri
52alizer"),props:{clipboardTextSerializer:()=>{const{editor:e}=this,{state:t,schema:n}=e,{doc:r,selection:s}=t,{ranges:i}=s,o=Math.min(...i.map(u=>u.$from.pos)),l=Math.max(...i.map(u=>u.$to.pos)),c=RJ(n);return MJ(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),mX=ln.create({name:"commands",addCommands(){return{...ss}}}),gX=ln.create({name:"delete",onUpdate({transaction:e,appendedTransactions:t}){var n,r,s;const i=()=>{var o,l,c,d;if((d=(c=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:c.call(l,e))!=null?d:e.getMeta("y-sync$"))return;const u=XN(e.before,[e,...t]);nO(u).forEach(f=>{u.mapping.mapResult(f.oldRange.from).deletedAfter&&u.mapping.mapResult(f.oldRange.to).deletedBefore&&u.before.nodesBetween(f.oldRange.from,f.oldRange.to,(g,x)=>{const b=x+g.nodeSize-2,y=f.oldRange.from<=x&&b<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:g,from:x,to:b,newFrom:u.mapping.map(x),newTo:u.mapping.map(b),deletedRange:f.oldRange,newRange:f.newRange,partial:!y,editor:this.editor,transaction:e,combinedTransform:u})})});const h=u.mapping;u.steps.forEach((f,g)=>{var x,b;if(f instanceof ps){const y=h.slice(g).map(f.from,-1),v=h.slice(g).map(f.to),C=h.invert().map(y,-1),w=h.invert().map(v),S=y>0?(x=u.doc.nodeAt(y-1))==null?void 0:x.marks.some(k=>k.eq(f.mark)):!1,E=(b=u.doc.nodeAt(v))==null?void 0:b.marks.some(k=>k.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:C,to:w},newRange:{from:y,to:v},partial:!!(E||S),editor:this.editor,transaction:e,combinedTransform:u})}})};(s=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||s?setTimeout(i,0):i()}}),xX=ln.create({name:"drop",addProseMirrorPlugins(){return[new pn({key:new hn("tiptapDrop"),props:{handleDrop:(e,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),bX=ln.create({name:"editable",addProseMirrorPlugins(){return[new pn({key:new hn("editable"),props:{editable:()=>this.editor.options.editable}})]}}),oO=new hn("focusEvents"),yX=ln.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:e}=this;return[new pn({key:oO,props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;const r=e.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;const r=e.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),vX=ln.create({name:"keymap",addKeyboardShortcuts(){const e=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:c,doc:d}=l,{empty:u,$anchor:p}=c,{pos:h,parent:f}=p,g=p.parent.isTextblock&&h>0?l.doc.resolve(h-1):p,x=g.parent.type.spec.isolating,b=p.pos-p.parentOffset,y=x&&g.parent.childCount===1?b===p.pos:nt.atStart(d).from===h;return!u||!f.type.isTextblock||f.textContent.length||!y||y&&p.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},s={...r},i={...r,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Vd()||QN()?i:s},addProseMirrorPlugins(){return[new pn({key:new hn("clearDocument"),appendTransaction:(e,t,n)=>{if(e.some(x=>x.getMeta("composition")))return;const r=e.some(x=>x.docChanged)&&!t.doc.eq(n.doc),s=e.some(x=>x.getMeta("preventClearDocument"));if(!r||s)return;const{empty:i,from:o,to:l}=t.selection,c=nt.atStart(t.doc).from,d=nt.atEnd(t.doc).to;
52if(i||!(o===c&&l===d)||!df(n.doc))return;const h=n.tr,f=GN({state:n,transaction:h}),{commands:g}=new k9({editor:this.editor,state:f});if(g.clearNodes(),!!h.steps.length)return h}})]}}),CX=ln.create({name:"paste",addProseMirrorPlugins(){return[new pn({key:new hn("tiptapPaste"),props:{handlePaste:(e,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),wX=ln.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new pn({key:new hn("tabindex"),props:{attributes:()=>{var e;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(e=this.options.value)!=null?e:"0"}}}})]}}),SX=ln.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:e}=Gm(this.extensions);return[{types:e.filter(t=>t.name!=="text").map(t=>t.name),attributes:{dir:{default:this.options.direction,parseHTML:t=>{const n=t.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:t=>t.dir?{dir:t.dir}:{}}}}]},addProseMirrorPlugins(){return[new pn({key:new hn("textDirection"),props:{attributes:()=>{const e=this.options.direction;return e?{dir:e}:{}}}})]}});function cl(e){return new Ym({find:e.find,handler:({state:t,range:n,match:r})=>{const s=It(e.getAttributes,void 0,r);if(s===!1||s===null)return null;const{tr:i}=t,o=r[r.length-1],l=r[0];if(o){const c=l.search(/\S/),d=n.from+l.indexOf(o),u=d+o.length;if(o0(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(x=>x===e.type&&x!==f.mark.type)).filter(f=>f.to>d).length)return null;u<n.to&&i.delete(u,n.to),d>n.from&&i.delete(n.from+c,d);const h=n.from+c+o.length;i.addMark(n.from+c,h,e.type.create(s||{})),i.removeStoredMark(e.type)}},undoable:e.undoable})}function lO(e){return new Ym({find:e.find,handler:({state:t,range:n,match:r})=>{const s=It(e.getAttributes,void 0,r)||{},{tr:i}=t,o=n.from;let l=n.to;const c=e.type.create(s);if(r[1]){const d=r[0].lastIndexOf(r[1]);let u=o+d;u>l?u=l:l=u+r[1].length;const p=r[0][r[0].length-1];i.insertText(p,o+r[0].length-1),i.replaceWith(u,l,c)}else if(r[0]){const d=e.type.isInline?o:o-1;i.insert(d,e.type.create(s)).delete(i.mapping.map(o),i.mapping.map(l))}i.scrollIntoView()},undoable:e.undoable})}function by(e){return new Ym({find:e.find,handler:({state:t,range:n,match:r})=>{const s=t.doc.resolve(n.from),i=It(e.getAttributes,void 0,r)||{};if(!s.node(-1).canReplaceWith(s.index(-1),s.indexAfter(-1),e.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,e.type,i)},undoable:e.undoable})}function dl(e){return new Ym({find:e.find,handler:({state:t,range:n,match:r,chain:s})=>{const i=It(e.getAttributes,void 0,r)||{},o=t.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),d=c&&UC(c,e.type,i);if(!d)return null;if(o.wrap(c,d),e.keepMarks&&e.editor){const{selection:p,storedMarks:h}=t,{splittableMarks:f}=e.editor.extensionManager,g=h||p.$to.parentOffset&&p.$from.marks();if(g){const x=g.filter(b=>f.includes(b.type.name));o.ensureMarks(x)}}if(e.keepAttributes){const p=e.type.name==="bulletList"||e.type.name==="orderedList"?"listItem":"taskList";s().updateAttributes(p,i).run()}const u=o.doc.resolve(n.from-1).nodeBefore;u&&u.type===e.type&&pa(o.doc,n.from-1)&&(!e.joinPredicate||e.joinPredicate(r,u))&&o.join(n.from-1)},undoable:e.undoable})}var jX=e=>"touches"in e,kX=class{constructor(e){this.directions=["bottom-left","bottom-right","top-left","top-right"],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:"",wrapper:"",handle:"",resizing:""},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.clientX-this.startX,d=l.clientY-this.startY;this.handleResize(c,d)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.touches[0];if(!c)return;const d=c.clientX-this.startX,u=c.clientY-this.startY;this.handleResize(d,u)},this.handleMouseUp=()=>
52{if(!this.isResizing)return;const l=this.element.offsetWidth,c=this.element.offsetHeight;this.onCommit(l,c),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)},this.handleKeyDown=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!1)};var t,n,r,s,i,o;this.node=e.node,this.editor=e.editor,this.element=e.element,this.contentElement=e.contentElement,this.getPos=e.getPos,this.onResize=e.onResize,this.onCommit=e.onCommit,this.onUpdate=e.onUpdate,(t=e.options)!=null&&t.min&&(this.minSize={...this.minSize,...e.options.min}),(n=e.options)!=null&&n.max&&(this.maxSize=e.options.max),(r=e?.options)!=null&&r.directions&&(this.directions=e.options.directions),(s=e.options)!=null&&s.preserveAspectRatio&&(this.preserveAspectRatio=e.options.preserveAspectRatio),(i=e.options)!=null&&i.className&&(this.classNames={container:e.options.className.container||"",wrapper:e.options.className.wrapper||"",handle:e.options.className.handle||"",resizing:e.options.className.resizing||""}),(o=e.options)!=null&&o.createCustomHandle&&(this.createCustomHandle=e.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on("update",this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var e;return(e=this.contentElement)!=null?e:null}handleEditorUpdate(){const e=this.editor.isEditable;e!==this.lastEditableState&&(this.lastEditableState=e,e?e&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}update(e,t,n){return e.type!==this.node.type?!1:(this.node=e,this.onUpdate?this.onUpdate(e,t,n):!0)}destroy(){this.isResizing&&(this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.editor.off("update",this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){const e=document.createElement("div");return e.dataset.resizeContainer="",e.dataset.node=this.node.type.name,e.style.display=this.node.type.isInline?"inline-flex":"flex",this.classNames.container&&(e.className=this.classNames.container),e.appendChild(this.wrapper),e}createWrapper(){const e=document.createElement("div");return e.style.position="relative",e.style.display="block",e.dataset.resizeWrapper="",this.classNames.wrapper&&(e.className=this.classNames.wrapper),e.appendChild(this.element),e}createHandle(e){const t=document.createElement("div");return t.dataset.resizeHandle=e,t.style.position="absolute",this.classNames.handle&&(t.className=this.classNames.handle),t}positionHandle(e,t){const n=t.includes("top"),r=t.includes("bottom"),s=t.includes("left"),i=t.includes("right");n&&(e.style.top="0"),r&&(e.style.bottom="0"),s&&(e.style.left="0"),i&&(e.style.right="0"),(t==="top"||t==="bottom")&&(e.style.left="0",e.style.right="0"),(t==="left"||t==="right")&&(e.style.top="0",e.style.bottom="0")}attachHandles(){this.directions.forEach(e=>{let t;this.createCustomHandle?t=this.createCustomHandle(e):t=this.createHandle(e),t instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${e}") did not return an HTMLElement. Falling back to default handle.`),t=this.createHandle(e)),this.createCustomHandle||this.positionHandle(t,e),t.addEventListener("mousedown",n=>this.handleResizeStart(n,e)),t.addEventListener("touchstart",n=>this.handleResizeStart(n,e)),this.handleMap.set(e,t),this.wrapper.appendChild(t)})}
52removeHandles(){this.handleMap.forEach(e=>e.remove()),this.handleMap.clear()}applyInitialSize(){const e=this.node.attrs.width,t=this.node.attrs.height;e?(this.element.style.width=`${e}px`,this.initialWidth=e):this.initialWidth=this.element.offsetWidth,t?(this.element.style.height=`${t}px`,this.initialHeight=t):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(e,t){e.preventDefault(),e.stopPropagation(),this.isResizing=!0,this.activeHandle=t,jX(e)?(this.startX=e.touches[0].clientX,this.startY=e.touches[0].clientY):(this.startX=e.clientX,this.startY=e.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState="true",this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}handleResize(e,t){if(!this.activeHandle)return;const n=this.preserveAspectRatio||this.isShiftKeyPressed,{width:r,height:s}=this.calculateNewDimensions(this.activeHandle,e,t),i=this.applyConstraints(r,s,n);this.element.style.width=`${i.width}px`,this.element.style.height=`${i.height}px`,this.onResize&&this.onResize(i.width,i.height)}calculateNewDimensions(e,t,n){let r=this.startWidth,s=this.startHeight;const i=e.includes("right"),o=e.includes("left"),l=e.includes("bottom"),c=e.includes("top");return i?r=this.startWidth+t:o&&(r=this.startWidth-t),l?s=this.startHeight+n:c&&(s=this.startHeight-n),(e==="right"||e==="left")&&(r=this.startWidth+(i?t:-t)),(e==="top"||e==="bottom")&&(s=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,s,e):{width:r,height:s}}applyConstraints(e,t,n){var r,s,i,o;if(!n){let d=Math.max(this.minSize.width,e),u=Math.max(this.minSize.height,t);return(r=this.maxSize)!=null&&r.width&&(d=Math.min(this.maxSize.width,d)),(s=this.maxSize)!=null&&s.height&&(u=Math.min(this.maxSize.height,u)),{width:d,height:u}}let l=e,c=t;return l<this.minSize.width&&(l=this.minSize.width,c=l/this.aspectRatio),c<this.minSize.height&&(c=this.minSize.height,l=c*this.aspectRatio),(i=this.maxSize)!=null&&i.width&&l>this.maxSize.width&&(l=this.maxSize.width,c=l/this.aspectRatio),(o=this.maxSize)!=null&&o.height&&c>this.maxSize.height&&(c=this.maxSize.height,l=c*this.aspectRatio),{width:l,height:c}}applyAspectRatio(e,t,n){const r=n==="left"||n==="right",s=n==="top"||n==="bottom";return r?{width:e,height:e/this.aspectRatio}:s?{width:t*this.aspectRatio,height:t}:{width:e,height:e/this.aspectRatio}}};function EX(e,t){const{selection:n}=e,{$from:r}=n;if(n instanceof Ye){const i=r.index();return r.parent.canReplaceWith(i,i+1,t)}let s=r.depth;for(;s>=0;){const i=r.index(s);if(r.node(s).contentMatchAt(i).matchType(t))return!0;s-=1}return!1}function _X(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}function T1(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&/g,"&")}function TX(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var IX={};n0(IX,{createAtomBlockMarkdownSpec:()=>DX,createBlockMarkdownSpec:()=>AX,createInlineMarkdownSpec:()=>NX,parseAttributes:()=>c0,parseIndentedBlocks:()=>yy,renderNestedMarkdownContent:()=>u0,serializeAttributes:()=>d0});function c0(e){if(!e?.trim())return{};const t={},n=[],r=e.replace(/["']([^"']*)["']/g,d=>(n.push(d),`__QUOTED_${n.length-1}__`)),s=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(s){const d=s.map(u=>u.trim().slice(1));t.class=d.join(" ")}const i=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);i&&(t.id=i[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,d,u])=>{var p;const h=parseInt(((p=u.match(/__QUOTED_(\d+)__/))==null?void 0:p[1])||"0",10),f=n[h];
52f&&(t[d]=f.slice(1,-1))});const c=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(t[u]=!0)}),t}function d0(e){if(!e||Object.keys(e).length===0)return"";const t=[];return e.class&&String(e.class).split(/\s+/).filter(Boolean).forEach(r=>t.push(`.${r}`)),e.id&&t.push(`#${e.id}`),Object.entries(e).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?t.push(n):r!==!1&&r!=null&&t.push(`${n}="${String(r)}"`))}),t.join(" ")}function DX(e){const{nodeName:t,name:n,parseAttributes:r=c0,serializeAttributes:s=d0,defaultAttributes:i={},requiredAttributes:o=[],allowedAttributes:l}=e,c=n||t,d=u=>{if(!l)return u;const p={};return l.forEach(h=>{h in u&&(p[h]=u[h])}),p};return{parseMarkdown:(u,p)=>{const h={...i,...u.attributes};return p.createNode(t,h,[])},markdownTokenizer:{name:t,level:"block",start(u){var p;const h=new RegExp(`^:::${c}(?:\\s|$)`,"m"),f=(p=u.match(h))==null?void 0:p.index;return f!==void 0?f:-1},tokenize(u,p,h){const f=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),g=u.match(f);if(!g)return;const x=g[1]||"",b=r(x);if(!o.find(v=>!(v in b)))return{type:t,raw:g[0],attributes:b}}},renderMarkdown:u=>{const p=d(u.attrs||{}),h=s(p),f=h?` {${h}}`:"";return`:::${c}${f} :::`}}}function AX(e){const{nodeName:t,name:n,getContent:r,parseAttributes:s=c0,serializeAttributes:i=d0,defaultAttributes:o={},content:l="block",allowedAttributes:c}=e,d=n||t,u=p=>{if(!c)return p;const h={};return c.forEach(f=>{f in p&&(h[f]=p[f])}),h};return{parseMarkdown:(p,h)=>{let f;if(r){const x=r(p);f=typeof x=="string"?[{type:"text",text:x}]:x}else l==="block"?f=h.parseChildren(p.tokens||[]):f=h.parseInline(p.tokens||[]);const g={...o,...p.attributes};return h.createNode(t,g,f)},markdownTokenizer:{name:t,level:"block",start(p){var h;const f=new RegExp(`^:::${d}`,"m"),g=(h=p.match(f))==null?void 0:h.index;return g!==void 0?g:-1},tokenize(p,h,f){var g;const x=new RegExp(`^:::${d}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),b=p.match(x);if(!b)return;const[y,v=""]=b,C=s(v);let w=1;const S=y.length;let E="";const k=/^:::([\w-]*)(\s.*)?/gm,j=p.slice(S);for(k.lastIndex=0;;){const _=k.exec(j);if(_===null)break;const D=_.index,M=_[1];if(!((g=_[2])!=null&&g.endsWith(":::"))){if(M)w+=1;else if(w-=1,w===0){const N=j.slice(0,D);E=N.trim();const O=p.slice(0,S+D+_[0].length);let R=[];if(E)if(l==="block")for(R=f.blockTokens(N),R.forEach(L=>{L.text&&(!L.tokens||L.tokens.length===0)&&(L.tokens=f.inlineTokens(L.text))});R.length>0;){const L=R[R.length-1];if(L.type==="paragraph"&&(!L.text||L.text.trim()===""))R.pop();else break}else R=f.inlineTokens(E);return{type:t,raw:O,attributes:C,content:E,tokens:R}}}}}},renderMarkdown:(p,h)=>{const f=u(p.attrs||{}),g=i(f),x=g?` {${g}}`:"",b=h.renderChildren(p.content||[],` 53 54`);return`:::${d}${x} 55 56${b} 57 58:::`}}}function MX(e){if(!e.trim())return{};const t={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(e);for(;r!==null;){const[,s,i,o]=r;t[s]=i||o,r=n.exec(e)}return t}function RX(e){return Object.entries(e).filter(([,t])=>t!=null).map(([t,n])=>`${t}="${n}"`).join(" ")}function NX(e){const{nodeName:t,name:n,getContent:r,parseAttributes:s=MX,serializeAttributes:i=RX,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=e,d=n||t,u=h=>{if(!c)return h;const f={};return c.forEach(g=>{const x=typeof g=="string"?g:g.name,b=typeof g=="string"?void 0:g.skipIfDefault;if(x in h){const y=h[x];if(b!==void 0&&y===b)return;f[x]=y}}),f},p=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,f)=>{const g={...o,...h.attributes};if(l)return f.createNode(t,g);const x=r?r(h):h.content||"";return x?f.createNode(t,g,[f.createTextNode(x)]):f.createNode(t,g,[])},markdownTokenizer:{name:t,level:"inline",start(h){const f=l?new RegExp(`\\[${p}\\s*[^\\]]*\\]`):new RegExp(`\\[${p}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${p}\\]`),g=h.match(f),x=g?.index;return x!==void 0?x:-1},tokenize(h,f,g){const x=l?new RegExp(`^\\[${p}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${p}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${p}\\]`),b=h.match(x);if(!b)return;let y="",v="";if(l){const[,w]=b;v=w}else{const[,w,S]=b;v=w,y=S||""}const C=s(v.trim());return{type:t,raw:b[0],content:y.trim(),attributes:C}}},renderMarkdown:h=>{let f="";r?f=r(h):h.content&&h.content.length>0&&(f=h.content.filter(y=>y.type==="text").map(y=>y.text).join(""));const g=u(h.attrs||{}),x=i(g),b=x?` ${x}`:"";return l?`[${d}${b}]`:`[${d}${b}]${f}[/${d}]`}}}function yy(e,t,n){var r,s,i,o;const l=e.split(` 59`),c=[];let d="",u=0;const p=t.baseIndentSize||2;for(;u<l.length;){const h=l[u],f=h.match(t.itemPattern);if(!f){if(c.length>0)break;if(h.trim()===""){u+=1,d=`${d}${h} 60`;continue}else return}const g=t.extractItemData(f),{indentLevel:x,mainContent:b}=g;d=`${d}${h} 61`;const y=[b];for(u+=1;u<l.length;){const S=l[u];if(S.trim()===""){const k=l.slice(u+1).findIndex(D=>D.trim()!=="");if(k===-1)break;if((((s=(r=l[u+1+k].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:s.length)||0)>x){y.push(S),d=`${d}${S} 62`,u+=1;continue}else break}if((((o=(i=S.match(/^(\s*)/))==null?void 0:i[1])==null?void 0:o.length)||0)>x)y.push(S),d=`${d}${S} 63`,u+=1;else break}let v;const C=y.slice(1);if(C.length>0){const S=C.map(E=>E.slice(x+p)).join(` 64`);S.trim()&&(t.customNestedParser?v=t.customNestedParser(S):v=n.blockTokens(S))}const w=t.createToken(g,v);c.push(w)}if(c.length!==0)return{items:c,raw:d}}function u0(e,t,n,r){if(!e||!Array.isArray(e.content))return"";const s=typeof n=="function"?n(r):n,[i,...o]=e.content,l=t.renderChildren([i]);let c=`${s}${l}`;return o&&o.length>0&&o.forEach((d,u)=>{var p,h;const f=(h=(p=t.renderChild)==null?void 0:p.call(t,d,u+1))!=null?h:t.renderChildren([d]);if(f!=null){const g=f.split(` 65`).map(x=>x?t.indent(x):t.indent("")).join(` 66`);c+=d.type==="paragraph"?` 67 68${g}`:` 69${g}`}}),c}var Gn=class cO extends l0{constructor(){super(...arguments),this.type="node"}static create(t={}){const n=typeof t=="function"?t():t;return new cO(n)}configure(t){return super.configure(t)}extend(t){const n=typeof t=="function"?t():t;return super.extend(n)}},OX=class{constructor(e,t,n){this.isDragging=!1,this.component=e,this.editor=t.editor,this.options={stopEvent:null,ignoreMutation:null,...n},this.extension=t.extension,this.node=t.node,this.decorations=t.decorations,this.innerDecorations=t.innerDecorations,this.view=t.view,this.HTMLAttributes=t.HTMLAttributes,this.getPos=t.getPos,this.mount()}mount(){}get dom(){return this.editor.view.dom}get contentDOM(){return null}onDragStart(e){var t,n,r,s,i,o,l;const{view:c}=this.editor,d=e.target,u=d.nodeType===3?(t=d.parentElement)==null?void 0:t.closest("[data-drag-handle]"):d.closest("[data-drag-handle]");if(!this.dom||(n=this.contentDOM)!=null&&n.contains(d)||!u)return;let p=0,h=0;if(this.dom!==u){const v=this.dom.getBoundingClientRect(),C=u.getBoundingClientRect(),w=(s=e.offsetX)!=null?s:(r=e.nativeEvent)==null?void 0:r.offsetX,S=(o=e.offsetY)!=null?o:(i=e.nativeEvent)==null?void 0:i.offsetY;p=C.x-v.x+w,h=C.y-v.y+S}const f=this.dom.cloneNode(!0);try{const v=this.dom.getBoundingClientRect();f.style.width=`${Math.round(v.width)}px`,f.style.height=`${Math.round(v.height)}px`,f.style.boxSizing="border-box",f.style.pointerEvents="none"}catch{}let g=null;try{g=document.createElement("div"),g.style.position="absolute",g.style.top="-9999px",g.style.left="-9999px",g.style.pointerEvents="none",g.appendChild(f),document.body.appendChild(g),(l=e.dataTransfer)==null||l.setDragImage(f,p,h)}finally{g&&setTimeout(()=>{try{g?.remove()}catch{}},0)}const x=this.getPos();if(typeof x!="number")return;const b=Ye.create(c.state.doc,x),y=c.state.tr.setSelection(b);c.dispatch(y)}stopEvent(e){var t;if(!this.dom)return!1;if(typeof this.options.stopEvent=="function")return this.options.stopEvent({event:e});const n=e.target;if(!(this.dom.contains(n)&&!((t=this.contentDOM)!=null&&t.contains(n))))return!1;const s=e.type.startsWith("drag"),i=e.type==="dragover"||e.type==="dragenter",o=e.type==="drop";if((["INPUT","BUTTON","SELECT","TEXTAREA"].includes(n.tagName)||n.isContentEditable)&&!o&&!s)return!0;const{isEditable:c}=this.editor,{isDragging:d}=this,u=!!this.node.type.spec.draggable,p=Ye.isSelectable(this.node),h=e.type==="copy",f=e.type==="paste",g=e.type==="cut",x=e.type==="mousedown";if(!u&&p&&s&&e.target===this.dom&&e.preventDefault(),u&&s&&!d&&e.target===this.dom)return e.preventDefault(),!1;if(u&&c&&!d&&x){const b=n.closest("[data-drag-handle]");b&&(this.dom===b||this.dom.contains(b))&&(this.isDragging=!0,document.addEventListener("dragend",()=>{this.isDragging=!1},{once:!0}),document.addEventListener("drop",()=>{this.isDragging=!1},{once:!0}),document.addEventListener("mouseup",()=>{this.isDragging=!1},{once:!0}))}return!(d||i||o||h||f||g||x&&p)}ignoreMutation(e){return!this.dom||!this.contentDOM?!0:typeof this.options.ignoreMutation=="function"?this.options.ignoreMutation({mutation:e}):this.node.isLeaf||this.node.isAtom?!0:e.type==="selection"||this.dom.contains(e.target)&&e.type==="childList"&&(Vd()||xy())&&this.editor.isFocused&&[...Array.from(e.addedNodes),...Array.from(e.removedNodes
69)].every(n=>n.isContentEditable)?!1:this.contentDOM===e.target&&e.type==="attributes"?!0:!this.contentDOM.contains(e.target)}updateAttributes(e){this.editor.commands.command(({tr:t})=>{const n=this.getPos();return typeof n!="number"?!1:(t.setNodeMarkup(n,void 0,{...this.node.attrs,...e}),!0)})}deleteNode(){const e=this.getPos();if(typeof e!="number")return;const t=e+this.node.nodeSize;this.editor.commands.deleteRange({from:e,to:t})}};function ro(e){return new pX({find:e.find,handler:({state:t,range:n,match:r,pasteEvent:s})=>{const i=It(e.getAttributes,void 0,r,s);if(i===!1||i===null)return null;const{tr:o}=t,l=r[r.length-1],c=r[0];let d=n.to;if(l){const u=c.search(/\S/),p=n.from+c.indexOf(l),h=p+l.length;if(o0(n.from,n.to,t.doc).filter(x=>x.mark.type.excluded.find(y=>y===e.type&&y!==x.mark.type)).filter(x=>x.to>p).length)return null;h<n.to&&o.delete(h,n.to),p>n.from&&o.delete(n.from+u,p),d=n.from+u+l.length,o.addMark(n.from+u,d,e.type.create(i||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(e.type)}}})}var PX=(...e)=>t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},LX=({contentComponent:e})=>{const t=$5.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getServerSnapshot);return a.jsx(a.Fragment,{children:Object.values(t)})};function FX(){const e=new Set;let t={};return{subscribe(n){return e.add(n),()=>{e.delete(n)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(n,r){t={...t,[n]:TD.createPortal(r.reactElement,r.element,n)},e.forEach(s=>s())},removeRenderer(n){const r={...t};delete r[n],t=r,e.forEach(s=>s())}}}var $X=class extends Ne.Component{constructor(e){super(e),this.editorContentRef=Ne.createRef()}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var e;const t=this.props.editor;if(t&&!t.isDestroyed&&((e=t.view.dom)!=null&&e.parentNode)){if(t.contentComponent)return;const n=this.editorContentRef.current;n.append(...t.view.dom.parentNode.childNodes),t.setOptions({element:n}),t.contentComponent=FX(),t.createNodeViews(),t.isEditorContentInitialized=!0,this.forceUpdate()}}componentWillUnmount(){var e;const t=this.props.editor;if(t){t.isEditorContentInitialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),t.contentComponent=null;try{if(!((e=t.view.dom)!=null&&e.parentNode))return;const n=document.createElement("div");n.append(...t.view.dom.parentNode.childNodes),t.setOptions({element:n})}catch{}}}render(){const{editor:e,innerRef:t,...n}=this.props;return a.jsxs(a.Fragment,{children:[a.jsx("div",{ref:PX(t,this.editorContentRef),...n}),e?.contentComponent&&a.jsx(LX,{contentComponent:e.contentComponent})]})}},zX=m.forwardRef((e,t)=>{const n=Ne.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[e.editor]);return Ne.createElement($X,{key:n,innerRef:t,...e})}),BX=Ne.memo(zX),dO=m.createContext({editor:null});dO.Consumer;var uO=m.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),UX=()=>m.useContext(uO),VX=Ne.forwardRef((e,t)=>{const{onDragStart:n}=UX(),r=e.as||"div";return a.jsx(r,{...e,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...e.style}})});function I1(e){return!!(typeof e=="function"&&e.prototype&&e.prototype.isReactComponent)}function D1(e){return!!(typeof e=="object"&&e.$$typeof&&(e.$$typeof.toString()==="Symbol(react.forward_ref)"||e.$$typeof.description==="react.forward_ref"))}function WX(e){return!!(typeof e=="object"&&e.$$typeof&&(e.$$typeof.toString()==="Symbol(react.memo)"||e.$$typeof.description==="react.memo"))}function HX(e){if(I1(e)||D1(e))return!0;if(WX(e)){const t=e.type;if(t)return I1(t)||D1(t)}return!1}function qX(){try{if(m.version)return parseInt(m.version.split(".")[0],10)>=19}catch{}return!1}var pO=class{constructor(e,{editor:t,props:n={},as:r="div",className:s=""}){this.ref=null,this.destroyed=!1,this.id=Math.floor(Math.random()*4294967295).toString(),this.component=e,this.editor=t,this.props=n,this.element=document.createElement(r),this.element.classList.add("react-renderer"),s&&this.element.classList.add(...s.split(" ")),this.editor.isEditorContentInitialized?jD.flushSync(()=>{this.render()}):queueMicrotask(()=>{this.destroyed||this.render()})}render(){var e;if(this.destroyed)return;const t=this.component,n=this.props,r=this.editor,s=qX(),i=HX(t),o={...n};o.ref&&!(s||i)&&delete o.ref,!o.ref&&(s||i)&&(o.ref=l=>{this.ref=l}),this.reactElement=a.jsx(t,{...o}),(e=r?.contentComponent)==null||e.setRenderer(this.id,this)}updateProps(e={}){if(this.destroyed)return;let t=!1;const n=Object.keys(e);for(let r=0;r<n.length;r+=1){const s=n[r];if(e[s]!==this.props[s]){t=!0;break}}t&&(this.props={...this.props,...e},this.render())}destroy(){var e;this.destroyed=!0;const t=this.editor;
69(e=t?.contentComponent)==null||e.removeRenderer(this.id);try{this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}catch{}}updateAttributes(e){Object.keys(e).forEach(t=>{this.element.setAttribute(t,e[t])})}};Ne.createContext({markViewContentRef:()=>{}});var GX=class extends OX{constructor(e,t,n){if(super(e,t,n),this.selectionRafId=null,this.handlePositionUpdate=()=>{const r=this.getPos();typeof r!="number"||r===this.currentPos||(this.currentPos=r,this.renderer.updateProps({getPos:()=>this.getPos()}),typeof this.options.attrs=="function"&&this.updateElementAttributes())},this.cachedExtensionWithSyncedStorage=null,!this.node.isLeaf){this.options.contentDOMElementTag?this.contentDOMElement=document.createElement(this.options.contentDOMElementTag):this.contentDOMElement=document.createElement(this.node.isInline?"span":"div"),this.contentDOMElement.dataset.nodeViewContentReact="",this.contentDOMElement.dataset.nodeViewWrapper="",this.contentDOMElement.style.whiteSpace="inherit";const r=this.dom.querySelector("[data-node-view-content]");if(!r)return;r.appendChild(this.contentDOMElement)}this.options.trackNodeViewPosition&&this.editor.on("update",this.handlePositionUpdate)}get extensionWithSyncedStorage(){if(!this.cachedExtensionWithSyncedStorage){const e=this.editor,t=this.extension;this.cachedExtensionWithSyncedStorage=new Proxy(t,{get(n,r,s){var i;return r==="storage"?(i=e.storage[t.name])!=null?i:{}:Reflect.get(n,r,s)}})}return this.cachedExtensionWithSyncedStorage}mount(){const t={editor:this.editor,node:this.node,decorations:this.decorations,innerDecorations:this.innerDecorations,view:this.view,selected:!1,extension:this.extensionWithSyncedStorage,HTMLAttributes:this.HTMLAttributes,getPos:()=>this.getPos(),updateAttributes:(d={})=>this.updateAttributes(d),deleteNode:()=>this.deleteNode(),ref:m.createRef()};if(!this.component.displayName){const d=u=>u.charAt(0).toUpperCase()+u.substring(1);this.component.displayName=d(this.extension.name)}const s={onDragStart:this.onDragStart.bind(this),nodeViewContentRef:d=>{d&&this.contentDOMElement&&d.firstChild!==this.contentDOMElement&&(d.hasAttribute("data-node-view-wrapper")&&d.removeAttribute("data-node-view-wrapper"),d.appendChild(this.contentDOMElement))}},i=this.component,o=m.memo(d=>a.jsx(uO.Provider,{value:s,children:m.createElement(i,d)}));o.displayName="ReactNodeView";let l=this.node.isInline?"span":"div";this.options.as&&(l=this.options.as);const{className:c=""}=this.options;this.handleSelectionUpdate=this.handleSelectionUpdate.bind(this),this.renderer=new pO(o,{editor:this.editor,props:t,as:l,className:`node-${this.node.type.name} ${c}`.trim()}),this.editor.on("selectionUpdate",this.handleSelectionUpdate),this.updateElementAttributes(),this.currentPos=this.getPos()}get dom(){var e;if(this.renderer.element.firstElementChild&&!((e=this.renderer.element.firstElementChild)!=null&&e.hasAttribute("data-node-view-wrapper")))throw Error("Please use the NodeViewWrapper component for your node view.");return this.renderer.element}get contentDOM(){return this.node.isLeaf?null:this.contentDOMElement}handleSelectionUpdate(){this.selectionRafId&&(cancelAnimationFrame(this.selectionRafId),this.selectionRafId=null),this.selectionRafId=requestAnimationFrame(()=>{this.selectionRafId=null;const e=this.currentPos;if(typeof e!="number")return;if(UJ({selection:this.editor.state.selection,pos:e,nodeSize:this.node.nodeSize,selectedOnTextSelection:this.options.selectedOnTextSelection})){if(this.renderer.props.selected)return;this.selectNode()}else{if(!this.renderer.props.selected)return;this.deselectNode()}})}update(e,t,n){const r=l=>{this.renderer.updateProps(l),typeof this.options.attrs=="function"&&this.updateElementAttributes()};if(e.type!==this.node.type)return!1;if(typeof this.options.update=="function"){const l=this.node,c=this.decorations,d=this.innerDecorations;return this.node=e,this.decorations=t,this.innerDecorations=n,this.currentPos=this.getPos(),this.options.update({oldNode:l,oldDecorations:c,newNode:e,newDecorations:t,oldInnerDecorations:d,innerDecorations:n,updateProps:()=>r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage})})}if(!(e!==this.node))return this.node=e,this.decorations=t,this.innerDecorations=n,!0;const i=this.getPos();this.node=e,this.decorations=t,this.innerDecorations=n,this.currentPos=i;const o={node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage};return this.options.trackNodeViewPosition&&(o.getPos=()=>this.getPos()),r(o),!0}selectNode(){this.renderer.updateProps({selected:!0}),this.renderer.element.classList.add("ProseMirror-selectednode")}deselectNode(){this.renderer.updateProps({selected:!1}),this.renderer.element.classList.remove("ProseMirror-selectednode")}destroy(){this.renderer.destroy(),this.editor.off("selectionUpdate",this.handleSelectionUpdate),this.options.trackNodeViewPosition&&this.editor.off("update",this.handlePositionUpdate),this.contentDOMElement=null,this.selectionRafId&&(cancelAnimationFrame(this.selectionRafId),this.selectionRafId=null)}updateElementAttributes(){if(this.options.attrs){let e={};if(typeof this.options.attrs=="function"){const t=this.editor.extensionManager.attributes,n=cf(this.node,t);e=this.options.attrs({node:this.node,HTMLAttributes:n}
69)}else e=this.options.attrs;this.renderer.updateAttributes(e)}}};function YX(e,t){return n=>n.editor.contentComponent?new GX(e,n,t):{}}var p0=m.createContext({get editor(){throw new Error("useTiptap must be used within a <Tiptap> provider")}});p0.displayName="TiptapContext";var KX=()=>m.useContext(p0);function hO({editor:e,instance:t,children:n}){const r=e??t;if(!r)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const s=m.useMemo(()=>({editor:r}),[r]),i=m.useMemo(()=>({editor:r}),[r]);return a.jsx(dO.Provider,{value:i,children:a.jsx(p0.Provider,{value:s,children:n})})}hO.displayName="Tiptap";function fO({...e}){const{editor:t}=KX();return a.jsx(BX,{editor:t,...e})}fO.displayName="Tiptap.Content";Object.assign(hO,{Content:fO});let vy,Cy;if(typeof WeakMap<"u"){let e=new WeakMap;vy=t=>e.get(t),Cy=(t,n)=>(e.set(t,n),n)}else{const e=[];let n=0;vy=r=>{for(let s=0;s<e.length;s+=2)if(e[s]==r)return e[s+1]},Cy=(r,s)=>(n==10&&(n=0),e[n++]=r,e[n++]=s)}var En=class{constructor(e,t,n,r){this.width=e,this.height=t,this.map=n,this.problems=r}findCell(e){for(let t=0;t<this.map.length;t++){const n=this.map[t];if(n!=e)continue;const r=t%this.width,s=t/this.width|0;let i=r+1,o=s+1;for(let l=1;i<this.width&&this.map[t+l]==n;l++)i++;for(let l=1;o<this.height&&this.map[t+this.width*l]==n;l++)o++;return{left:r,top:s,right:i,bottom:o}}throw new RangeError(`No cell with offset ${e} found`)}colCount(e){for(let t=0;t<this.map.length;t++)if(this.map[t]==e)return t%this.width;throw new RangeError(`No cell with offset ${e} found`)}nextCell(e,t,n){const{left:r,right:s,top:i,bottom:o}=this.findCell(e);return t=="horiz"?(n<0?r==0:s==this.width)?null:this.map[i*this.width+(n<0?r-1:s)]:(n<0?i==0:o==this.height)?null:this.map[r+this.width*(n<0?i-1:o)]}rectBetween(e,t){const{left:n,right:r,top:s,bottom:i}=this.findCell(e),{left:o,right:l,top:c,bottom:d}=this.findCell(t);return{left:Math.min(n,o),top:Math.min(s,c),right:Math.max(r,l),bottom:Math.max(i,d)}}cellsInRect(e){const t=[],n={};for(let r=e.top;r<e.bottom;r++)for(let s=e.left;s<e.right;s++){const i=r*this.width+s,o=this.map[i];n[o]||(n[o]=!0,!(s==e.left&&s&&this.map[i-1]==o||r==e.top&&r&&this.map[i-this.width]==o)&&t.push(o))}return t}positionAt(e,t,n){for(let r=0,s=0;;r++){const i=s+n.child(r).nodeSize;if(r==e){let o=t+e*this.width;const l=(e+1)*this.width;for(;o<l&&this.map[o]<s;)o++;return o==l?i-1:this.map[o]}s=i}}static get(e){return vy(e)||Cy(e,QX(e))}};function QX(e){if(e.type.spec.tableRole!="table")throw new RangeError("Not a table node: "+e.type.name);const t=JX(e),n=e.childCount,r=[];let s=0,i=null;const o=[];for(let d=0,u=t*n;d<u;d++)r[d]=0;for(let d=0,u=0;d<n;d++){const p=e.child(d);u++;for(let g=0;;g++){for(;s<r.length&&r[s]!=0;)s++;if(g==p.childCount)break;const x=p.child(g),{colspan:b,rowspan:y,colwidth:v}=x.attrs;for(let C=0;C<y;C++){if(C+d>=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:y-C});break}const w=s+C*t;for(let S=0;S<b;S++){r[w+S]==0?r[w+S]=u:(i||(i=[])).push({type:"collision",row:d,pos:u,n:b-S});const E=v&&v[S];if(E){const k=(w+S)%t*2,j=o[k];j==null||j!=E&&o[k+1]==1?(o[k]=E,o[k+1]=1):j==E&&o[k+1]++}}}s+=b,u+=x.nodeSize}const h=(d+1)*t;let f=0;for(;s<h;)r[s++]==0&&f++;f&&(i||(i=[])).push({type:"missing",row:d,n:f}),u++}(t===0||n===0)&&(i||(i=[])).push({type:"zero_sized"});const l=new En(t,n,r,i);let c=!1;for(let d=0;!c&&d<o.length;d+=2)o[d]!=null&&o[d+1]<n&&(c=!0);return c&&XX(l,o,e),l}function JX(e){let t=-1,n=!1;for(let r=0;r<e.childCount;r++){const s=e.child(r);let i=0;if(n)for(let o=0;o<r;o++){const l=e.child(o);for(let c=0;c<l.childCount;c++){const d=l.child(c);o+d.attrs.rowspan>r&&(i+=d.attrs.colspan)}}for(let o=0;o<s.childCount;o++){const l=s.child(o);i+=l.attrs.colspan,l.attrs.rowspan>1&&(n=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function XX(e,t,n){e.problems||(e.problems=[]);const r={};for(let s=0;s<e.map.length;s++){const i=e.map[s];if(r[i])continue;r[i]=!0;const o=n.nodeAt(i);if(!o)throw new RangeError(`No cell with offset ${i} found`);let l=null;const c=o.attrs;for(let d=0;d<c.colspan;d++){const u=t[(s+d)%e.width*2];u!=null&&(!c.colwidth||c.colwidth[d]!=u)&&((l||(l=ZX(c)))[d]=u)}l&&e.problems.unshift({type:"colwidth mismatch",pos:i,colwidth:l})}}function ZX(e){if(e.colwidth)return e.colwidth.slice();const t=[];for(let n=0;n<e.colspan;n++)t.push(0);return t}function cr(e){let t=e.cached.tableNodeTypes;
69if(!t){t=e.cached.tableNodeTypes={};for(const n in e.nodes){const r=e.nodes[n],s=r.spec.tableRole;s&&(t[s]=r)}}return t}const Bi=new hn("selectingCells");function so(e){for(let t=e.depth-1;t>0;t--)if(e.node(t).type.spec.tableRole=="row")return e.node(0).resolve(e.before(t+1));return null}function eZ(e){for(let t=e.depth;t>0;t--){const n=e.node(t).type.spec.tableRole;if(n==="cell"||n==="header_cell")return e.node(t)}return null}function Ss(e){const t=e.selection.$head;for(let n=t.depth;n>0;n--)if(t.node(n).type.spec.tableRole=="row")return!0;return!1}function Km(e){const t=e.selection;if("$anchorCell"in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if("node"in t&&t.node&&t.node.type.spec.tableRole=="cell")return t.$anchor;const n=so(t.$head)||tZ(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function tZ(e){for(let t=e.nodeAfter,n=e.pos;t;t=t.firstChild,n++){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return e.doc.resolve(n)}for(let t=e.nodeBefore,n=e.pos;t;t=t.lastChild,n--){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return e.doc.resolve(n-t.nodeSize)}}function wy(e){return e.parent.type.spec.tableRole=="row"&&!!e.nodeAfter}function nZ(e){return e.node(0).resolve(e.pos+e.nodeAfter.nodeSize)}function h0(e,t){return e.depth==t.depth&&e.pos>=t.start(-1)&&e.pos<=t.end(-1)}function mO(e,t,n){const r=e.node(-1),s=En.get(r),i=e.start(-1),o=s.nextCell(e.pos-i,t,n);return o==null?null:e.node(0).resolve(i+o)}function io(e,t,n=1){const r={...e,colspan:e.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(t,n),r.colwidth.some(s=>s>0)||(r.colwidth=null)),r}function gO(e,t,n=1){const r={...e,colspan:e.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let s=0;s<n;s++)r.colwidth.splice(t,0,0)}return r}function rZ(e,t,n){const r=cr(t.type.schema).header_cell;for(let s=0;s<e.height;s++)if(t.nodeAt(e.map[n+s*e.width]).type!=r)return!1;return!0}var Qt=class di extends nt{constructor(t,n=t){const r=t.node(-1),s=En.get(r),i=t.start(-1),o=s.rectBetween(t.pos-i,n.pos-i),l=t.node(0),c=s.cellsInRect(o).filter(u=>u!=n.pos-i);c.unshift(n.pos-i);const d=c.map(u=>{const p=r.nodeAt(u);if(!p)throw new RangeError(`No cell with offset ${u} found`);const h=i+u+1;return new iN(l.resolve(h),l.resolve(h+p.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=n}map(t,n){const r=t.resolve(n.map(this.$anchorCell.pos)),s=t.resolve(n.map(this.$headCell.pos));if(wy(r)&&wy(s)&&h0(r,s)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?di.rowSelection(r,s):i&&this.isColSelection()?di.colSelection(r,s):new di(r,s)}return Ke.between(r,s)}content(){const t=this.$anchorCell.node(-1),n=En.get(t),r=this.$anchorCell.start(-1),s=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},o=[];for(let c=s.top;c<s.bottom;c++){const d=[];for(let u=c*n.width+s.left,p=s.left;p<s.right;p++,u++){const h=n.map[u];if(i[h])continue;i[h]=!0;const f=n.findCell(h);let g=t.nodeAt(h);if(!g)throw new RangeError(`No cell with offset ${h} found`);const x=s.left-f.left,b=f.right-s.right;if(x>0||b>0){let y=g.attrs;if(x>0&&(y=io(y,0,x)),b>0&&(y=io(y,y.colspan-b,b)),f.left<s.left){if(g=g.type.createAndFill(y),!g)throw new RangeError(`Could not create cell with attrs ${JSON.stringify(y)}`)}else g=g.type.create(y,g.content)}if(f.top<s.top||f.bottom>s.bottom){const y={...g.attrs,rowspan:Math.min(f.bottom,s.bottom)-Math.max(f.top,s.top)};f.top<s.top?g=g.type.createAndFill(y):g=g.type.create(y,g.content)}d.push(g)}o.push(t.child(c).copy(we.from(d)))}const l=this.isColSelection()&&this.isRowSelection()?t:o;return new Te(we.from(l),1,1)}replace(t,n=Te.empty){const r=t.steps.length,s=this.ranges;for(let o=0;o<s.length;o++){const{$from:l,$to:c}=s[o],d=t.mapping.slice(r);t.replace(d.map(l.pos),d.map(c.pos),o?Te.empty:n)}const i=nt.findFrom(t.doc.resolve(t.mapping.slice(r).map(this.to)),-1);i&&t.setSelection(i)}replaceWith(t,n){this.replace(t,new Te(we.from(n),0,0))}forEachCell(t){const n=this.$anchorCell.node(-1),r=En.get(n),s=this.$anchorCell.start(-1),i=r.cellsInRect(r.rectBetween(this.$anchorCell.pos-s,this.$headCell.pos-s));for(let o=0;o<i.length;o++)t(n.nodeAt(i[o]),s+i[o])}isColSelection(){const t=this.$anchorCell.index(-1),n=this.$headCell.index(-1);if(Math.min(t,n)>0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,s=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,s)==this.$headCell.node(-1).childCount}
69static colSelection(t,n=t){const r=t.node(-1),s=En.get(r),i=t.start(-1),o=s.findCell(t.pos-i),l=s.findCell(n.pos-i),c=t.node(0);return o.top<=l.top?(o.top>0&&(t=c.resolve(i+s.map[o.left])),l.bottom<s.height&&(n=c.resolve(i+s.map[s.width*(s.height-1)+l.right-1]))):(l.top>0&&(n=c.resolve(i+s.map[l.left])),o.bottom<s.height&&(t=c.resolve(i+s.map[s.width*(s.height-1)+o.right-1]))),new di(t,n)}isRowSelection(){const t=this.$anchorCell.node(-1),n=En.get(t),r=this.$anchorCell.start(-1),s=n.colCount(this.$anchorCell.pos-r),i=n.colCount(this.$headCell.pos-r);if(Math.min(s,i)>0)return!1;const o=s+this.$anchorCell.nodeAfter.attrs.colspan,l=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(o,l)==n.width}eq(t){return t instanceof di&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),s=En.get(r),i=t.start(-1),o=s.findCell(t.pos-i),l=s.findCell(n.pos-i),c=t.node(0);return o.left<=l.left?(o.left>0&&(t=c.resolve(i+s.map[o.top*s.width])),l.right<s.width&&(n=c.resolve(i+s.map[s.width*(l.top+1)-1]))):(l.left>0&&(n=c.resolve(i+s.map[l.top*s.width])),o.right<s.width&&(t=c.resolve(i+s.map[s.width*(o.top+1)-1]))),new di(t,n)}toJSON(){return{type:"cell",anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(t,n){return new di(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){return new di(t.resolve(n),t.resolve(r))}getBookmark(){return new sZ(this.$anchorCell.pos,this.$headCell.pos)}};Qt.prototype.visible=!1;nt.jsonID("cell",Qt);var sZ=class xO{constructor(t,n){this.anchor=t,this.head=n}map(t){return new xO(t.map(this.anchor),t.map(this.head))}resolve(t){const n=t.resolve(this.anchor),r=t.resolve(this.head);return n.parent.type.spec.tableRole=="row"&&r.parent.type.spec.tableRole=="row"&&n.index()<n.parent.childCount&&r.index()<r.parent.childCount&&h0(n,r)?new Qt(n,r):nt.near(r,1)}};function iZ(e){if(!(e.selection instanceof Qt))return null;const t=[];return e.selection.forEachCell((n,r)=>{t.push(Qn.node(r,r+n.nodeSize,{class:"selectedCell"}))}),Bt.create(e.doc,t)}function aZ({$from:e,$to:t}){if(e.pos==t.pos||e.pos<t.pos-6)return!1;let n=e.pos,r=t.pos,s=e.depth;for(;s>=0&&!(e.after(s+1)<e.end(s));s--,n++);for(let i=t.depth;i>=0&&!(t.before(i+1)>t.start(i));i--,r--);return n==r&&/row|table/.test(e.node(s).type.spec.tableRole)}function oZ({$from:e,$to:t}){let n,r;for(let s=e.depth;s>0;s--){const i=e.node(s);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){n=i;break}}for(let s=t.depth;s>0;s--){const i=t.node(s);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}return n!==r&&t.parentOffset===0}function lZ(e,t,n){const r=(t||e).selection,s=(t||e).doc;let i,o;if(r instanceof Ye&&(o=r.node.type.spec.tableRole)){if(o=="cell"||o=="header_cell")i=Qt.create(s,r.from);else if(o=="row"){const l=s.resolve(r.from+1);i=Qt.rowSelection(l,l)}else if(!n){const l=En.get(r.node),c=r.from+1,d=c+l.map[l.width*l.height-1];i=Qt.create(s,c+1,d)}}else r instanceof Ke&&aZ(r)?i=Ke.create(s,r.from):r instanceof Ke&&oZ(r)&&(i=Ke.create(s,r.$from.start(),r.$from.end()));return i&&(t||(t=e.tr)).setSelection(i),t}const cZ=new hn("fix-tables");function bO(e,t,n,r){const s=e.childCount,i=t.childCount;e:for(let o=0,l=0;o<i;o++){const c=t.child(o);for(let d=l,u=Math.min(s,o+3);d<u;d++)if(e.child(d)==c){l=d+1,n+=c.nodeSize;continue e}r(c,n),l<s&&e.child(l).sameMarkup(c)?bO(e.child(l),c,n+1,r):c.nodesBetween(0,c.content.size,r,n+1),n+=c.nodeSize}}function yO(e,t){let n;const r=(s,i)=>{s.type.spec.tableRole=="table"&&(n=dZ(e,s,i,n))};return t?t.doc!=e.doc&&bO(t.doc,e.doc,0,r):e.doc.descendants(r),n}function dZ(e,t,n,r){const s=En.get(t);if(!s.problems)return r;r||(r=e.tr);const i=[];for(let c=0;c<s.height;c++)i.push(0);for(let c=0;c<s.problems.length;c++){const d=s.problems[c];if(d.type=="collision"){const u=t.nodeAt(d.pos);if(!u)continue;const p=u.attrs;for(let h=0;h<p.rowspan;h++)i[d.row+h]+=d.n;r.setNodeMarkup(r.mapping.map(n+1+d.pos),null,io(p,p.colspan-d.n,d.n))}else if(d.type=="missing")i[d.row]+=d.n;
69else if(d.type=="overlong_rowspan"){const u=t.nodeAt(d.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+d.pos),null,{...u.attrs,rowspan:u.attrs.rowspan-d.n})}else if(d.type=="colwidth mismatch"){const u=t.nodeAt(d.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+d.pos),null,{...u.attrs,colwidth:d.colwidth})}else if(d.type=="zero_sized"){const u=r.mapping.map(n);r.delete(u,u+t.nodeSize)}}let o,l;for(let c=0;c<i.length;c++)i[c]&&(o==null&&(o=c),l=c);for(let c=0,d=n+1;c<s.height;c++){const u=t.child(c),p=d+u.nodeSize,h=i[c];if(h>0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const g=[];for(let b=0;b<h;b++){const y=cr(e.schema)[f].createAndFill();y&&g.push(y)}const x=(c==0||o==c-1)&&l==c?d+1:p-1;r.insert(r.mapping.map(x),g)}d=p}return r.setMeta(cZ,{fixTables:!0})}function ei(e){const t=e.selection,n=Km(e),r=n.node(-1),s=n.start(-1),i=En.get(r);return{...t instanceof Qt?i.rectBetween(t.$anchorCell.pos-s,t.$headCell.pos-s):i.findCell(n.pos-s),tableStart:s,map:i,table:r}}function vO(e,{map:t,tableStart:n,table:r},s){let i=s>0?-1:0;rZ(t,r,s+i)&&(i=s==0||s==t.width?null:0);for(let o=0;o<t.height;o++){const l=o*t.width+s;if(s>0&&s<t.width&&t.map[l-1]==t.map[l]){const c=t.map[l],d=r.nodeAt(c);e.setNodeMarkup(e.mapping.map(n+c),null,gO(d.attrs,s-t.colCount(c))),o+=d.attrs.rowspan-1}else{const c=i==null?cr(r.type.schema).cell:r.nodeAt(t.map[l+i]).type,d=t.positionAt(o,s,r);e.insert(e.mapping.map(n+d),c.createAndFill())}}return e}function uZ(e,t){if(!Ss(e))return!1;if(t){const n=ei(e);t(vO(e.tr,n,n.left))}return!0}function pZ(e,t){if(!Ss(e))return!1;if(t){const n=ei(e);t(vO(e.tr,n,n.right))}return!0}function hZ(e,{map:t,table:n,tableStart:r},s){const i=e.mapping.maps.length;for(let o=0;o<t.height;){const l=o*t.width+s,c=t.map[l],d=n.nodeAt(c),u=d.attrs;if(s>0&&t.map[l-1]==c||s<t.width-1&&t.map[l+1]==c)e.setNodeMarkup(e.mapping.slice(i).map(r+c),null,io(u,s-t.colCount(c)));else{const p=e.mapping.slice(i).map(r+c);e.delete(p,p+d.nodeSize)}o+=u.rowspan}}function fZ(e,t){if(!Ss(e))return!1;if(t){const n=ei(e),r=e.tr;if(n.left==0&&n.right==n.map.width)return!1;for(let s=n.right-1;hZ(r,n,s),s!=n.left;s--){const i=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!i)throw new RangeError("No table found");n.table=i,n.map=En.get(i)}t(r)}return!0}function mZ(e,t,n){var r;const s=cr(t.type.schema).header_cell;for(let i=0;i<e.width;i++)if(((r=t.nodeAt(e.map[i+n*e.width]))===null||r===void 0?void 0:r.type)!=s)return!1;return!0}function CO(e,{map:t,tableStart:n,table:r},s){let i=n;for(let d=0;d<s;d++)i+=r.child(d).nodeSize;const o=[];let l=s>0?-1:0;mZ(t,r,s+l)&&(l=s==0||s==t.height?null:0);for(let d=0,u=t.width*s;d<t.width;d++,u++)if(s>0&&s<t.height&&t.map[u]==t.map[u-t.width]){const p=t.map[u],h=r.nodeAt(p).attrs;e.setNodeMarkup(n+p,null,{...h,rowspan:h.rowspan+1}),d+=h.colspan-1}else{var c;const p=l==null?cr(r.type.schema).cell:(c=r.nodeAt(t.map[u+l*t.width]))===null||c===void 0?void 0:c.type,h=p?.createAndFill();h&&o.push(h)}return e.insert(i,cr(r.type.schema).row.create(null,o)),e}function gZ(e,t){if(!Ss(e))return!1;if(t){const n=ei(e);t(CO(e.tr,n,n.top))}return!0}function xZ(e,t){if(!Ss(e))return!1;if(t){const n=ei(e);t(CO(e.tr,n,n.bottom))}return!0}function bZ(e,{map:t,table:n,tableStart:r},s){let i=0;for(let d=0;d<s;d++)i+=n.child(d).nodeSize;const o=i+n.child(s).nodeSize,l=e.mapping.maps.length;e.delete(i+r,o+r);const c=new Set;for(let d=0,u=s*t.width;d<t.width;d++,u++){const p=t.map[u];if(!c.has(p)){if(c.add(p),s>0&&p==t.map[u-t.width]){const h=n.nodeAt(p).attrs;e.setNodeMarkup(e.mapping.slice(l).map(p+r),null,{...h,rowspan:h.rowspan-1}),d+=h.colspan-1}else if(s<t.height&&p==t.map[u+t.width]){const h=n.nodeAt(p),f=h.attrs,g=h.type.create({...f,rowspan:h.attrs.rowspan-1},h.content),x=t.positionAt(s+1,d,n);e.insert(e.mapping.slice(l).map(r+x),g),d+=f.colspan-1}}}}function yZ(e,t){if(!Ss(e))return!1;if(t){const n=ei(e),r=e.tr;if(n.top==0&&n.bottom==n.map.height)return!1;for(let s=n.bottom-1;bZ(r,n,s),s!=n.top;s--){const i=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!i)throw new RangeError("No table found");n.table=i,n.map=En.get(n.table)}t(r)}return!0}function A1(e){const t=e.content;return t.childCount==1&&t.child(0).isTextblock&&t.child(0).childCount==0}function vZ({width:e,height:t,map:n},r){let s=r.top*e+r.left,i=s,o=(r.bottom-1)*e+r.left,l=s+(r.right-r.left-1);for(let c=r.top;c<r.bottom;c++){if(r.left>0&&n[i]==n[i-1]||r.right<e&&n[l]==n[l+1])return!0;
69i+=e,l+=e}for(let c=r.left;c<r.right;c++){if(r.top>0&&n[s]==n[s-e]||r.bottom<t&&n[o]==n[o+e])return!0;s++,o++}return!1}function M1(e,t){const n=e.selection;if(!(n instanceof Qt)||n.$anchorCell.pos==n.$headCell.pos)return!1;const r=ei(e),{map:s}=r;if(vZ(s,r))return!1;if(t){const i=e.tr,o={};let l=we.empty,c,d;for(let u=r.top;u<r.bottom;u++)for(let p=r.left;p<r.right;p++){const h=s.map[u*s.width+p],f=r.table.nodeAt(h);if(!(o[h]||!f))if(o[h]=!0,c==null)c=h,d=f;else{A1(f)||(l=l.append(f.content));const g=i.mapping.map(h+r.tableStart);i.delete(g,g+f.nodeSize)}}if(c==null||d==null)return!0;if(i.setNodeMarkup(c+r.tableStart,null,{...gO(d.attrs,d.attrs.colspan,r.right-r.left-d.attrs.colspan),rowspan:r.bottom-r.top}),l.size>0){const u=c+1+d.content.size,p=A1(d)?c+1:u;i.replaceWith(p+r.tableStart,u+r.tableStart,l)}i.setSelection(new Qt(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function R1(e,t){const n=cr(e.schema);return CZ(({node:r})=>n[r.type.spec.tableRole])(e,t)}function CZ(e){return(t,n)=>{const r=t.selection;let s,i;if(r instanceof Qt){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;s=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var o;if(s=eZ(r.$from),!s)return!1;i=(o=so(r.$from))===null||o===void 0?void 0:o.pos}if(s==null||i==null||s.attrs.colspan==1&&s.attrs.rowspan==1)return!1;if(n){let l=s.attrs;const c=[],d=l.colwidth;l.rowspan>1&&(l={...l,rowspan:1}),l.colspan>1&&(l={...l,colspan:1});const u=ei(t),p=t.tr;for(let f=0;f<u.right-u.left;f++)c.push(d?{...l,colwidth:d&&d[f]?[d[f]]:null}:l);let h;for(let f=u.top;f<u.bottom;f++){let g=u.map.positionAt(f,u.left,u.table);f==u.top&&(g+=s.nodeSize);for(let x=u.left,b=0;x<u.right;x++,b++)x==u.left&&f==u.top||p.insert(h=p.mapping.map(g+u.tableStart,1),e({node:s,row:f,col:x}).createAndFill(c[b]))}p.setNodeMarkup(i,e({node:s,row:u.top,col:u.left}),c[0]),r instanceof Qt&&p.setSelection(new Qt(p.doc.resolve(r.$anchorCell.pos),h?p.doc.resolve(h):void 0)),n(p)}return!0}}function wZ(e,t){return function(n,r){if(!Ss(n))return!1;const s=Km(n);if(s.nodeAfter.attrs[e]===t)return!1;if(r){const i=n.tr;n.selection instanceof Qt?n.selection.forEachCell((o,l)=>{o.attrs[e]!==t&&i.setNodeMarkup(l,null,{...o.attrs,[e]:t})}):i.setNodeMarkup(s.pos,null,{...s.nodeAfter.attrs,[e]:t}),r(i)}return!0}}function SZ(e){return function(t,n){if(!Ss(t))return!1;if(n){const r=cr(t.schema),s=ei(t),i=t.tr,o=s.map.cellsInRect(e=="column"?{left:s.left,top:0,right:s.right,bottom:s.map.height}:e=="row"?{left:0,top:s.top,right:s.map.width,bottom:s.bottom}:s),l=o.map(c=>s.table.nodeAt(c));for(let c=0;c<o.length;c++)l[c].type==r.header_cell&&i.setNodeMarkup(s.tableStart+o[c],r.cell,l[c].attrs);if(i.steps.length===0)for(let c=0;c<o.length;c++)i.setNodeMarkup(s.tableStart+o[c],r.header_cell,l[c].attrs);n(i)}return!0}}function N1(e,t,n){const r=t.map.cellsInRect({left:0,top:0,right:e=="row"?t.map.width:1,bottom:e=="column"?t.map.height:1});for(let s=0;s<r.length;s++){const i=t.table.nodeAt(r[s]);if(i&&i.type!==n.header_cell)return!1}return!0}function Hd(e,t){return t=t||{useDeprecatedLogic:!1},t.useDeprecatedLogic?SZ(e):function(n,r){if(!Ss(n))return!1;if(r){const s=cr(n.schema),i=ei(n),o=n.tr,l=N1("row",i,s),c=N1("column",i,s),d=(e==="column"?l:e==="row"&&c)?1:0,u=e=="column"?{left:0,top:d,right:1,bottom:i.map.height}:e=="row"?{left:d,top:0,right:i.map.width,bottom:1}:i,p=e=="column"?c?s.cell:s.header_cell:e=="row"?l?s.cell:s.header_cell:s.cell;i.map.cellsInRect(u).forEach(h=>{const f=h+i.tableStart,g=o.doc.nodeAt(f);g&&o.setNodeMarkup(f,p,g.attrs)}),r(o)}return!0}}Hd("row",{useDeprecatedLogic:!0});Hd("column",{useDeprecatedLogic:!0});const jZ=Hd("cell",{useDeprecatedLogic:!0});function kZ(e,t){if(t<0){const n=e.nodeBefore;if(n)return e.pos-n.nodeSize;for(let r=e.index(-1)-1,s=e.before();r>=0;r--){const i=e.node(-1).child(r),o=i.lastChild;if(o)return s-1-o.nodeSize;s-=i.nodeSize}}else{if(e.index()<e.parent.childCount-1)return e.pos+e.nodeAfter.nodeSize;const n=e.node(-1);for(let r=e.indexAfter(-1),s=e.after();r<n.childCount;r++){const i=n.child(r);if(i.childCount)return s+1;s+=i.nodeSize}}return null}function O1(e){return function(t,n){if(!Ss(t))return!1;const r=kZ(Km(t),e);if(r==null)return!1;if(n){const s=t.doc.resolve(r);n(t.tr.setSelection(Ke.between(s,nZ(s))).scrollIntoView())}return!0}}function EZ(e,t){const n=e.selection.$anchor;for(let r=n.depth;r>0;r--)if(n.node(r).type.spec.tableRole=="table")return t&&t(e.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function mp(e,t){const n=e.selection;if(!(n instanceof Qt))return!1;if(t){const r=e.tr,s=cr(e.schema).cell.createAndFill().content;
69n.forEachCell((i,o)=>{i.content.eq(s)||r.replace(r.mapping.map(o+1),r.mapping.map(o+i.nodeSize-1),new Te(s,0,0))}),r.docChanged&&t(r)}return!0}function _Z(e){if(e.size===0)return null;let{content:t,openStart:n,openEnd:r}=e;for(;t.childCount==1&&(n>0&&r>0||t.child(0).type.spec.tableRole=="table");)n--,r--,t=t.child(0).content;const s=t.child(0),i=s.type.spec.tableRole,o=s.type.schema,l=[];if(i=="row")for(let c=0;c<t.childCount;c++){let d=t.child(c).content;const u=c?0:Math.max(0,n-1),p=c<t.childCount-1?0:Math.max(0,r-1);(u||p)&&(d=Sy(cr(o).row,new Te(d,u,p)).content),l.push(d)}else if(i=="cell"||i=="header_cell")l.push(n||r?Sy(cr(o).row,new Te(t,n,r)).content:t);else return null;return TZ(o,l)}function TZ(e,t){const n=[];for(let s=0;s<t.length;s++){const i=t[s];for(let o=i.childCount-1;o>=0;o--){const{rowspan:l,colspan:c}=i.child(o).attrs;for(let d=s;d<s+l;d++)n[d]=(n[d]||0)+c}}let r=0;for(let s=0;s<n.length;s++)r=Math.max(r,n[s]);for(let s=0;s<n.length;s++)if(s>=t.length&&t.push(we.empty),n[s]<r){const i=cr(e).cell.createAndFill(),o=[];for(let l=n[s];l<r;l++)o.push(i);t[s]=t[s].append(we.from(o))}return{height:t.length,width:r,rows:t}}function Sy(e,t){const n=e.createAndFill();return new sN(n).replace(0,n.content.size,t).doc}function IZ({width:e,height:t,rows:n},r,s){if(e!=r){const i=[],o=[];for(let l=0;l<n.length;l++){const c=n[l],d=[];for(let u=i[l]||0,p=0;u<r;p++){let h=c.child(p%c.childCount);u+h.attrs.colspan>r&&(h=h.type.createChecked(io(h.attrs,h.attrs.colspan,u+h.attrs.colspan-r),h.content)),d.push(h),u+=h.attrs.colspan;for(let f=1;f<h.attrs.rowspan;f++)i[l+f]=(i[l+f]||0)+h.attrs.colspan}o.push(we.from(d))}n=o,e=r}if(t!=s){const i=[];for(let o=0,l=0;o<s;o++,l++){const c=[],d=n[l%t];for(let u=0;u<d.childCount;u++){let p=d.child(u);o+p.attrs.rowspan>s&&(p=p.type.create({...p.attrs,rowspan:Math.max(1,s-p.attrs.rowspan)},p.content)),c.push(p)}i.push(we.from(c))}n=i,t=s}return{width:e,height:t,rows:n}}function DZ(e,t,n,r,s,i,o){const l=e.doc.type.schema,c=cr(l);let d,u;if(s>t.width)for(let p=0,h=0;p<t.height;p++){const f=n.child(p);h+=f.nodeSize;const g=[];let x;f.lastChild==null||f.lastChild.type==c.cell?x=d||(d=c.cell.createAndFill()):x=u||(u=c.header_cell.createAndFill());for(let b=t.width;b<s;b++)g.push(x);e.insert(e.mapping.slice(o).map(h-1+r),g)}if(i>t.height){const p=[];for(let g=0,x=(t.height-1)*t.width;g<Math.max(t.width,s);g++){const b=g>=t.width?!1:n.nodeAt(t.map[x+g]).type==c.header_cell;p.push(b?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const h=c.row.create(null,we.from(p)),f=[];for(let g=t.height;g<i;g++)f.push(h);e.insert(e.mapping.slice(o).map(r+n.nodeSize-2),f)}return!!(d||u)}function P1(e,t,n,r,s,i,o,l){if(o==0||o==t.height)return!1;let c=!1;for(let d=s;d<i;d++){const u=o*t.width+d,p=t.map[u];if(t.map[u-t.width]==p){c=!0;const h=n.nodeAt(p),{top:f,left:g}=t.findCell(p);e.setNodeMarkup(e.mapping.slice(l).map(p+r),null,{...h.attrs,rowspan:o-f}),e.insert(e.mapping.slice(l).map(t.positionAt(o,g,n)),h.type.createAndFill({...h.attrs,rowspan:f+h.attrs.rowspan-o})),d+=h.attrs.colspan-1}}return c}function L1(e,t,n,r,s,i,o,l){if(o==0||o==t.width)return!1;let c=!1;for(let d=s;d<i;d++){const u=d*t.width+o,p=t.map[u];if(t.map[u-1]==p){c=!0;const h=n.nodeAt(p),f=t.colCount(p),g=e.mapping.slice(l).map(p+r);e.setNodeMarkup(g,null,io(h.attrs,o-f,h.attrs.colspan-(o-f))),e.insert(g+h.nodeSize,h.type.createAndFill(io(h.attrs,0,o-f))),d+=h.attrs.rowspan-1}}return c}function F1(e,t,n,r,s){let i=n?e.doc.nodeAt(n-1):e.doc;if(!i)throw new Error("No table found");let o=En.get(i);const{top:l,left:c}=r,d=c+s.width,u=l+s.height,p=e.tr;let h=0;function f(){if(i=n?p.doc.nodeAt(n-1):p.doc,!i)throw new Error("No table found");o=En.get(i),h=p.mapping.maps.length}DZ(p,o,i,n,d,u,h)&&f(),P1(p,o,i,n,c,d,l,h)&&f(),P1(p,o,i,n,c,d,u,h)&&f(),L1(p,o,i,n,l,u,c,h)&&f(),L1(p,o,i,n,l,u,d,h)&&f();for(let g=l;g<u;g++){const x=o.positionAt(g,c,i),b=o.positionAt(g,d,i);p.replace(p.mapping.slice(h).map(x+n),p.mapping.slice(h).map(b+n),new Te(s.rows[g-l],0,0))}f(),p.setSelection(new Qt(p.doc.resolve(n+o.positionAt(l,c,i)),p.doc.resolve(n+o.positionAt(u-1,d-1,i)))),t(p)}const AZ=qN({ArrowLeft:gp("horiz",-1),ArrowRight:gp("horiz",1),ArrowUp:gp("vert",-1),ArrowDown:gp("vert",1),"Shift-ArrowLeft":xp("horiz",-1),"Shift-ArrowRight":xp("horiz",1),"Shift-ArrowUp":xp("vert",-1),"Shift-ArrowDown":xp("vert",1),Backspace:mp,"Mod-Backspace":mp,Delete:mp,"Mod-Delete":mp});
69function yh(e,t,n){return n.eq(e.selection)?!1:(t&&t(e.tr.setSelection(n).scrollIntoView()),!0)}function gp(e,t){return(n,r,s)=>{if(!s)return!1;const i=n.selection;if(i instanceof Qt)return yh(n,r,nt.near(i.$headCell,t));if(e!="horiz"&&!i.empty)return!1;const o=wO(s,e,t);if(o==null)return!1;if(e=="horiz")return yh(n,r,nt.near(n.doc.resolve(i.head+t),t));{const l=n.doc.resolve(o),c=mO(l,e,t);let d;return c?d=nt.near(c,1):t<0?d=nt.near(n.doc.resolve(l.before(-1)),-1):d=nt.near(n.doc.resolve(l.after(-1)),1),yh(n,r,d)}}}function xp(e,t){return(n,r,s)=>{if(!s)return!1;const i=n.selection;let o;if(i instanceof Qt)o=i;else{const c=wO(s,e,t);if(c==null)return!1;o=new Qt(n.doc.resolve(c))}const l=mO(o.$headCell,e,t);return l?yh(n,r,new Qt(o.$anchorCell,l)):!1}}function MZ(e,t){const n=e.state.doc,r=so(n.resolve(t));return r?(e.dispatch(e.state.tr.setSelection(new Qt(r))),!0):!1}function RZ(e,t,n){if(!Ss(e.state))return!1;let r=_Z(n);const s=e.state.selection;if(s instanceof Qt){r||(r={width:1,height:1,rows:[we.from(Sy(cr(e.state.schema).cell,n))]});const i=s.$anchorCell.node(-1),o=s.$anchorCell.start(-1),l=En.get(i).rectBetween(s.$anchorCell.pos-o,s.$headCell.pos-o);return r=IZ(r,l.right-l.left,l.bottom-l.top),F1(e.state,e.dispatch,o,l,r),!0}else if(r){const i=Km(e.state),o=i.start(-1);return F1(e.state,e.dispatch,o,En.get(i.node(-1)).findCell(i.pos-o),r),!0}else return!1}function NZ(e,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=$1(e,t.target);let s;if(t.shiftKey&&e.state.selection instanceof Qt)i(e.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(s=so(e.state.selection.$anchor))!=null&&((n=px(e,t))===null||n===void 0?void 0:n.pos)!=s.pos)i(s,t),t.preventDefault();else if(!r)return;function i(c,d){let u=px(e,d);const p=Bi.getState(e.state)==null;if(!u||!h0(c,u))if(p)u=c;else return;const h=new Qt(c,u);if(p||!e.state.selection.eq(h)){const f=e.state.tr.setSelection(h);p&&f.setMeta(Bi,c.pos),e.dispatch(f)}}function o(){e.root.removeEventListener("mouseup",o),e.root.removeEventListener("dragstart",o),e.root.removeEventListener("mousemove",l),Bi.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta(Bi,-1))}function l(c){const d=c,u=Bi.getState(e.state);let p;if(u!=null)p=e.state.doc.resolve(u);else if($1(e,d.target)!=r&&(p=px(e,t),!p))return o();p&&i(p,d)}e.root.addEventListener("mouseup",o),e.root.addEventListener("dragstart",o),e.root.addEventListener("mousemove",l)}function wO(e,t,n){if(!(e.state.selection instanceof Ke))return null;const{$head:r}=e.state.selection;for(let s=r.depth-1;s>=0;s--){const i=r.node(s);if((n<0?r.index(s):r.indexAfter(s))!=(n<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const o=r.before(s),l=t=="vert"?n>0?"down":"up":n>0?"right":"left";return e.endOfTextblock(l)?o:null}}return null}function $1(e,t){for(;t&&t!=e.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function px(e,t){const n=e.posAtCoords({left:t.clientX,top:t.clientY});if(!n)return null;let{inside:r,pos:s}=n;return r>=0&&so(e.state.doc.resolve(r))||so(e.state.doc.resolve(s))}var OZ=class{constructor(t,n){this.node=t,this.defaultCellMinWidth=n,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${n}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),jy(t,this.colgroup,this.table,n),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,jy(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function jy(e,t,n,r,s,i){let o=0,l=!0,c=t.firstChild;const d=e.firstChild;if(d){for(let p=0,h=0;p<d.childCount;p++){const{colspan:f,colwidth:g}=d.child(p).attrs;for(let x=0;x<f;x++,h++){const b=s==h?i:g&&g[x],y=b?b+"px":"";if(o+=b||r,b||(l=!1),c)c.style.width!=y&&(c.style.width=y),c=c.nextSibling;else{const v=document.createElement("col");v.style.width=y,t.appendChild(v)}}}for(;c;){var u;const p=c.nextSibling;(u=c.parentNode)===null||u===void 0||u.removeChild(c),c=p}l?(n.style.width=o+"px",n.style.minWidth=""):(n.style.width="",n.style.minWidth=o+"px")}}const Or=new hn("tableColumnResizing");function PZ({handleWidth:e=5,cellMinWidth:t=25,defaultCellMinWidth:n=100,View:r=OZ,lastColumnResizable:s=!0}={}){const i=new pn({key:Or,state:{init(o,l){var c;const d=(c=i.spec)===null||c===void 0||(c=c.props)===null||c===void 0?void 0:c.nodeViews,u=cr(l.schema).table.name;return r&&d&&(d[u]=(p,h)=>new r(p,n,h)),new LZ(-1,!1)},apply(o,l){return l.apply(o)}},props:{attributes:o=>{const l=Or.getState(o);return l&&l.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(o,l)=>{FZ(o,l,e,s)},mouseleave:o=>{$Z(o)},mousedown:(o,l)=>{zZ(o,l,t,n)}},decorations:o=>{const l=Or.getState(o);if(l&&l.activeHandle>-1)return HZ(o,l.activeHandle)},nodeViews:{}}});return i}var LZ=class vh{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(Or);if(r&&r.setHandle!=null)return new vh(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new vh(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let s=t.mapping.map(n.activeHandle,-1);return wy(t.doc.resolve(s))||(s=-1),new vh(s,n.dragging)}return n}};function FZ(e,t,n,r){if(!e.editable)return;const s=Or.getState(e.state);if(s&&!s.dragging){const i=UZ(t.target);let o=-1;if(i){const{left:l,right:c}=i.getBoundingClientRect();t.clientX-l<=n?o=z1(e,t,"left",n):c-t.clientX<=n&&(o=z1(e,t,"right",n))}if(o!=s.activeHandle){if(!r&&o!==-1){const l=e.state.doc.resolve(o),c=l.node(-1),d=En.get(c),u=l.start(-1);if(d.colCount(l.pos-u)+l.nodeAfter.attrs.colspan-1==d.width-1)return}SO(e,o)}}}function $Z(e){if(!e.editable)return;const t=Or.getState(e.state);t&&t.activeHandle>-1&&!t.dragging&&SO(e,-1)}function zZ(e,t,n,r){var s;if(!e.editable)return!1;const i=(s=e.dom.ownerDocument.defaultView)!==null&&s!==void 0?s:window,o=Or.getState(e.state);if(!o||o.activeHandle==-1||o.dragging)return!1;const l=e.state.doc.nodeAt(o.activeHandle),c=BZ(e,o.activeHandle,l.attrs);e.dispatch(e.state.tr.setMeta(Or,{setDragging:{startX:t.clientX,startWidth:c}}));function d(p){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const h=Or.getState(e.state);h?.dragging&&(VZ(e,h.activeHandle,B1(h.dragging,p,n)),e.dispatch(e.state.tr.setMeta(Or,{setDragging:null})))}function u(p){if(!p.which)return d(p);const h=Or.getState(e.state);if(h&&h.dragging){const f=B1(h.dragging,p,n);U1(e,h.activeHandle,f,r)}}return U1(e,o.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function BZ(e,t,{colspan:n,colwidth:r}){const s=r&&r[r.length-1];if(s)return s;const i=e.domAtPos(t);let o=i.node.childNodes[i.offset].offsetWidth,l=n;if(r)for(let c=0;c<n;c++)r[c]&&(o-=r[c],l--);return o/l}function UZ(e){for(;e&&e.nodeName!="TD"&&e.nodeName!="TH";)e=e.classList&&e.classList.contains("ProseMirror")?null:e.parentNode;return e}function z1(e,t,n,r){const s=n=="right"?-r:r,i=e.posAtCoords({left:t.clientX+s,top:t.clientY});if(!i)return-1;const{pos:o}=i,l=so(e.state.doc.resolve(o));if(!l)return-1;if(n=="right")return l.pos;const c=En.get(l.node(-1)),d=l.start(-1),u=c.map.indexOf(l.pos-d);return u%c.width==0?-1:d+c.map[u-1]}function B1(e,t,n){const r=t.clientX-e.startX;return Math.max(n,e.startWidth+r)}function SO(e,t){e.dispatch(e.state.tr.setMeta(Or,{setHandle:t}))}
69function VZ(e,t,n){const r=e.state.doc.resolve(t),s=r.node(-1),i=En.get(s),o=r.start(-1),l=i.colCount(r.pos-o)+r.nodeAfter.attrs.colspan-1,c=e.state.tr;for(let d=0;d<i.height;d++){const u=d*i.width+l;if(d&&i.map[u]==i.map[u-i.width])continue;const p=i.map[u],h=s.nodeAt(p).attrs,f=h.colspan==1?0:l-i.colCount(p);if(h.colwidth&&h.colwidth[f]==n)continue;const g=h.colwidth?h.colwidth.slice():WZ(h.colspan);g[f]=n,c.setNodeMarkup(o+p,null,{...h,colwidth:g})}c.docChanged&&e.dispatch(c)}function U1(e,t,n,r){const s=e.state.doc.resolve(t),i=s.node(-1),o=s.start(-1),l=En.get(i).colCount(s.pos-o)+s.nodeAfter.attrs.colspan-1;let c=e.domAtPos(s.start(-1)).node;for(;c&&c.nodeName!="TABLE";)c=c.parentNode;c&&jy(i,c.firstChild,c,r,l,n)}function WZ(e){return Array(e).fill(0)}function HZ(e,t){const n=[],r=e.doc.resolve(t),s=r.node(-1);if(!s)return Bt.empty;const i=En.get(s),o=r.start(-1),l=i.colCount(r.pos-o)+r.nodeAfter.attrs.colspan-1;for(let d=0;d<i.height;d++){const u=l+d*i.width;if((l==i.width-1||i.map[u]!=i.map[u+1])&&(d==0||i.map[u]!=i.map[u-i.width])){var c;const p=i.map[u],h=o+p+s.nodeAt(p).nodeSize-1,f=document.createElement("div");f.className="column-resize-handle",!((c=Or.getState(e))===null||c===void 0)&&c.dragging&&n.push(Qn.node(o+p,o+p+s.nodeAt(p).nodeSize,{class:"column-resize-dragging"})),n.push(Qn.widget(h,f))}}return Bt.create(e.doc,n)}function qZ({allowTableNodeSelection:e=!1}={}){return new pn({key:Bi,state:{init(){return null},apply(t,n){const r=t.getMeta(Bi);if(r!=null)return r==-1?null:r;if(n==null||!t.docChanged)return n;const{deleted:s,pos:i}=t.mapping.mapResult(n);return s?null:i}},props:{decorations:iZ,handleDOMEvents:{mousedown:NZ},createSelectionBetween(t){return Bi.getState(t.state)!=null?t.state.selection:null},handleTripleClick:MZ,handleKeyDown:AZ,handlePaste:RZ},appendTransaction(t,n,r){return lZ(r,yO(r,n),e)}})}const GZ="modulepreload",YZ=function(e){return"/"+e},V1={},KZ=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");s=c(n.map(d=>{if(d=YZ(d),d in V1)return;V1[d]=!0;const u=d.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":GZ,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((f,g)=>{h.addEventListener("load",f),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return s.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};var QZ=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/;Gn.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:e}){return["img",an(this.options.HTMLAttributes,e)]},parseMarkdown:(e,t)=>t.createNode("image",{src:e.href,title:e.title,alt:e.text}),renderMarkdown:e=>{var t,n,r,s,i,o;const l=(n=(t=e.attrs)==null?void 0:t.src)!=null?n:"",c=(s=(r=e.attrs)==null?void 0:r.alt)!=null?s:"",d=(o=(i=e.attrs)==null?void 0:i.title)!=null?o:"";return d?``:``},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>"u")return null;const{directions:e,minWidth:t,minHeight:n,alwaysPreserveAspectRatio:r}=this.options.resize;return({node:s,getPos:i,HTMLAttributes:o,editor:l})=>{const c=document.createElement("img");
69Object.entries(o).forEach(([p,h])=>{if(h!=null)switch(p){case"width":case"height":break;default:c.setAttribute(p,h);break}}),c.src=o.src;const d=new kX({element:c,editor:l,node:s,getPos:i,onResize:(p,h)=>{c.style.width=`${p}px`,c.style.height=`${h}px`},onCommit:(p,h)=>{const f=i();f!==void 0&&this.editor.chain().setNodeSelection(f).updateAttributes(this.name,{width:p,height:h}).run()},onUpdate:(p,h,f)=>p.type===s.type,options:{directions:e,min:{width:t,height:n},preserveAspectRatio:r===!0}}),u=d.dom;return u.style.visibility="hidden",u.style.pointerEvents="none",c.onload=()=>{u.style.visibility="",u.style.pointerEvents=""},d}},addCommands(){return{setImage:e=>({commands:t})=>t.insertContent({type:this.name,attrs:e})}},addInputRules(){return[lO({find:QZ,type:this.type,getAttributes:e=>{const[,,t,n,r]=e;return{src:n,alt:t,title:r}}})]}});var JZ=Object.defineProperty,XZ=(e,t)=>{for(var n in t)JZ(e,n,{get:t[n],enumerable:!0})},ZZ="listItem",W1="textStyle",H1=/^\s*([-+*])\s$/,jO=Gn.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:e}){return["ul",an(this.options.HTMLAttributes,e),0]},markdownTokenName:"list",parseMarkdown:(e,t)=>e.type!=="list"||e.ordered?[]:{type:"bulletList",content:e.items?t.parseChildren(e.items):[]},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,` 70`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(ZZ,this.editor.getAttributes(W1)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}}
70,addInputRules(){let e=dl({find:H1,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=dl({find:H1,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(W1),editor:this.editor})),[e]}});function eee(e){var t,n;const r=(t=e.tokens)==null?void 0:t[0];return!!(e.text&&((n=e.tokens)==null?void 0:n.length)===1&&r?.type==="list"&&r.ordered&&r.raw===e.text)}function tee(e,t){return t.tokenizeInline?t.parseInline(t.tokenizeInline(e)):t.parseInline([{type:"text",raw:e,text:e}])}var kO=Gn.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:e}){return["li",an(this.options.HTMLAttributes,e),0]},markdownTokenName:"list_item",parseMarkdown:(e,t)=>{var n;if(e.type!=="list_item")return[];const r=(n=t.parseBlockChildren)!=null?n:t.parseChildren;let s=[];if(e.tokens&&e.tokens.length>0){if(eee(e))return{type:"listItem",content:[{type:"paragraph",content:tee(e.text||"",t)}]};if(e.tokens.some(o=>o.type==="paragraph"))s=r(e.tokens);else{const o=e.tokens[0];if(o&&o.type==="text"&&o.tokens&&o.tokens.length>0){if(s=[{type:"paragraph",content:t.parseInline(o.tokens)}],e.tokens.length>1){const c=e.tokens.slice(1),d=r(c);s.push(...d)}}else s=r(e.tokens)}}return s.length===0&&(s=[{type:"paragraph",content:[]}]),{type:"listItem",content:s}},renderMarkdown:(e,t,n)=>u0(e,t,r=>{var s,i;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((i=(s=r.meta)==null?void 0:s.parentAttrs)==null?void 0:i.start)||1)+r.index}. `:"- "},n),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),nee={};XZ(nee,{findListItemPos:()=>Tu,getNextListDepth:()=>f0,handleBackspace:()=>ky,handleDelete:()=>Ey,hasListBefore:()=>EO,hasListItemAfter:()=>ree,hasListItemBefore:()=>_O,listItemHasSubList:()=>TO,nextListIsDeeper:()=>IO,nextListIsHigher:()=>DO});var Tu=(e,t)=>{const{$from:n}=t.selection,r=qn(e,t.schema);let s=null,i=n.depth,o=n.pos,l=null;for(;i>0&&l===null;)s=n.node(i),s.type===r?l=i:(i-=1,o-=1);return l===null?null:{$pos:t.doc.resolve(o),depth:l}},f0=(e,t)=>{const n=Tu(e,t);if(!n)return!1;const[,r]=FJ(t,e,n.$pos.pos+4);return r},EO=(e,t,n)=>{const{$anchor:r}=e.selection,s=Math.max(0,r.pos-2),i=e.doc.resolve(s).node();return!(!i||!n.includes(i.type.name))},_O=(e,t)=>{var n;const{$anchor:r}=t.selection,s=t.doc.resolve(r.pos-2);return!(s.index()===0||((n=s.nodeBefore)==null?void 0:n.type.name)!==e)},TO=(e,t,n)=>{if(!n)return!1;const r=qn(e,t.schema);let s=!1;return n.descendants(i=>{i.type===r&&(s=!0)}),s},ky=(e,t,n)=>{if(e.commands.undoInputRule())return!0;if(e.state.selection.from!==e.state.selection.to)return!1;if(!ll(e.state,t)&&EO(e.state,t,n)){const{$anchor:l}=e.state.selection,c=e.state.doc.resolve(l.before()-1),d=[];c.node().descendants((h,f)=>{h.type.name===t&&d.push({node:h,pos:f})});const u=d.at(-1);if(!u)return!1;const p=e.state.doc.resolve(c.start()+u.pos+1);return e.chain().cut({from:l.start()-1,to:l.end()+1},p.end()).joinForward().run()}if(!ll(e.state,t)||!BJ(e.state))return!1;const r=Tu(t,e.state);if(!r)return!1;const i=e.state.doc.resolve(r.$pos.pos-2).node(r.depth),o=TO(t,e.state,i);return _O(t,e.state)&&!o?e.commands.joinItemBackward():e.chain().liftListItem(t).run()},IO=(e,t)=>{const n=f0(e,t),r=Tu(e,t);return!r||!n?!1:n>r.depth},DO=(e,t)=>{const n=f0(e,t),r=Tu(e,t);return!r||!n?!1:n<r.depth},Ey=(e,t)=>{if(!ll(e.state,t)||!zJ(e.state,t))return!1;const{selection:n}=e.state,{$from:r,$to:s}=n;return!n.empty&&r.sameParent(s)?!1:IO(t,e.state)?e.chain().focus(e.state.selection.from+4).lift(t).joinBackward().run():DO(t,e.state)?e.chain().joinForward().joinBackward().run():e.commands.joinItemForward()},ree=(e,t)=>{var n;const{$anchor:r}=t.selection,s=t.doc.resolve(r.pos-r.parentOffset-2);return!(s.index()===s.parent.childCount-1||((n=s.nodeAfter)==null?void 0:n.type.name)!==e)},AO=ln.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:e})=>{let t=!1;
70return this.options.listTypes.forEach(({itemName:n})=>{e.state.schema.nodes[n]!==void 0&&Ey(e,n)&&(t=!0)}),t},"Mod-Delete":({editor:e})=>{let t=!1;return this.options.listTypes.forEach(({itemName:n})=>{e.state.schema.nodes[n]!==void 0&&Ey(e,n)&&(t=!0)}),t},Backspace:({editor:e})=>{let t=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{e.state.schema.nodes[n]!==void 0&&ky(e,n,r)&&(t=!0)}),t},"Mod-Backspace":({editor:e})=>{let t=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{e.state.schema.nodes[n]!==void 0&&ky(e,n,r)&&(t=!0)}),t}}}}),q1=/^(\s*)(\d+)\.\s+(.*)$/,see=/^\s/;function iee(e){const t=e.trimStart();return/^[-+*]\s+/.test(t)||/^\d+\.\s+/.test(t)||/^>\s?/.test(t)||/^```/.test(t)||/^~~~/.test(t)}function aee(e){const t=[],n=[];let r=!1;return e.forEach(s=>{if(r){n.push(s);return}if(s.trim()===""){r=!0,n.push(s);return}if(t.length>0&&iee(s)){r=!0,n.push(s);return}t.push(s)}),{paragraphLines:t,blockLines:n}}function oee(e){const t=[];let n=0,r=0;for(;n<e.length;){const s=e[n],i=s.match(q1);if(!i)break;const[,o,l,c]=i,d=o.length,u=[c];let p=n+1;const h=[s];let f=!1;for(;p<e.length;){const g=e[p];if(g.match(q1))break;if(g.trim()==="")h.push(g),u.push(""),f=!0,p+=1;else if(g.match(see))h.push(g),u.push(g.slice(d+2)),p+=1;else{if(f)break;h.push(g),u.push(g),p+=1}}t.push({indent:d,number:parseInt(l,10),content:u.join(` 71`).trim(),contentLines:u,raw:h.join(` 72`)}),r=p,n=p}return[t,r]}function MO(e,t,n){const r=[];let s=0;for(;s<e.length;){const i=e[s];if(i.indent===t){const{paragraphLines:o,blockLines:l}=aee(i.contentLines),c=o.join(` 73`).trim(),d=[];c&&d.push({type:"paragraph",raw:c,tokens:n.inlineTokens(c)});const u=l.join(` 74`).trim();if(u){const f=n.blockTokens(u);d.push(...f)}let p=s+1;const h=[];for(;p<e.length&&e[p].indent>t;)h.push(e[p]),p+=1;if(h.length>0){const f=Math.min(...h.map(x=>x.indent)),g=MO(h,f,n);d.push({type:"list",ordered:!0,start:h[0].number,items:g,raw:h.map(x=>x.raw).join(` 75`)})}r.push({type:"list_item",raw:i.raw,tokens:d}),s=p}else s+=1}return r}function lee(e,t){return e.map(n=>{if(n.type!=="list_item")return t.parseChildren([n])[0];const r=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(s=>{if(s.type==="paragraph"||s.type==="list"||s.type==="blockquote"||s.type==="code")r.push(...t.parseChildren([s]));else if(s.type==="text"&&s.tokens){const i=t.parseChildren([s]);r.push({type:"paragraph",content:i})}else{const i=t.parseChildren([s]);i.length>0&&r.push(...i)}}),{type:"listItem",content:r}})}var cee="listItem",G1="textStyle",Y1=/^(\d+)\.\s$/,RO=Gn.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute("start")?parseInt(e.getAttribute("start")||"",10):1},type:{default:null,parseHTML:e=>e.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:e}){const{start:t,...n}=e;return t===1?["ol",an(this.options.HTMLAttributes,n),0]:["ol",an(this.options.HTMLAttributes,e),0]},markdownTokenName:"list",parseMarkdown:(e,t)=>{if(e.type!=="list"||!e.ordered)return[];const n=e.start||1,r=e.items?lee(e.items,t):[];return n!==1?{type:"orderedList",attrs:{start:n},content:r}:{type:"orderedList",content:r}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,` 76`):"",markdownTokenizer:{name:"orderedList",level:"block",start:e=>{const t=e.match(/^(\s*)(\d+)\.\s+/),n=t?.index;return n!==void 0?n:-1},tokenize:(e,t,n)=>{var r;const s=e.split(` 77`),[i,o]=oee(s);if(i.length===0)return;const l=MO(i,0,n);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=i[0])==null?void 0:r.number)||1,items:l,raw:s.slice(0,o).join(` 78`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(cee,this.editor.getAttributes(G1)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}}
vendor: 5,483 bytes, lines 78-79
78,addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let e=dl({find:Y1,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(e=dl({find:Y1,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(G1)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[e]}}),dee=/^\s*(\[([( |x])?\])\s$/,uee=Gn.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{const t=e.getAttribute("data-checked");return t===""||t==="true"},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:e,HTMLAttributes:t}){return["li",an(this.options.HTMLAttributes,t,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:e.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(e,t)=>{const n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode("paragraph",{},t.parseInline(e.tokens))):e.text?n.push(t.createNode("paragraph",{},[t.createNode("text",{text:e.text})])):n.push(t.createNode("paragraph",{},[])),e.nestedTokens&&e.nestedTokens.length>0){const r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode("taskItem",{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>{var n;const s=`- [${(n=e.attrs)!=null&&n.checked?"x":" "}] `;return u0(e,t,s)},addKeyboardShortcuts(){const e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{const s=document.createElement("li"),i=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),c=document.createElement("div"),d=p=>{var h,f;l.ariaLabel=((f=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:f.call(h,p,l.checked))||`Task item checkbox for ${p.textContent||"empty task item"}`};d(e),i.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",p=>p.preventDefault()),l.addEventListener("change",p=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:h}=p.target;r.isEditable&&typeof n=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{const g=n();if(typeof g!="number")return!1;const x=f.doc.nodeAt(g);return f.setNodeMarkup(g,void 0,{...x?.attrs,checked:h}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,h)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([p,h])=>{s.setAttribute(p,h)}),s.dataset.checked=e.attrs.checked,l.checked=e.attrs.checked,i.append(l,o),s.append(i,c),Object.entries(t).forEach(([p,h])=>{s.setAttribute(p,h)});let u=new Set(Object.keys(t));return{dom:s,contentDOM:c,update:p=>{if(p.type!==this.type)return!1;s.dataset.checked=p.attrs.checked,l.checked=p.attrs.checked,d(p);const h=r.extensionManager.attributes,f=cf(p,h),g=new Set(Object.keys(f)),x=this.options.HTMLAttributes;return u.forEach(b=>{g.has(b)||(b in x?s.setAttribute(b,x[b]):s.removeAttribute(b))}),Object.entries(f).forEach(([b,y])=>{y==null?b in x?s.setAttribute(b,x[b]):s.removeAttribute(b):s.setAttribute(b,y)}),u=g,!0}}}},addInputRules(){return[dl({find:dee,type:this.type,getAttributes:e=>({checked:e[e.length-1]==="x"})})]}}),pee=Gn.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:e}){return["ul",an(this.options.HTMLAttributes,e,{"data-type":this.name}),0]},parseMarkdown:(e,t)=>t.createNode("taskList",{},t.parseChildren(e.items||[])),renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,` 79`):"",markdownTokenizer:{name:"taskList",level:"block",start(e){var t;const n=(t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:t.index;return n!==void 0?n:-1},tokenize(e,t,n){const r=i=>{const o=yy(i,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,c)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:n.inlineTokens(l.mainContent),nestedTokens:c}),customNestedParser:r},n);return o?[{type:"taskList",raw:o.raw,items:o.items}]:n.blockTokens(i)},s=yy(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:i=>({indentLevel:i[1].length,mainContent:i[4],checked:i[3].toLowerCase()==="x"}),createToken:(i,o)=>({type:"taskItem",raw:"",mainContent:i.mainContent,indentLevel:i.indentLevel,checked:i.checked,text:i.mainContent,tokens:n.inlineTokens(i.mainContent),nestedTokens:o}),customNestedParser:r},n);if(s)return{type:"taskList",raw:s.raw,items:s.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}}
79,addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});ln.create({name:"listKit",addExtensions(){const e=[];return this.options.bulletList!==!1&&e.push(jO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(kO.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(AO.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(RO.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(uee.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(pee.configure(this.options.taskList)),e}});function uf(e){return e==="left"||e==="right"||e==="center"?e:null}function hee(e){const t=(e.style.textAlign||"").trim().toLowerCase(),n=(e.getAttribute("align")||"").trim().toLowerCase();return uf(t||n)}function fee(e){return uf(e?.align)}function NO(){return{default:null,parseHTML:e=>hee(e),renderHTML:e=>e.align?{style:`text-align: ${e.align}`}:{}}}var mee=Gn.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{var t,n;const r=e.getAttribute("colwidth"),s=r?r.split(",").map(i=>parseInt(i,10)):null;if(!s){const i=(t=e.closest("table"))==null?void 0:t.querySelectorAll("colgroup > col"),o=Array.from(((n=e.parentElement)==null?void 0:n.children)||[]).indexOf(e);if(o&&o>-1&&i&&i[o]){const l=i[o].getAttribute("width");return l?[parseInt(l,10)]:null}}return s}},align:NO()}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:e}){return["td",an(this.options.HTMLAttributes,e),0]}}),gee=Gn.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}},align:NO()}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:e}){return["th",an(this.options.HTMLAttributes,e),0]}}),xee=Gn.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:e}){return["tr",an(this.options.HTMLAttributes,e),0]}});function _y(e,t){return t?["width",`${Math.max(t,e)}px`]:["min-width",`${e}px`]}function K1(e,t,n,r,s,i){var o;let l=0,c=!0,d=t.firstChild;const u=e.firstChild;if(u!==null)for(let h=0,f=0;h<u.childCount;h+=1){const{colspan:g,colwidth:x}=u.child(h).attrs;for(let b=0;b<g;b+=1,f+=1){const y=s===f?i:x&&x[b],v=y?`${y}px`:"";if(l+=y||r,y||(c=!1),d){if(d.style.width!==v){const[C,w]=_y(r,y);d.style.setProperty(C,w)}d=d.nextSibling}else{const C=document.createElement("col"),[w,S]=_y(r,y);C.style.setProperty(w,S),t.appendChild(C)}}}for(;d;){const h=d.nextSibling;(o=d.parentNode)==null||o.removeChild(d),d=h}const p=e.attrs.style&&typeof e.attrs.style=="string"&&/\bwidth\s*:/i.test(e.attrs.style);c&&!p?(n.style.width=`${l}px`,n.style.minWidth=""):(n.style.width="",n.style.minWidth=`${l}px`)}var bee=class{constructor(e,t){this.node=e,this.cellMinWidth=t,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),e.attrs.style&&(this.table.style.cssText=e.attrs.style),this.colgroup=this.table.appendChild(document.createElement("colgroup")),K1(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(e){return e.type!==this.node.type?!1:(this.node=e,K1(e,this.colgroup,this.table,this.cellMinWidth),!0)}ignoreMutation(e){const t=e.target,n=this.dom.contains(t),r=this.contentDOM.contains(t);return!!(n&&!r&&(e.type==="attributes"||e.type==="childList"||e.type==="characterData"))}};function yee(e,t,n,r){let s=0,i=!0;const o=[],l=e.firstChild;if(!l)return{};for(let p=0,h=0;p<l.childCount;p+=1){const{colspan:f,colwidth:g}=l.child(p).attrs;for(let x=0;x<f;x+=1,h+=1){const b=n===h?r:g&&g[x];s+=b||t,b||(i=!1);const[y,v]=_y(t,b);o.push(["col",{style:`${y}: ${v}`}])}}const c=i?`${s}px`:"",d=i?"":`${s}px`;return{colgroup:["colgroup",{},...o],tableWidth:c,tableMinWidth:d}}function Q1(e,t){return e.createAndFill()}
79function vee(e){if(e.cached.tableNodeTypes)return e.cached.tableNodeTypes;const t={};return Object.keys(e.nodes).forEach(n=>{const r=e.nodes[n];r.spec.tableRole&&(t[r.spec.tableRole]=r)}),e.cached.tableNodeTypes=t,t}function Cee(e,t,n,r,s){const i=vee(e),o=[],l=[];for(let d=0;d<n;d+=1){const u=Q1(i.cell);if(u&&l.push(u),r){const p=Q1(i.header_cell);p&&o.push(p)}}const c=[];for(let d=0;d<t;d+=1)c.push(i.row.createChecked(null,r&&d===0?o:l));return i.table.createChecked(null,c)}function wee(e){return e instanceof Qt}var bp=({editor:e})=>{const{selection:t}=e.state;if(!wee(t))return!1;let n=0;const r=ZN(t.ranges[0].$from,i=>i.type.name==="table");return r?.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(n+=1)}),n===t.ranges.length?(e.commands.deleteTable(),!0):!1},See="�";function jee(e){return(e||"").replace(/\s+/g," ").trim()}function kee(e,t,n={}){var r;const s=(r=n.cellLineSeparator)!=null?r:See;if(!e||!e.content||e.content.length===0)return"";const i=[];e.content.forEach(x=>{const b=[];x.content&&x.content.forEach(y=>{let v="";y.content&&Array.isArray(y.content)&&y.content.length>1?v=y.content.map(k=>t.renderChildren(k)).join(s):v=y.content?t.renderChildren(y.content):"";const C=jee(v),w=y.type==="tableHeader",S=fee(y.attrs);b.push({text:C,isHeader:w,align:S})}),i.push(b)});const o=i.reduce((x,b)=>Math.max(x,b.length),0);if(o===0)return"";const l=Array.from({length:o}).fill(0);i.forEach(x=>{var b;for(let y=0;y<o;y+=1){const C=(((b=x[y])==null?void 0:b.text)||"").length;C>l[y]&&(l[y]=C),l[y]<3&&(l[y]=3)}});const c=(x,b)=>x+" ".repeat(Math.max(0,b-x.length)),d=i[0],u=d.some(x=>x.isHeader),p=Array.from({length:o}).fill(null);i.forEach(x=>{var b;for(let y=0;y<o;y+=1)!p[y]&&((b=x[y])!=null&&b.align)&&(p[y]=x[y].align)});let h=` 80`;const f=Array.from({length:o}).map((x,b)=>u&&d[b]&&d[b].text||"");return h+=`| ${f.map((x,b)=>c(x,l[b])).join(" | ")} | 81`,h+=`| ${l.map((x,b)=>{const y=Math.max(3,x),v=p[b];return v==="left"?`:${"-".repeat(y)}`:v==="right"?`${"-".repeat(y)}:`:v==="center"?`:${"-".repeat(y)}:`:"-".repeat(y)}).join(" | ")} | 82`,(u?i.slice(1):i).forEach(x=>{h+=`| ${Array.from({length:o}).fill(0).map((b,y)=>c(x[y]&&x[y].text||"",l[y])).join(" | ")} | 83`}),h}var Eee=kee,_ee=Gn.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:bee,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:e,HTMLAttributes:t}){const{colgroup:n,tableWidth:r,tableMinWidth:s}=yee(e,this.options.cellMinWidth),i=t.style;function o(){return i||(r?`width: ${r}`:`min-width: ${s}`)}const l=["table",an(this.options.HTMLAttributes,t,{style:o()}),n,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},l]:l},parseMarkdown:(e,t)=>{const n=[],r=Array.isArray(e.align)?e.align:[];if(e.header){const s=[];e.header.forEach((i,o)=>{var l;const c=uf((l=r[o])!=null?l:i.align),d=c?{align:c}:{};s.push(t.createNode("tableHeader",d,[{type:"paragraph",content:t.parseInline(i.tokens)}]))}),n.push(t.createNode("tableRow",{},s))}return e.rows&&e.rows.forEach(s=>{const i=[];s.forEach((o,l)=>{var c;const d=uf((c=r[l])!=null?c:o.align),u=d?{align:d}:{};i.push(t.createNode("tableCell",u,[{type:"paragraph",content:t.parseInline(o.tokens)}]))}),n.push(t.createNode("tableRow",{},i))}),t.createNode("table",void 0,n)},renderMarkdown:(e,t)=>Eee(e,t),addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:s,editor:i})=>{const o=Cee(i.schema,e,t,n);if(s){const l=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(Ke.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>uZ(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>pZ(e,t),deleteColumn:()=>({state:e,dispatch:t})=>fZ(e,t),addRowBefore:()=>({state:e,dispatch:t})=>gZ(e,t),addRowAfter:()=>({state:e,dispatch:t})=>xZ(e,t),deleteRow:()=>({state:e,dispatch:t})=>yZ(e,t),deleteTable:()=>({state:e,dispatch:t})=>EZ(e,t),mergeCells:()=>({state:e,dispatch:t})=>M1(e,t),splitCell:()=>({state:e,dispatch:t})=>R1(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>Hd("column")(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>Hd("row")(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>jZ(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>M1(e,t)?!0:R1(e,t),setCellAttribute:(e,t)=>
83({state:n,dispatch:r})=>wZ(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>O1(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>O1(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&yO(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){const r=Qt.create(t.doc,e.anchorCell,e.headCell);t.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:bp,"Mod-Backspace":bp,Delete:bp,"Mod-Delete":bp}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[PZ({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],qZ({allowTableNodeSelection:this.options.allowTableNodeSelection})]},addNodeView(){const e=this.options.resizable&&this.editor.isEditable,t=this.options.View;return e||!t?null:({node:n,view:r})=>new t(n,this.options.cellMinWidth,r)},extendNodeSchema(e){const t={name:e.name,options:e.options,storage:e.storage};return{tableRole:It(st(e,"tableRole",t))}}});ln.create({name:"tableKit",addExtensions(){const e=[];return this.options.table!==!1&&e.push(_ee.configure(this.options.table)),this.options.tableCell!==!1&&e.push(mee.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(gee.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(xee.configure(this.options.tableRow)),e}});function m0(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var xo=m0();function OO(e){xo=e}var Aa={exec:()=>null};function bt(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(s,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(Cr.caret,"$1"),n=n.replace(s,o),r},getRegex:()=>new RegExp(n,t)};return r}var Tee=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),Cr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Iee=/^(?:[ \t]*(?:\n|$))+/,Dee=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Aee=/^ {0,3}(`{3,}
vendor: 5,282 bytes, lines 83-84
83(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Iu=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Mee=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,g0=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,PO=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,LO=bt(PO).replace(/bull/g,g0).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ree=bt(PO).replace(/bull/g,g0).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),x0=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Nee=/^[^\n]+/,b0=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Oee=bt(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",b0).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pee=bt(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,g0).getRegex(),Qm="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",y0=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Lee=bt("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",y0).replace("tag",Qm).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),FO=bt(x0).replace("hr",Iu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qm).getRegex(),Fee=bt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",FO).getRegex(),v0={blockquote:Fee,code:Dee,def:Oee,fences:Aee,heading:Mee,hr:Iu,html:Lee,lheading:LO,list:Pee,newline:Iee,paragraph:FO,table:Aa,text:Nee},J1=bt("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Iu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qm).getRegex(),$ee={...v0,lheading:Ree,table:J1,paragraph:bt(x0).replace("hr",Iu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",J1).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qm).getRegex()},zee={...v0,html:bt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",y0).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Aa,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:bt(x0).replace("hr",Iu).replace("heading",` *#{1,6} *[^ 84]`).replace("lheading",LO).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Bee=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Uee=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,$O=/^( {2,}|\\)\n(?!\s*$)/,Vee=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Nl=/[\p{P}\p{S}]/u,Jm=/[\s\p{P}\p{S}]/u,C0=/[^\s\p{P}\p{S}]/u,Wee=bt(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Jm).getRegex(),zO=/(?!~)[\p{P}\p{S}]/u,Hee=/(?!~)[\s\p{P}\p{S}]/u,qee=/(?:[^\s\p{P}\p{S}]|~)/u,Gee=bt(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("prec
84ode-",Tee?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),BO=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Yee=bt(BO,"u").replace(/punct/g,Nl).getRegex(),Kee=bt(BO,"u").replace(/punct/g,zO).getRegex(),UO="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Qee=bt(UO,"gu").replace(/notPunctSpace/g,C0).replace(/punctSpace/g,Jm).replace(/punct/g,Nl).getRegex(),Jee=bt(UO,"gu").replace(/notPunctSpace/g,qee).replace(/punctSpace/g,Hee).replace(/punct/g,zO).getRegex(),Xee=bt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,C0).replace(/punctSpace/g,Jm).replace(/punct/g,Nl).getRegex(),Zee=bt(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Nl).getRegex(),ete="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",tte=bt(ete,"gu").replace(/notPunctSpace/g,C0).replace(/punctSpace/g,Jm).replace(/punct/g,Nl).getRegex(),nte=bt(/\\(punct)/,"gu").replace(/punct/g,Nl).getRegex(),rte=bt(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ste=bt(y0).replace("(?:-->|$)","-->").getRegex(),ite=bt("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",ste).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),pf=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ate=bt(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",pf).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),VO=bt(/^!?\[(label)\]\[(ref)\]/).replace("label",pf).replace("ref",b0).getRegex(),WO=bt(/^!?\[(ref)\](?:\[\])?/).replace("ref",b0).getRegex(),ote=bt("reflink|nolink(?!\\()","g").replace("reflink",VO).replace("nolink",WO).getRegex(),X1=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,w0={_backpedal:Aa,anyPunctuation:nte,autolink:rte,blockSkip:Gee,br:$O,code:Uee,del:Aa,delLDelim:Aa,delRDelim:Aa,emStrongLDelim:Yee,emStrongRDelimAst:Qee,emStrongRDelimUnd:Xee,escape:Bee,link:ate,nolink:WO,punctuation:Wee,reflink:VO,reflinkSearch:ote,tag:ite,text:Vee,url:Aa},lte={...w0,link:bt(/^!?\[(label)\]\((.*?)\)/).replace("label",pf).getRegex(),reflink:bt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",pf).getRegex()},Ty={...w0,emStrongRDelimAst:Jee,emStrongLDelim:Kee,delLDelim:Zee,delRDelim:tte,url:bt(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",X1).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:bt(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",X1).getRegex()},cte={...Ty,br:bt($O).replace("{2,}","*").getRegex(),text:bt(Ty.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},yp={normal:v0,gfm:$ee,pedantic:zee},hc={normal:w0,gfm:Ty,breaks:cte,pedantic:lte},dte={"&":"&","<":"<",">":">",'"':""","'":"'"},Z1=e=>dte[e];function As(e,t){if(t){if(Cr.escapeTest.test(e))return e.replace(Cr.escapeReplace,Z1)}else if(Cr.escapeTestNoEncode.test(e))return e.replace(Cr.escapeReplaceNoEncode,Z1);return e}function eE(e){try{e=encodeURI(e).replace(Cr.percentDecode,"%")}catch{return null}return e}function tE(e,t){let n=e.replace(Cr.findPipe,(i,o,l)=>{let c=!1,d=o;for(;--d>=0&&l[d]==="\\";)c=!c;return c?"|":" |"}),r=n.split(Cr.splitPipe),s=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;s<r.length;s++)r[s]=r[s].trim().replace(Cr.slashPipe,"|");return r}
vendor: 24,205 bytes, lines 84-140
84function fc(e,t,n){let r=e.length;if(r===0)return"";let s=0;for(;s<r&&e.charAt(r-s-1)===t;)s++;return e.slice(0,r-s)}function ute(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function pte(e,t=0){let n=t,r="";for(let s of e)if(s===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=s,n++;return r}function nE(e,t,n,r,s){let i=t.href,o=t.title||null,l=e[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,c}function hte(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let s=r[1];return t.split(` 85`).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[l]=o;return l.length>=s.length?i.slice(s.length):i}).join(` 86`)}var hf=class{options;rules;lexer;constructor(t){this.options=t||xo}space(t){let n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){let n=this.rules.block.code.exec(t);if(n){let r=n[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:fc(r,` 87`)}}}fences(t){let n=this.rules.block.fences.exec(t);if(n){let r=n[0],s=hte(r,n[3]||"",this.rules);return{type:"code",raw:r,lang:n[2]?n[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):n[2],text:s}}}heading(t){let n=this.rules.block.heading.exec(t);if(n){let r=n[2].trim();if(this.rules.other.endingHash.test(r)){let s=fc(r,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(r=s.trim())}return{type:"heading",raw:n[0],depth:n[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){let n=this.rules.block.hr.exec(t);if(n)return{type:"hr",raw:fc(n[0],` 88`)}}blockquote(t){let n=this.rules.block.blockquote.exec(t);if(n){let r=fc(n[0],` 89`).split(` 90`),s="",i="",o=[];for(;r.length>0;){let l=!1,c=[],d;for(d=0;d<r.length;d++)if(this.rules.other.blockquoteStart.test(r[d]))c.push(r[d]),l=!0;else if(!l)c.push(r[d]);else break;r=r.slice(d);let u=c.join(` 91`),p=u.replace(this.rules.other.blockquoteSetextReplace,` 92 $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s} 93${u}`:u,i=i?`${i} 94${p}`:p;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,o,!0),this.lexer.state.top=h,r.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let g=f,x=g.raw+` 95`+r.join(` 96`),b=this.blockquote(x);o[o.length-1]=b,s=s.substring(0,s.length-g.raw.length)+b.raw,i=i.substring(0,i.length-g.text.length)+b.text;break}else if(f?.type==="list"){let g=f,x=g.raw+` 97`+r.join(` 98`),b=this.list(x);o[o.length-1]=b,s=s.substring(0,s.length-f.raw.length)+b.raw,i=i.substring(0,i.length-g.raw.length)+b.raw,r=x.substring(o.at(-1).raw.length).split(` 99`);continue}}return{type:"blockquote",raw:s,tokens:o,text:i}}}list(t){let n=this.rules.block.list.exec(t);if(n){let r=n[1].trim(),s=r.length>1,i={type:"list",raw:"",ordered:s,start:s?+r.slice(0,-1):"",loose:!1,items:[]};r=s?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=s?r:"[*+-]");let o=this.rules.other.listItemRegex(r),l=!1;for(;t;){let d=!1,u="",p="";if(!(n=o.exec(t))||this.rules.block.hr.test(t))break;u=n[0],t=t.substring(u.length);let h=pte(n[2].split(` 100`,1)[0],n[1].length),f=t.split(` 101`,1)[0],g=!h.trim(),x=0;if(this.options.pedantic?(x=2,p=h.trimStart()):g?x=n[1].length+1:(x=h.search(this.rules.other.nonSpaceChar),x=x>4?1:x,p=h.slice(x),x+=n[1].length),g&&this.rules.other.blankLine.test(f)&&(u+=f+` 102`,t=t.substring(f.length+1),d=!0),!d){let b=this.rules.other.nextBulletRegex(x),y=this.rules.other.hrRegex(x),v=this.rules.other.fencesBeginRegex(x),C=this.rules.other.headingBeginRegex(x),w=this.rules.other.htmlBeginRegex(x),S=this.rules.other.blockquoteBeginRegex(x);for(;t;){let E=t.split(` 103`,1)[0],k;if(f=E,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),k=f):k=f.replace(this.rules.other.tabCharGlobal," "),v.test(f)||C.test(f)||w.test(f)||S.test(f)||b.test(f)||y.test(f))break;if(k.search(this.rules.other.nonSpaceChar)>=x||!f.trim())p+=` 104`+k.slice(x);else{if(g||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||v.test(h)||C.test(h)||y.test(h))break;p+=` 105`+f}g=!f.trim(),u+=E+` 106`,t=t.substring(E.length+1),h=k.slice(x)}}i.loose||(l?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(l=!0)),i.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),i.raw+=u}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let d of i.items){if(this.lexer.state.top=!1,d.tokens=this.lexer.blockTokens(d.text,[]),d.task){if(d.text=d.text.replace(this.rules.other.listReplaceTask,""),d.tokens[0]?.type==="text"||d.tokens[0]?.type==="paragraph"){d.tokens[0].raw=d.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),d.tokens[0].text=d.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let u=this.rules.other.listTaskCheckbox.exec(d.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};d.checked=p.checked,i.loose?d.tokens[0]&&["paragraph","text"].includes(d.tokens[0].type)&&"tokens"in d.tokens[0]&&d.tokens[0].tokens?(d.tokens[0].raw=p.raw+d.tokens[0].raw,d.tokens[0].text=p.raw+d.tokens[0].text,d.tokens[0].tokens.unshift(p)):d.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):d.tokens.unshift(p)}}if(!i.loose){let u=d.tokens.filter(h=>h.type==="space"),p=u.length>0&&u.some(h=>this.rules.other.anyLine.test(h.raw));i.loose=p}}if(i.loose)for(let d of i.items){d.loose=!0;for(let u of d.tokens)u.type==="text"&&(u.type="paragraph")}return i}}html(t){let n=this.rules.block.html.exec(t);if(n)return{type:"html",block:!0,raw:n[0],pre:n[1]==="pre"||n[1]==="script"||n[1]==="style",text:n[0]}}def(t){let n=this.rules.block.def.exec(t);if(n){let r=n[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=n[2]?n[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:s,title:i}}}table(t){let n=this.rules.block.table.exec(t);if(!n||!this.rules.other.tableDelimiter.test(n[2]))return;let r=tE(n[1]),s=n[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=n[3]?.trim()?n[3].replace(this.rules.other.tableRowBlankLine,"").split(` 107`):[],o={type:"table",raw:n[0],header:[],align:[],rows:[]};if(r.length===s.length){for(let l of s)this.rules.other.tableAlignRight.test(l)?o.align.push("right"):this.rules.other.tableAlignCenter.test(l)?o.align.push("center"):this.rules.other.tableAlignLeft.test(l)?o.align.push("left"):o.align.push(null);for(let l=0;l<r.length;l++)o.header.push({text:r[l],tokens:this.lexer.inline(r[l]),header:!0,align:o.align[l]});for(let l of i)o.rows.push(tE(l,o.header.length).map((c,d)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:o.align[d]})));return o}}lheading(t){let n=this.rules.block.lheading.exec(t);if(n){let r=n[1].trim();return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(t){let n=this.rules.block.paragraph.exec(t);if(n){let r=n[1].charAt(n[1].length-1)===` 108`?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){let n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:n[1]}}tag(t){let n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&this.rules.other.startATag.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:n[0]}}link(t){let n=this.rules.inline.link.exec(t);if(n){let r=n[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let o=fc(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=ute(n[2],"()");if(o===-2)return;if(o>-1){let l=(n[0].indexOf("!")===0?5:4)+n[1].length+o;n[2]=n[2].substring(0,o),n[0]=n[0].substring(0,l).trim(),n[3]=""}}let s=n[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],i=o[3])}else i=n[3]?n[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?s=s.slice(1):s=s.slice(1,-1)),nE(n,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},n[0],this.lexer,this.rules)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let s=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=n[s.toLowerCase()];if(!i){let o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return nE(r,i,r[0],this.lexer,this.rules)}}emStrong(t,n,r=""){let s=this.rules.inline.emStrongLDelim.exec(t);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...s[0]].length-1,o,l,c=i,d=0,u=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,n=n.slice(-1*t.length+i);(s=u.exec(n))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(l=[...o].length,s[3]||s[4]){c+=l;continue}else if((s[5]||s[6])&&i%3&&!((i+l)%3)){d+=l;continue}if(c-=l,c>0)continue;l=Math.min(l,l+c+d);let p=[...s[0]][0].length,h=t.slice(0,i+s.index+p+l);if(Math.min(i,l)%2){let g=h.slice(1,-1);return{type:"em",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(t){let n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return s&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:n[0],text:r}}}br(t){let n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t,n,r=""){let s=this.rules.inline.delLDelim.exec(t);if(s&&(!s[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...s[0]].length-1,o,l,c=i,d=this.rules.inline.delRDelim;for(d.lastIndex=0,n=n.slice(-1*t.length+i);(s=d.exec(n))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(l=[...o].length,l!==i))continue;if(s[3]||s[4]){c+=l;continue}if(c-=l,c>0)continue;l=Math.min(l,l+c);let u=[...s[0]][0].length,p=t.slice(0,i+s.index+u+l),h=p.slice(i,-i);return{type:"del",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(t){let n=this.rules.inline.autolink.exec(t);if(n){let r,s;return n[2]==="@"?(r=n[1],s="mailto:"+r):(r=n[1],s=r),{type:"link",raw:n[0],text:r,href:s,tokens:[{type:"text",raw:r,text:r}]}}}url(t){let n;if(n=this.rules.inline.url.exec(t)){let r,s;if(n[2]==="@")r=n[0],s="mailto:"+r;else{let i;do i=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])?.[0]??"";while(i!==n[0]);r=n[0],n[1]==="www."?s="http://"+n[0]:s=n[0]}return{type:"link",raw:n[0],text:r,href:s,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(t){let n=this.rules.inline.text.exec(t);if(n){let r=this.lexer.state.inRawBlock;return{type:"text",raw:n[0],text:n[0],escaped:r}}}},ls=class Iy{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||xo,this.options.tokenizer=this.options.tokenizer||new hf,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Cr,block:yp.normal,inline:hc.normal};this.options.pedantic?(n.block=yp.pedantic,n.inline=hc.pedantic):this.options.gfm&&(n.block=yp.gfm,this.options.breaks?n.inline=hc.breaks:n.inline=hc.gfm),this.tokenizer.rules=n}static get rules(){return{block:yp,inline:hc}}static lex(t,n){return new Iy(n).lex(t)}static lexInline(t,n){return new Iy(n).inlineTokens(t)}lex(t){t=t.replace(Cr.carriageReturn,` 109`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Cr.tabCharGlobal," ").replace(Cr.spaceLine,""));t;){let s;if(this.options.extensions?.block?.some(o=>(s=o.call({lexer:this},t,n))?(t=t.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(t)){t=t.substring(s.raw.length);let o=n.at(-1);s.raw.length===1&&o!==void 0?o.raw+=` 110`:n.push(s);continue}if(s=this.tokenizer.code(t)){t=t.substring(s.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` 111`)?"":` 112`)+s.raw,o.text+=` 113`+s.text,this.inlineQueue.at(-1).src=o.text):n.push(s);continue}if(s=this.tokenizer.fences(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(t)){t=t.substring(s.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` 114`)?"":` 115`)+s.raw,o.text+=` 116`+s.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(t)){t=t.substring(s.raw.length),n.push(s);continue}let i=t;if(this.options.extensions?.startBlock){let o=1/0,l=t.slice(1),c;this.options.extensions.startBlock.forEach(d=>{c=d.call({lexer:this},l),typeof c=="number"&&c>=0&&(o=Math.min(o,c))}),o<1/0&&o>=0&&(i=t.substring(0,o+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let o=n.at(-1);r&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` 117`)?"":` 118`)+s.raw,o.text+=` 119`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(s),r=i.length!==t.length,t=t.substring(s.raw.length);continue}if(s=this.tokenizer.text(t)){t=t.substring(s.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` 120`)?"":` 121`)+s.raw,o.text+=` 122`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(s);continue}if(t){let o="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t,s=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)i=s[2]?s[2].length:0,r=r.slice(0,s.index+i)+"["+"a".repeat(s[0].length-i-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,l="";for(;t;){o||(l=""),o=!1;let c;if(this.options.extensions?.inline?.some(u=>(c=u.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let u=n.at(-1);c.type==="text"&&u?.type==="text"?(u.raw+=c.raw,u.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,r,l)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,r,l)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let d=t;if(this.options.extensions?.startInline){let u=1/0,p=t.slice(1),h;this.options.extensions.startInline.forEach(f=>{h=f.call({lexer:this},p),typeof h=="number"&&h>=0&&(u=Math.min(u,h))}),u<1/0&&u>=0&&(d=t.substring(0,u+1))}if(c=this.tokenizer.inlineText(d)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(l=c.raw.slice(-1)),o=!0;let u=n.at(-1);u?.type==="text"?(u.raw+=c.raw,u.text+=c.text):n.push(c);continue}if(t){let u="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return n}},ff=class{options;parser;constructor(t){this.options=t||xo}space(t){return""}code({text:t,lang:n,escaped:r}){let s=(n||"").match(Cr.notSpaceStart)?.[0],i=t.replace(Cr.endingNewline,"")+` 123`;return s?'<pre><code class="language-'+As(s)+'">'+(r?i:As(i,!0))+`</code></pre> 124`:"<pre><code>"+(r?i:As(i,!0))+`</code></pre> 125`}blockquote({tokens:t}){return`<blockquote> 126${this.parser.parse(t)}</blockquote> 127`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:n}){return`<h${n}>${this.parser.parseInline(t)}</h${n}> 128`}hr(t){return`<hr> 129`}list(t){let n=t.ordered,r=t.start,s="";for(let l=0;l<t.items.length;l++){let c=t.items[l];s+=this.listitem(c)}let i=n?"ol":"ul",o=n&&r!==1?' start="'+r+'"':"";return"<"+i+o+`> 130`+s+"</"+i+`> 131`}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li> 132`}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p> 133`}table(t){let n="",r="";for(let i=0;i<t.header.length;i++)r+=this.tablecell(t.header[i]);n+=this.tablerow({text:r});let s="";for(let i=0;i<t.rows.length;i++){let o=t.rows[i];r="";for(let l=0;l<o.length;l++)r+=this.tablecell(o[l]);s+=this.tablerow({text:r})}return s&&(s=`<tbody>${s}</tbody>`),`<table> 134<thead> 135`+n+`</thead> 136`+s+`</table> 137`}tablerow({text:t}){return`<tr> 138${t}</tr> 139`}tablecell(t){let n=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+n+`</${r}> 140`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${As(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:n,tokens:r}){let s=this.parser.parseInline(r),i=eE(t);if(i===null)return s;t=i;let o='<a href="'+t+'"';return n&&(o+=' title="'+As(n)+'"'),o+=">"+s+"</a>",o}image({href:t,title:n,text:r,tokens:s}){s&&(r=this.parser.parseInline(s,this.parser.textRenderer));let i=eE(t);if(i===null)return As(r);t=i;let o=`<img src="${t}" alt="${As(r)}"`;return n&&(o+=` title="${As(n)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:As(t.text)}},S0=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},cs=class Dy{options;renderer;textRenderer;constructor(t){this.options=t||xo,this.options.renderer=this.options.renderer||new ff,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new S0}static parse(t,n){return new Dy(n).parse(t)}static parseInline(t,n){return new Dy(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let s=t[r];if(this.options.extensions?.renderers?.[s.type]){let o=s,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let i=s;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let s=0;s<t.length;s++){let i=t[s];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){r+=l||"";continue}}let o=i;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},ad=class{options;block;constructor(t){this.options=t||xo}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ls.lex:ls.lexInline}provideParser(t=this.block){return t?cs.parse:cs.parseInline}},fte=class{defaults=m0();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=cs;Renderer=ff;TextRenderer=S0;Lexer=ls;Tokenizer=hf;Hooks=ad;constructor(...t){this.use(...t)}walkTokens(t,n){let r=[];for(let s of t)switch(r=r.concat(n.call(this,s)),s.type){case"table":{let i=s;for(let o of i.header)r=r.concat(this.walkTokens(o.tokens,n));for(let o of i.rows)for(let l of o)r=r.concat(this.walkTokens(l.tokens,n));break}case"list":{let i=s;r=r.concat(this.walkTokens(i.items,n));break}default:{let i=s;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let l=i[o].flat(1/0);r=r.concat(this.walkTokens(l,n))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,n)))}}return r}use(...t){let n=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let s={...r};if(s.async=this.defaults.async||s.async||!1,r.extensions&&(r.extensions.forEach(i=>
140{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=n.renderers[i.name];o?n.renderers[i.name]=function(...l){let c=i.renderer.apply(this,l);return c===!1&&(c=o.apply(this,l)),c}:n.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=n[i.level];o?o.unshift(i.tokenizer):n[i.level]=[i.tokenizer],i.start&&(i.level==="block"?n.startBlock?n.startBlock.push(i.start):n.startBlock=[i.start]:i.level==="inline"&&(n.startInline?n.startInline.push(i.start):n.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(n.childTokens[i.name]=i.childTokens)}),s.extensions=n),r.renderer){let i=this.defaults.renderer||new ff(this.defaults);for(let o in r.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let l=o,c=r.renderer[l],d=i[l];i[l]=(...u)=>{let p=c.apply(i,u);return p===!1&&(p=d.apply(i,u)),p||""}}s.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new hf(this.defaults);for(let o in r.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let l=o,c=r.tokenizer[l],d=i[l];i[l]=(...u)=>{let p=c.apply(i,u);return p===!1&&(p=d.apply(i,u)),p}}s.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new ad;for(let o in r.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let l=o,c=r.hooks[l],d=i[l];ad.passThroughHooks.has(o)?i[l]=u=>{if(this.defaults.async&&ad.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await c.call(i,u);return d.call(i,h)})();let p=c.call(i,u);return d.call(i,p)}:i[l]=(...u)=>{if(this.defaults.async)return(async()=>{let h=await c.apply(i,u);return h===!1&&(h=await d.apply(i,u)),h})();let p=c.apply(i,u);return p===!1&&(p=d.apply(i,u)),p}}s.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,o=r.walkTokens;s.walkTokens=function(l){let c=[];return c.push(o.call(this,l)),i&&(c=c.concat(i.call(this,l))),c}}this.defaults={...this.defaults,...s}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,n){return ls.lex(t,n??this.defaults)}parser(t,n){return cs.parse(t,n??this.defaults)}parseMarkdown(t){return(n,r)=>{let s={...r},i={...this.defaults,...s},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let l=i.hooks?await i.hooks.preprocess(n):n,c=await(i.hooks?await i.hooks.provideLexer(t):t?ls.lex:ls.lexInline)(l,i),d=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(d,i.walkTokens));let u=await(i.hooks?await i.hooks.provideParser(t):t?cs.parse:cs.parseInline)(d,i);return i.hooks?await i.hooks.postprocess(u):u})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let l=(i.hooks?i.hooks.provideLexer(t):t?ls.lex:ls.lexInline)(n,i);i.hooks&&(l=i.hooks.processAllTokens(l)),i.walkTokens&&this.walkTokens(l,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(t):t?cs.parse:cs.parseInline)(l,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(l){return o(l)}}}onError(t,n){return r=>{if(r.message+=` 141Please report this to https://github.com/markedjs/marked.`,t){let s="<p>An error occurred:</p><pre>"+As(r.message+"",!0)+"</pre>";return n?Promise.resolve(s):s}if(n)return Promise.reject(r);throw r}}},ao=new fte;function Rt(e,t){return ao.parse(e,t)}Rt.options=Rt.setOptions=function(e){return ao.setOptions(e),Rt.defaults=ao.defaults,OO(Rt.defaults),Rt};Rt.getDefaults=m0;Rt.defaults=xo;Rt.use=function(...e){return ao.use(...e),Rt.defaults=ao.defaults,OO(Rt.defaults),Rt};Rt.walkTokens=function(e,t){return ao.walkTokens(e,t)};Rt.parseInline=ao.parseInline;Rt.Parser=cs;Rt.parser=cs.parse;Rt.Renderer=ff;Rt.TextRenderer=S0;Rt.Lexer=ls;Rt.lexer=ls.lex;Rt.Tokenizer=hf;Rt.Hooks=ad;Rt.parse=Rt;Rt.options;Rt.setOptions;Rt.use;Rt.walkTokens;Rt.parseInline;cs.parse;ls.lex;function mte(e,t){const r=t.split(` 142`).flatMap(s=>[s,""]).map(s=>`${e}${s}`).join(` 143`);return r.slice(0,r.length-1)}function qd(e,t){if(e===t)return!0;
143if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(t,s)&&Object.is(e[s],t[s]))}function gte(e,t){const n=[];return Array.from(e.entries()).forEach(([r,s])=>{if(!t){n.push(r);return}(t.marks||[]).find(o=>o.type===r&&qd(o.attrs,s.attrs))||n.push(r)}),n}function xte(e,t){const n=[];return Array.from(t.entries()).forEach(([r,s])=>{const i=e.get(r);(!i||!qd(i.attrs,s.attrs))&&n.push({type:r,mark:s})}),n}function bte(e,t,n,r){const s=!n,i=n&&(!n.marks||n.marks.length===0),o=n&&n.marks&&!r(t,new Map(n.marks.map(c=>[c.type,c]))),l=[];return(s||i||o)&&(n&&n.marks?Array.from(e.entries()).reverse().forEach(([c,d])=>{n.marks.find(p=>p.type===c&&qd(p.attrs,d.attrs))||l.push(c)}):(s||i)&&l.push(...Array.from(e.keys()).reverse())),l}function yte(e,t){let n="";return Array.from(e.keys()).reverse().forEach(r=>{const s=e.get(r),i=t(r,s);i&&(n=i+n)}),e.clear(),n}function vte(e,t,n){let r="";return Array.from(e.entries()).forEach(([s,i])=>{const o=n(s,i);o&&(r+=o),t.set(s,i)}),r}function hx(e){const n=(e.raw||e.text||"").match(/^(\s*)[-+*]\s+\[([ xX])\]\s+/);return n?{isTask:!0,checked:n[2].toLowerCase()==="x",indentLevel:n[1].length}:{isTask:!1,indentLevel:0}}function vp(e,t){return typeof e!="string"?"json":t}var Cte=e=>{const t=window.HTMLUnknownElement;return typeof t=="function"&&e instanceof t},wte=class{constructor(e){this.activeParseLexer=null,this.extensionRanks=new Map,this.baseExtensions=[],this.extensions=[],this.codeTypes=new Set,this.schemaParseDomTagsCache=null,this.lastParseResult=null;var t,n,r,s,i;this.markedInstance=(t=e?.marked)!=null?t:Rt,this.indentStyle=(r=(n=e?.indentation)==null?void 0:n.style)!=null?r:"space",this.indentSize=(i=(s=e?.indentation)==null?void 0:s.size)!=null?i:2,this.baseExtensions=e?.extensions||[],e?.markedOptions&&typeof this.markedInstance.setOptions=="function"&&this.markedInstance.setOptions(e.markedOptions),this.registry=new Map,this.nodeTypeRegistry=new Map,e?.extensions&&(this.baseExtensions=e.extensions,eO(a0(e.extensions)).forEach(l=>this.registerExtension(l)))}get instance(){return this.markedInstance}get indentCharacter(){return this.indentStyle==="space"?" ":" "}get indentString(){return this.indentCharacter.repeat(this.indentSize)}hasMarked(){return!!this.markedInstance}registerExtension(e){var t,n;this.extensions.push(e);const r=It(st(e,"code")),s=e.name;r&&this.codeTypes.add(s),this.extensionRanks.has(s)||this.extensionRanks.set(s,this.extensionRanks.size);const i=st(e,"markdownTokenName")||s,o=st(e,"parseMarkdown"),l=st(e,"renderMarkdown"),c=st(e,"markdownTokenizer"),d=(t=st(e,"markdownOptions"))!=null?t:null,u=(n=d?.indentsContent)!=null?n:!1,p=d?.htmlReopen,h={tokenName:i,nodeName:s,parseMarkdown:o,renderMarkdown:l,isIndenting:u,htmlReopen:p,tokenizer:c};if(i&&o){const f=this.registry.get(i)||[];f.push(h),this.registry.set(i,f)}if(l){const f=this.nodeTypeRegistry.get(s)||[];f.push(h),this.nodeTypeRegistry.set(s,f)}c&&this.hasMarked()&&this.registerTokenizer(c)}createLexer(){return new this.markedInstance.Lexer}createTokenizerHelpers(e){return{inlineTokens:t=>e.inlineTokens(t),blockTokens:t=>e.blockTokens(t)}}tokenizeInline(e){var t;return((t=this.activeParseLexer)!=null?t:this.createLexer()).inlineTokens(e)}registerTokenizer(e){if(!this.hasMarked())return;const{name:t,start:n,level:r="inline",tokenize:s}=e,i=this.createTokenizerHelpers.bind(this),o=this.createLexer.bind(this);let l;n?l=typeof n=="function"?n:d=>d.indexOf(n):l=d=>{const u=s(d,[],this.createTokenizerHelpers(this.createLexer()));return u&&u.raw?d.indexOf(u.raw):-1};const c={name:t,level:r,start:l,tokenizer(d,u){const p=this.lexer?i(this.lexer):i(o()),h=s(d,u,p);if(h&&h.type)return{...h,type:h.type||t,raw:h.raw||"",tokens:h.tokens||[]}},childTokens:[]};this.markedInstance.use({extensions:[c]})}getHandlersForToken(e){try{return this.registry.get(e)||[]}catch{return[]}}getHandlerForToken(e){const t=this.getHandlersForToken(e);if(t.length>0)return t[0];const n=this.getHandlersForNodeType(e);return n.length>0?n[0]:void 0}getHandlersForNodeType(e){try{return this.nodeTypeRegistry.get(e)||[]}catch{return[]}}serialize(e){if(!e)return"";const t=this.renderNodes(e,e);return this.isEmptyOutput(t)?"":t}isEmptyOutput(e){return!e||e.trim()===""?!0:e.replace(/ /g,"").replace(/\u00A0/g,"").trim()===""}parse(e){if(!this.hasMarked())throw new Error("No marked instance available for parsing");const t=this.activeParseLexer,n=this.createLexer();this.activeParseLexer=n;try{const r=n.lex(e);return{type:"doc",content:this.parseTokens(r,!0)}}finally{this.activeParseLexer=t}}parseTokens(e,t=!1){const n=e.reduce((i,o,l)=>(o.type!=="space"&&i.push(l),i),[]);let r=-1,s=0;return e.flatMap((i,o)=>{for(var l;s<n.length&&n[s]<o;)r=n[s],s+=1;if(t&&i.type==="space"){const d=(l=n[s])!=null?l:-1;return this.createImplicitEmptyParagraphsFromSpace(i,r,d)}const c=this.parseToken(i,t);return c===null?[]:Array.isArray(c)?c:[c]})}createImplicitEmptyParagraphsFromSpace(e,t,n){const r=this.countParagraphSeparators(e.raw||"");if(r===0)return[];const i=Math.max(r-(t===-1||n===-1?0:1),0);return Array.from({length:i},()=>({type:"paragraph",content:[]}))}countParagraphSeparators(e){return(e.replace(/\r\n/g,` 144`).match(/\n\n/g)||[]).length}parseToken(e,t=!1){if(!e.type)return null;if(e.type==="list")return this.parseListToken(e);const n=this.getHandlersForToken(e.type),r=this.createParseHelpers();if(n.find(i=>{if(!i.parseMarkdown)return!1;const o=i.parseMarkdown(e,r),l=this.normalizeParseResult(o);return l&&(!Array.isArray(l)||l.length>0)?(this.lastParseResult=l,!0):!1})&&this.lastParseResult){const i=this.lastParseResult;return this.lastParseResult=null,i}return this.parseFallbackToken(e,t)}parseListToken(e){if(!e.items||e.items.length===0)return this.parseTokenWithHandlers(e);const t=e.items.some(l=>hx(l).isTask),n=e.items.some(l=>!hx(l).isTask);if(!t||!n||this.getHandlersForToken("taskList").length===0)return this.parseTokenWithHandlers(e);const r=[];let s=[],i=null;for(let l=0;l<e.items.length;l+=1){const c=e.items[l],{isTask:d,checked:u,indentLevel:p}=hx(c);let h=c;if(d){const x=(c.raw||c.text||"").split(` 145`),b=x[0].match(/^\s*[-+*]\s+\[([ xX])\]\s+(.*)$/),y=b?b[2]:"";let v=[];
145if(x.length>1&&x.slice(1).join(` 146`).trim()){const w=x.slice(1),S=w.filter(E=>E.trim());if(S.length>0){const E=Math.min(...S.map(_=>_.length-_.trimStart().length)),j=w.map(_=>_.trim()?_.slice(E):"").join(` 147`).trim();j&&(v=this.markedInstance.lexer(`${j} 148`))}}h={type:"taskItem",raw:"",mainContent:y,indentLevel:p,checked:u??!1,text:y,tokens:this.tokenizeInline(y),nestedTokens:v}}const f=d?"taskList":"list";i!==f?(s.length>0&&r.push({type:i,items:s}),s=[h],i=f):s.push(h)}s.length>0&&r.push({type:i,items:s});const o=[];for(let l=0;l<r.length;l+=1){const c=r[l],d={...e,type:c.type,items:c.items},u=this.parseToken(d);u&&(Array.isArray(u)?o.push(...u):o.push(u))}return o.length>0?o:null}parseTokenWithHandlers(e){if(!e.type)return null;const t=this.getHandlersForToken(e.type),n=this.createParseHelpers();if(t.find(s=>{if(!s.parseMarkdown)return!1;const i=s.parseMarkdown(e,n),o=this.normalizeParseResult(i);return o&&(!Array.isArray(o)||o.length>0)?(this.lastParseResult=o,!0):!1})&&this.lastParseResult){const s=this.lastParseResult;return this.lastParseResult=null,s}return this.parseFallbackToken(e)}createParseHelpers(){return{parseInline:e=>this.parseInlineTokens(e),tokenizeInline:e=>this.tokenizeInline(e),parseChildren:e=>this.parseTokens(e),parseBlockChildren:e=>this.parseTokens(e,!0),createTextNode:(e,t)=>({type:"text",text:e,marks:t||void 0}),createNode:(e,t,n)=>{const r={type:e,attrs:t||void 0,content:n||void 0};return(!t||Object.keys(t).length===0)&&delete r.attrs,r},applyMark:(e,t,n)=>({mark:e,content:t,attrs:n&&Object.keys(n).length>0?n:void 0})}}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}parseInlineTokens(e){var t,n,r,s;const i=[];for(let o=0;o<e.length;o+=1){const l=e[o];if(l.type==="text")i.push({type:"text",text:T1(l.text||"")});else if(l.type==="html"){const c=((n=(t=l.raw)!=null?t:l.text)!=null?n:"").toString(),d=/^<\/[\s]*[\w-]+/i.test(c),u=c.match(/^<[\s]*([\w-]+)(\s|>|\/|$)/i);if(!d&&u&&!/\/>$/.test(c)){const h=u[1],f=this.escapeRegex(h),g=new RegExp(`^<\\/\\s*${f}\\b`,"i");let x=-1;const b=[c];for(let y=o+1;y<e.length;y+=1){const v=e[y],C=((s=(r=v.raw)!=null?r:v.text)!=null?s:"").toString();if(b.push(C),v.type==="html"&&g.test(C)){x=y;break}}if(x!==-1){const y=b.join(""),v={type:"html",raw:y,text:y,block:!1},C=this.parseHTMLToken(v);if(C){const w=this.normalizeParseResult(C);Array.isArray(w)?i.push(...w):w&&i.push(w)}o=x;continue}}const p=this.parseHTMLToken(l);if(p){const h=this.normalizeParseResult(p);Array.isArray(h)?i.push(...h):h&&i.push(h)}}else if(l.type){const c=this.getHandlerForToken(l.type);if(c&&c.parseMarkdown){const d=this.createParseHelpers(),u=c.parseMarkdown(l,d);if(this.isMarkResult(u)){const p=this.applyMarkToContent(u.mark,u.content,u.attrs);i.push(...p)}else{const p=this.normalizeParseResult(u);Array.isArray(p)?i.push(...p):p&&i.push(p)}}else l.tokens&&i.push(...this.parseInlineTokens(l.tokens))}}return i}applyMarkToContent(e,t,n){return t.map(r=>{if(r.type==="text"){const s=r.marks||[],i=n?{type:e,attrs:n}:{type:e};return{...r,marks:[...s,i]}}return{...r,content:r.content?this.applyMarkToContent(e,r.content,n):void 0}})}isMarkResult(e){return e&&typeof e=="object"&&"mark"in e}normalizeParseResult(e){return e?this.isMarkResult(e)?e.content:e:null}parseFallbackToken(e,t=!1){switch(e.type){case"paragraph":return{type:"paragraph",content:e.tokens?this.parseInlineTokens(e.tokens):[]};case"heading":return{type:"heading",attrs:{level:e.depth||1},content:e.tokens?this.parseInlineTokens(e.tokens):[]};case"text":return{type:"text",text:T1(e.text||"")};case"html":return this.parseHTMLToken(e);case"space":return null;default:return e.tokens?this.parseTokens(e.tokens,t):null}}parseHTMLToken(e){const t=e.text||e.raw||"";if(!t.trim())return null;if(typeof window>"u")return e.block?{type:"paragraph",content:[{type:"text",text:t}]}:{type:"text",text:t};if(this.isUnrecognizedHtml(t))return this.htmlAsLiteralText(t,!!e.block);try{const n=AJ(t,this.baseExtensions);return n.type==="doc"&&n.content?e.block?n.content:n.content.length===1&&n.content[0].type==="paragraph"&&n.content[0].content?n.content[0].content:n.content:n}catch(n){throw new Error(`Failed to parse HTML in markdown: ${n}`)}}isUnrecognizedHtml(e){if(typeof window>"u"||typeof window.DOMParser>"u")return!1;const n=new window.DOMParser().parseFromString(`<body>${e}</body>`,"text/html").body.querySelectorAll("*");if(n.length===0)return!1;const r=this.getSchemaParseDomTags();return Array.from(n).some(s=>{if(!Cte(s))return!1;const i=s.tagName.toLowerCase();return!r.has(i)})}getSchemaParseDomTags(){if(this.schemaParseDomTagsCache)return this.schemaParseDomTagsCache;const e=new Set;try{const t=tO(this.baseExtensions),n=r=>{const s=r?.parseDOM;
148Array.isArray(s)&&s.forEach(i=>{if(typeof i?.tag=="string"){const o=i.tag.match(/^[a-zA-Z][\w-]*/);o&&e.add(o[0].toLowerCase())}})};Object.values(t.nodes).forEach(r=>n(r.spec)),Object.values(t.marks).forEach(r=>n(r.spec))}catch{}return this.schemaParseDomTagsCache=e,e}htmlAsLiteralText(e,t){const n=e.replace(/\s+$/,"");return n?t?{type:"paragraph",content:[{type:"text",text:n}]}:{type:"text",text:n}:null}encodeTextForMarkdown(e,t,n){return n?.type!=null&&this.codeTypes.has(n.type)||(t.marks||[]).some(s=>this.codeTypes.has(typeof s=="string"?s:s.type))?e:TX(e)}renderNodeToMarkdown(e,t,n=0,r=0,s={}){var i;if(e.type==="text")return this.encodeTextForMarkdown(e.text||"",e,t);if(!e.type)return"";const o=this.getHandlerForToken(e.type);if(!o)return"";const l=Array.isArray(t?.content)&&n>0?t.content[n-1]:void 0,c={renderChildren:(p,h)=>{const f=o.isIndenting?r+1:r;return!Array.isArray(p)&&p.content?this.renderNodes(p.content,e,h||"",n,f):this.renderNodes(p,e,h||"",n,f)},renderChild:(p,h)=>{const f=o.isIndenting?r+1:r;return this.renderNodeToMarkdown(p,e,h,f)},indent:p=>this.indentString+p,wrapInBlock:mte},d={index:n,level:r,parentType:t?.type,previousNode:l,meta:{parentAttrs:t?.attrs,...s}};return((i=o.renderMarkdown)==null?void 0:i.call(o,e,c,d))||""}renderNodes(e,t,n="",r=0,s=0){return Array.isArray(e)?this.renderNodesWithMarkBoundaries(e,t,n,s):e.type?this.renderNodeToMarkdown(e,t,r,s):""}renderNodesWithMarkBoundaries(e,t,n="",r=0){const s=[],i=new Map,o=new Set,l=new Map;return e.forEach((c,d)=>{const u=d<e.length-1?e[d+1]:null;if(c.type)if(c.type==="text"){let p=this.encodeTextForMarkdown(c.text||"",c,t);const h=new Map((c.marks||[]).map(S=>[S.type,S])),f=this.getMarksToOpenForSerialization(i,h,u),g=gte(h,u),x=g.filter(S=>i.has(S)),b=x.length>0&&f.length>0;let y="";if(g.length>0&&!b){const S=p.match(/(\s+)$/);S&&(y=S[1],p=p.slice(0,-y.length))}b||g.slice().reverse().forEach(S=>{if(!i.has(S))return;const E=h.get(S),k=this.getMarkClosing(S,E,l.get(S));k&&(p+=k),i.has(S)&&(i.delete(S),l.delete(S))});let v="";if(f.length>0){const S=p.match(/^(\s+)/);S&&(v=S[1],p=p.slice(v.length))}f.forEach(({type:S,mark:E})=>{const k=o.has(S)?"html":"markdown",j=this.getMarkOpening(S,E,k);j&&(p=j+p),l.set(S,k),o.delete(S)}),b||f.slice().reverse().forEach(({type:S,mark:E})=>{i.set(S,E)}),p=v+p;let C;if(b){const S=new Set((u?.marks||[]).map(j=>j.type));f.forEach(({type:j})=>{S.has(j)&&this.getHtmlReopenTags(j)&&o.add(j)});const E=Array.from(i.keys()),k=x.slice().sort((j,_)=>E.indexOf(_)-E.indexOf(j));C=[...f.map(j=>j.type),...k]}else C=bte(i,h,u,this.markSetsEqual.bind(this));let w="";if(C.length>0){const S=p.match(/(\s+)$/);S&&(w=S[1],p=p.slice(0,-w.length))}C.forEach(S=>{var E;const k=(E=i.get(S))!=null?E:h.get(S),j=this.getMarkClosing(S,k,l.get(S));j&&(p+=j),i.delete(S),l.delete(S)}),p+=w,p+=y,s.push(p)}else{const p=new Set((c.marks||[]).map(y=>y.type)),h=new Map,f=new Map;i.forEach((y,v)=>{var C;p.has(v)&&(h.set(v,y),f.set(v,(C=l.get(v))!=null?C:"markdown"))});const g=yte(i,(y,v)=>this.getMarkClosing(y,v,l.get(y)));l.clear();const x=this.renderNodeToMarkdown(c,t,d,r),b=c.type==="hardBreak"?"":vte(h,i,(y,v)=>{var C;const w=(C=f.get(y))!=null?C:"markdown";return l.set(y,w),this.getMarkOpening(y,v,w)});s.push(g+x+b)}}),s.join(n)}getMarkOpening(e,t,n="markdown"){var r;if(n==="html")return((r=this.getHtmlReopenTags(e))==null?void 0:r.open)||"";const s=this.getHandlersForNodeType(e),i=s.length>0?s[0]:void 0;if(!i||!i.renderMarkdown)return"";const o="î__TIPTAP_MARKDOWN_PLACEHOLDER__î",l={type:e,attrs:t.attrs||{},content:[{type:"text",text:o}]};try{const c=i.renderMarkdown(l,{renderChildren:()=>o,renderChild:()=>o,indent:u=>u,wrapInBlock:(u,p)=>u+p},{index:0,level:0,parentType:"text",meta:{}}),d=c.indexOf(o);return d>=0?c.substring(0,d):""}catch(c){throw new Error(`Failed to get mark opening for ${e}: ${c}`)}}getMarkClosing(e,t,n="markdown"){var r;if(n==="html")return((r=this.getHtmlReopenTags(e))==null?void 0:r.close)||"";const s=this.getHandlersForNodeType(e),i=s.length>0?s[0]:void 0;if(!i||!i.renderMarkdown)return"";const o="î__TIPTAP_MARKDOWN_PLACEHOLDER__î",l={type:e,attrs:t.attrs||{},content:[{type:"text",text:o}]};try{const c=i.renderMarkdown(l,{renderChildren:()=>o,renderChild:()=>o,indent:p=>p,wrapInBlock:(p,h)=>p+h},{index:0,level:0,parentType:"text",meta:{}}),d=c.indexOf(o),u=d+o.length;return d>=0?c.substring(u):""}catch(c){throw new Error(`Failed to get mark closing for ${e}: ${c}`)}}getHtmlReopenTags(e){const t=this.getHandlersForNodeType(e),n=t.length>0?t[0]:void 0;return n?.htmlReopen}markSetsEqual(e,t){return e.size!==t.size?!1:Array.from(e.entries()).every(([n,r])=>{const s=t.get(n);return s&&qd(r.attrs,s.attrs)})}getMarksToOpenForSerialization(e,t,n){const r=xte(e,t);if(r.length<=1)return r;const s=n?.marks||[],i=(d,u)=>s.some(p=>p.type===d&&qd(p.attrs,u)),o=(d,u)=>{var p,h;const f=(p=this.extensionRanks.get(d.type))!=null?p:Number.MAX_SAFE_INTEGER,g=(h=this.extensionRanks.get(u.type))!=null?h:Number.MAX_SAFE_INTEGER;return f!==g?g-f:d.type.localeCompare(u.type)},l=r.filter(d=>!i(d.type,d.mark.attrs)).sort(o),c=r.filter(d=>i(d.type,d.mark.attrs)).sort(o);return[...l,...c]}},rE=wte;ln.create({name:"markdown",addOptions(){return{indentation:{style:"space",size:2},marked:void 0,markedOptions:{}}},addCommands(){return{setContent:(e,t)=>
148{if(!t?.contentType||vp(e,t?.contentType)!=="markdown"||!this.editor.markdown)return ss.setContent(e,t);const r=this.editor.markdown.parse(e);return ss.setContent(r,t)},insertContent:(e,t)=>{if(!t?.contentType||vp(e,t?.contentType)!=="markdown"||!this.editor.markdown)return ss.insertContent(e,t);const r=this.editor.markdown.parse(e);return ss.insertContent(r,t)},insertContentAt:(e,t,n)=>{if(!n?.contentType||vp(t,n?.contentType)!=="markdown"||!this.editor.markdown)return ss.insertContentAt(e,t,n);const s=this.editor.markdown.parse(t);return ss.insertContentAt(e,s,n)}}},addStorage(){return{manager:new rE({indentation:this.options.indentation,marked:this.options.marked,markedOptions:this.options.markedOptions,extensions:[]})}},onBeforeCreate(){var e;if(this.editor.markdown){console.error("[tiptap][markdown]: There is already a `markdown` property on the editor instance. This might lead to unexpected behavior.");return}if(this.storage.manager=new rE({indentation:this.options.indentation,marked:this.options.marked,markedOptions:this.options.markedOptions,extensions:this.editor.extensionManager.baseExtensions}),this.editor.markdown=this.storage.manager,this.editor.getMarkdown=()=>this.storage.manager.serialize(this.editor.getJSON()),!this.editor.options.contentType||vp(this.editor.options.content,this.editor.options.contentType)!=="markdown")return;if(!this.editor.markdown)throw new Error('[tiptap][markdown]: The `contentType` option is set to "markdown", but the Markdown extension is not added to the editor. Please add the Markdown extension to use this feature.');if(this.editor.options.content===void 0||typeof this.editor.options.content!="string")throw new Error('[tiptap][markdown]: The `contentType` option is set to "markdown", but the initial content is not a string. Please provide the initial content as a markdown string.');const n=this.editor.markdown.parse(this.editor.options.content);(e=n.content)!=null&&e.length&&(this.editor.options.content=n)}});var mf=(e,t)=>{if(e==="slot")return 0;if(e instanceof Function)return e(t);const{children:n,...r}=t??{};if(e==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[e,r,n]},Ste=/^\s*>\s$/,jte=Gn.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:e}){return mf("blockquote",{...an(this.options.HTMLAttributes,e),children:mf("slot",{})})},parseMarkdown:(e,t)=>{var n;const r=(n=t.parseBlockChildren)!=null?n:t.parseChildren;return t.createNode("blockquote",void 0,r(e.tokens||[]))},renderMarkdown:(e,t)=>{if(!e.content)return"";const n=">",r=[];return e.content.forEach((s,i)=>{var o,l;const u=((l=(o=t.renderChild)==null?void 0:o.call(t,s,i))!=null?l:t.renderChildren([s])).split(` 149`).map(p=>p.trim()===""?n:`${n} ${p}`);r.push(u.join(` 150`))}),r.join(` 151${n} 152`)},addCommands(){return{setBlockquote:()=>({commands:e})=>e.wrapIn(this.name),toggleBlockquote:()=>({commands:e})=>e.toggleWrap(this.name),unsetBlockquote:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[dl({find:Ste,type:this.type})]}}),kte=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Ete=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,_te=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Tte=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Ite=Rl.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:e=>e.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:e=>e.type.name===this.name},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}]},renderHTML({HTMLAttributes:e}){return mf("strong",{...an(this.options.HTMLAttributes,e),children:mf("slot",{})})},markdownTokenName:"strong",parseMarkdown:(e,t)=>t.applyMark("bold",t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:"<strong>",close:"</strong>"}},renderMarkdown:(e,t)=>`**${t.renderChildren(e)}**`,addCommands(){return{setBold:()=>({commands:e})=>e.setMark(this.name),toggleBold:()=>({commands:e})=>e.toggleMark(this.name),unsetBold:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}}
vendor: 7,853 bytes, lines 152-173
152,addInputRules(){return[cl({find:kte,type:this.type}),cl({find:_te,type:this.type})]},addPasteRules(){return[ro({find:Ete,type:this.type}),ro({find:Tte,type:this.type})]}}),Dte=/(^|[^`])`([^`]+)`(?!`)$/,Ate=/(^|[^`])`([^`]+)`(?!`)/g,Mte=Rl.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:e}){return["code",an(this.options.HTMLAttributes,e),0]},markdownTokenName:"codespan",parseMarkdown:(e,t)=>t.applyMark("code",[{type:"text",text:e.text||""}]),renderMarkdown:(e,t)=>e.content?`\`${t.renderChildren(e.content)}\``:"",addCommands(){return{setCode:()=>({commands:e})=>e.setMark(this.name),toggleCode:()=>({commands:e})=>e.toggleMark(this.name),unsetCode:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[cl({find:Dte,type:this.type})]},addPasteRules(){return[ro({find:Ate,type:this.type})]}}),fx=4,Rte=/^```([a-z]+)?[\s\n]$/,Nte=/^~~~([a-z]+)?[\s\n]$/,Ote=Gn.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:fx,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:e=>{var t;const{languageClassPrefix:n}=this.options;if(!n)return null;const i=[...((t=e.firstElementChild)==null?void 0:t.classList)||[]].filter(o=>o.startsWith(n)).map(o=>o.replace(n,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:e,HTMLAttributes:t}){return["pre",an(this.options.HTMLAttributes,t),["code",{class:e.attrs.language?this.options.languageClassPrefix+e.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(e,t)=>{var n,r;return((n=e.raw)==null?void 0:n.startsWith("```"))===!1&&((r=e.raw)==null?void 0:r.startsWith("~~~"))===!1&&e.codeBlockStyle!=="indented"?[]:t.createNode("codeBlock",{language:e.lang||null},e.text?[t.createTextNode(e.text)]:[])},renderMarkdown:(e,t)=>{var n;let r="";const s=((n=e.attrs)==null?void 0:n.language)||"";return e.content?r=[`\`\`\`${s}`,t.renderChildren(e.content),"```"].join(` 153`):r=`\`\`\`${s} 154 155\`\`\``,r},addCommands(){return{setCodeBlock:e=>({commands:t})=>t.setNode(this.name,e),toggleCodeBlock:e=>({commands:t})=>t.toggleNode(this.name,"paragraph",e)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:e,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!e||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:e})=>{var t;if(!this.options.enableTabIndentation)return!1;const n=(t=this.options.tabSize)!=null?t:fx,{state:r}=e,{selection:s}=r,{$from:i,empty:o}=s;if(i.parent.type!==this.type)return!1;const l=" ".repeat(n);return o?e.commands.insertContent(l):e.commands.command(({tr:c})=>{const{from:d,to:u}=s,f=r.doc.textBetween(d,u,` 156`,` 157`).split(` 158`).map(g=>l+g).join(` 159`);return c.replaceWith(d,u,r.schema.text(f)),!0})},"Shift-Tab":({editor:e})=>{var t;if(!this.options.enableTabIndentation)return!1;const n=(t=this.options.tabSize)!=null?t:fx,{state:r}=e,{selection:s}=r,{$from:i,empty:o}=s;return i.parent.type!==this.type?!1:o?e.commands.command(({tr:l})=>{var c;const{pos:d}=i,u=i.start(),p=i.end(),f=r.doc.textBetween(u,p,` 160`,` 161`).split(` 162`);let g=0,x=0;const b=d-u;for(let E=0;E<f.length;E+=1){if(x+f[E].length>=b){g=E;break}x+=f[E].length+1}const v=((c=f[g].match(/^ */))==null?void 0:c[0])||"",C=Math.min(v.length,n);if(C===0)return!0;let w=u;for(let E=0;E<g;E+=1)w+=f[E].length+1;return l.delete(w,w+C),d-w<=C&&l.setSelection(Ke.create(l.doc,w)),!0}):e.commands.command(({tr:l})=>{const{from:c,to:d}=s,h=r.doc.textBetween(c,d,` 163`,` 164`).split(` 165`).map(f=>{var g;const x=((g=f.match(/^ */))==null?void 0:g[0])||"",b=Math.min(x.length,n);return f.slice(b)}).join(` 166`);return l.replaceWith(c,d,r.schema.text(h)),!0})},Enter:({editor:e})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=e,{selection:n}=t,{$from:r,empty:s}=n;if(!s||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(` 167 168`);return!i||!o?!1:e.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:e})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=e,{selection:n,doc:r}=t,{$from:s,empty:i}=n;if(!i||s.parent.type!==this.type||!(s.parentOffset===s.parent.nodeSize-2))return!1;const l=s.after();return l===void 0?!1:r.nodeAt(l)?e.commands.command(({tr:d})=>(d.setSelection(nt.near(r.resolve(l))),!0)):e.commands.exitCode()}}},addInputRules(){return[by({find:Rte,type:this.type,getAttributes:e=>({language:e[1]})}),by({find:Nte,type:this.type,getAttributes:e=>({language:e[1]})})]},addProseMirrorPlugins(){return[new pn({key:new hn("codeBlockVSCodeHandler"),props:{handlePaste:(e,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const n=t.clipboardData.getData("text/plain"),r=t.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,i=s?.mode;if(!n||!i)return!1;const{tr:o,schema:l}=e.state,c=l.text(n.replace(/\r\n?/g,` 169`));return o.replaceSelectionWith(this.type.create({language:i},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(Ke.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),e.dispatch(o),!0}}})]}}),Pte=Gn.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,` 170 171`):""}),Lte=Gn.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:e}){return["br",an(this.options.HTMLAttributes,e)]},renderText(){return` 172`},renderMarkdown:()=>` 173`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:e,chain:t,state:n,editor:r})=>e.first([()=>e.exitCode(),()=>e.command(()=>{const{selection:s,storedMarks:i}=n;if(s.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,c=i||s.$to.parentOffset&&s.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&o){const p=c.filter(h=>l.includes(h.type.name));d.ensureMarks(p)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),Fte=Gn.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(e=>({tag:`h${e}`,attrs:{level:e}}))},renderHTML({node:e,HTMLAttributes:t}){return[`h${this.options.levels.includes(e.attrs.level)?e.attrs.level:this.options.levels[0]}`,an(this.options.HTMLAttributes,t),0]},parseMarkdown:(e,t)=>t.createNode("heading",{level:e.depth||1},t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>{var n;const r=(n=e.attrs)!=null&&n.level?parseInt(e.attrs.level,10):1,s="#".repeat(r);return e.content?`${s} ${t.renderChildren(e.content)}`:""},addCommands(){return{setHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.setNode(this.name,e):!1,toggleHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.toggleNode(this.name,"paragraph",e):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((e,t)=>({...e,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(e=>by({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${e}}
173)\\s$`),type:this.type,getAttributes:{level:e}}))}}),$te=Gn.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:e}){return["hr",an(this.options.HTMLAttributes,e)]},markdownTokenName:"hr",parseMarkdown:(e,t)=>t.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:e,state:t})=>{if(!EX(t,t.schema.nodes[this.name]))return!1;const{selection:n}=t,{$to:r}=n,s=e();return rO(n)?s.insertContentAt(r.pos,{type:this.name}):s.insertContent({type:this.name}),s.command(({state:i,tr:o,dispatch:l})=>{if(l){const{$to:c}=o.selection,d=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection(Ke.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(Ye.create(o.doc,c.pos)):o.setSelection(Ke.create(o.doc,c.pos));else{const u=i.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,p=u?.create();p&&(o.insert(d,p),o.setSelection(Ke.create(o.doc,d+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[lO({find:/^(?:---|â-|___\s|\*\*\*\s)$/,type:this.t
vendor: 4,515 bytes, line 173
173ype})]}}),zte=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Bte=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Ute=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Vte=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Wte=Rl.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:e=>e.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:e=>e.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:e}){return["em",an(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(e,t)=>t.applyMark("italic",t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:"<em>",close:"</em>"}},renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[cl({find:zte,type:this.type}),cl({find:Ute,type:this.type})]},addPasteRules(){return[ro({find:Bte,type:this.type}),ro({find:Vte,type:this.type})]}});const Hte="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2
173ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",qte="ελ1Ï
2бг1ел3деÑи4еÑ2каÑолик6ом3мÐ
173ºÐ´2он1Ñква6онлайн5Ñг3ÑÑÑ2Ñ2ÑайÑ3Ñб3ÑкÑ3Òаз3Õ°Õ¡Õµ3×שר××5×§××3Ø§Ø¨ÙØ¸Ø¨Ù5را٠ÙÙ5ÙØ§Ø±Ø¯Ù4Ø¨ØØ±ÙÙ5جزائر5Ø³Ø¹ÙØ¯ÙØ©6عÙÙØ§Ù5٠غرب5٠ارات5ÛØ±Ø§Ù5بارت2زار4ÙØªÙ3ھارت5تÙÙØ³4Ø³ÙØ¯Ø§Ù3Ø±ÙØ©5Ø´Ø¨ÙØ©4عراÙ2ب2٠اÙ4ÙÙØ³Ø·ÙÙ6ÙØ·Ø±3ÙØ§Ø«ÙÙÙÙ6ÙÙ 3٠صر2ÙÙØ³Ùا5ÙØ±ÙتاÙÙØ§7ÙØ¹4Ù٠راÙ5پاکستاÙ7ÚØ§Ø±Øª4à¤à¥à¤®3नà¥à¤3à¤à¤¾à¤°à¤¤0मà¥3à¥à¤¤5सà¤à¤à¤ न5বাà¦à¦²à¦¾5à¦à¦¾à¦°à¦¤2ৰত4à¨à¨¾à¨°à¨¤4àªàª¾àª°àª¤4à¬à¬¾à¬°à¬¤4à®à®¨à¯à®¤à®¿à®¯à®¾6லà®à¯à®à¯6à®à®¿à®à¯à®à®ªà¯à®ªà¯à®°à¯11à°à°¾à°°à°¤à±5à²à²¾à²°à²¤4à´à´¾à´°à´¤à´5à¶½à¶à¶à·4à¸à¸à¸¡3à¹à¸à¸¢3ລາວ3áá2ã¿ããª3ã¢ãã¾ã³4ã¯ã©ã¦ã4ã°ã¼ã°ã«4ã³ã 2ã¹ãã¢3ã»ã¼ã«3ãã¡ãã·ã§ã³6ãã¤ã³ã4ä¸ç2ä¸ä¿¡1å½1å1æç½3äºé©¬é3ä¼ä¸2ä½å±±2ä¿¡æ¯2å¥åº·2å «å¦2å ¬å¸1ç2å°æ¹¾1ç£2åå1åº1æ 2åé0大é åº5å¨çº¿2大æ¿2天主æ3娱ä¹2å®¶é»2广ä¸2å¾®å2æ å2æç±ä½ 3ææº2æè2æ¿å¡1åº2æ°å å¡2é»2æ¶å°2æ¸ç±2æºæ2淡马é¡3游æ2æ¾³é2ç¹ç2ç§»å¨2ç»ç»æºæ4ç½å1åº1ç«1ç»2èé2è°·æ2è´ç©2é販2éå¢2é»è¨çç§4é£å©æµ¦3é£å2é¤å 2馿 ¼éæ3港2ë·ë·1ì»´2ì¼ì±2íêµ2",Ay="numeric",My="ascii",Ry="alpha",bd="asciinumeric",od="alphanumeric",Ny="domain",HO="emoji",Gte="scheme",Yte="slashscheme",mx="whitespace";function Kte(e,t){return e in t||(t[e]=[]),t[e]}function Oa(e,t,n){t[Ay]&&(t[bd]=!0,t[od]=!0),t[My]&&(t[bd]=!0,t[Ry]=!0),t[bd]&&(t[od]=!0),t[Ry]&&(t[od]=!0),t[od]&&(t[Ny]=!0),t[HO]&&(t[Ny]=!0);for(const r in t){const s=Kte(r,n);s.indexOf(e)<0&&s.push(e)}}function Qte(e,t){const n={};for(const r in t)t[r].indexOf(e)>=0&&(n[r]=!0);return n}function _r(e=null){this.j={},this.jr=[],this.jd=null,this.t=e}_r.groups={};_r.prototype={accepts(){return!!this.t},go(e){const t=this,n=t.j[e];if(n)return n;for(let r=0;r<t.jr.length;r++){const s=t.jr[r][0],i=t.jr[r][1];if(i&&s.test(e))return i}return t.jd},has(e,t=!1){return t?e in this.j:!!this.go(e)},ta(e,t,n,r){for(let s=0;s<e.length;s++)this.tt(e[s],t,n,r)},tr(e,t,n,r){r=r||_r.groups;let s;return t&&t.j?s=t:(s=new _r(t),n&&r&&Oa(t,n,r)),this.jr.push([e,s]),s},ts(e,t,n,r){let s=this;const i=e.length;if(!i)return s;for(let o=0;o<i-1;o++)s=s.tt(e[o]);return s.tt(e[i-1],t,n,r)},tt(e,t,n,r){r=r||_r.groups;const s=this;if(t&&t.j)return s.j[e]=t,t;const i=t;let o,l=s.go(e);if(l?(o=new _r,Object.assign(o.j,l.j),o.jr.push.apply(o.jr,l.jr),o.jd=l.jd,o.t=l.t):o=new _r,i){if(r)if(o.t&&typeof o.t=="string"){const c=Object.assign(Qte(o.t,r),n);Oa(i,c,r)}else n&&Oa(i,n,r);o.t=i}return s.j[e]=o,o}};const ht=(e,t,n,r,s)=>e.ta(t,n,r,s),wn=(e,t,n,r,s)=>e.tr(t,n,r,s),sE=(e,t,n,r,s)=>e.ts(t,n,r,s),Ee=(e,t,n,r,s)=>e.tt(t,n,r,s),ui="WORD",Oy="UWORD",qO="ASCIINUMERICAL",GO="ALPHANUMERICAL",Gd="LOCALHOST",Py="TLD",Ly="UTLD",Ch="SCHEME",Bo="SLASH_SCHEME",j0="NUM",Fy="WS",k0="NL",yd="OPENBRACE",vd="CLOSEBRACE",gf="OPENBRACKET",xf="CLOSEBRACKET",bf="OPENPAREN",yf="CLOSEPAREN",vf="OPENANGLEBRACKET",Cf="CLOSEANGLEBRACKET",wf="FULLWIDTHLEFTPAREN",Sf="FULLWIDTHRIGHTPAREN",jf="LEFTCORNERBRACKET",kf="RIGHTCORNERBRACKET",Ef="LEFTWHITECORNERBRACKET",_f="RIGHTWHITECORNERBRACKET",Tf="FULLWIDTHLESSTHAN",If="FULLWIDTHGREATERTHAN",Df="AMPERSAND",Af="APOSTROPHE",Mf="ASTERISK",Li="AT",Rf="BACKSLASH",Nf="BACKTICK",Of="CARET",Pa="COLON",E0="COMMA",Pf="DOLLAR",Ns="DOT",Lf="EQUALS",_0="EXCLAMATION",Yr="HYPHEN",Cd="PERCENT",Ff="PIPE",$f="PLUS",zf="POUND",wd="QUERY",T0="QUOTE",YO="FULLWIDTHMIDDLEDOT",I0="SEMI",Os="SLASH",Sd="TILDE",Bf="UNDERSCORE",KO="EMOJI",Uf="SYM";var QO=Object.freeze({__proto__:null,ALPHANUMERICAL:GO,AMPERSAND:Df,APOSTROPHE:Af,ASCIINUMERICAL:qO,ASTERISK:Mf,AT:Li,BACKSLASH:Rf,BACKTICK:Nf,CARET:Of,CLOSEANGLEBRACKET:Cf,CLOSEBRACE:vd,CLOSEBRACKET:xf,CLOSEPAREN:yf,COLON:Pa,COMMA:E0,DOLLAR:Pf,DOT:Ns,EMOJI:KO,EQUALS:Lf,EXCLAMATION:_0,FULLWIDTHGREATERTHAN:If,FULLWIDTHLEFTPAREN:wf,FULLWIDTHLESSTHAN:Tf,FULLWIDTHMIDDLEDOT:YO,FULLWIDTHRIGHTPAREN:Sf,HYPHEN:Yr,LEFTCORNERBRACKET:jf,LEFTWHITECORNERBRACKET:Ef,LOCALHOST:Gd,NL:k0,NUM:j0,OPENANGLEBRACKET:vf,OPENBRACE:yd,OPENBRACKET:gf,OPENPAREN:bf,PERCENT:Cd,PIPE:Ff,PLUS:$f,POUND:zf,QUERY:wd,QUOTE:T0,RIGHTCORNERBRACKET:kf,RIGHTWHITECORNERBRACKET:_f,SCHEME:Ch,SEMI:I0,SLASH:Os,SLASH_SCHEME:Bo,SYM:Uf,TILDE:Sd,TLD:Py,UNDERSCORE:Bf,UTLD:Ly,UWORD:Oy,WORD:ui,WS:Fy});const si=/[a-z]/,mc=new RegExp("\\p{L}","u"),gx=new RegExp("\\p{Emoji}","u"),ii=/\d/,xx=/\s/,iE="\r",bx=` 174`,Jte="ï¸",Xte="â",yx="";let Cp=null,wp=null;function Zte(e=[]){const t={};_r.groups=t;const n=new _r;Cp==null&&(Cp=aE(Hte)),wp==null&&(wp=aE(qte)),Ee(n,"'",Af),Ee(n,"{",yd),Ee(n,"}",vd),Ee(n,"[",gf),Ee(n,"]",xf),Ee(n,"(",bf),Ee(n,")",yf),Ee(n,"<",vf),Ee(n,">",Cf),Ee(n,"ï¼",wf),Ee(n,"ï¼",Sf),Ee(n,"ã",jf),Ee(n,"ã",kf),Ee(n,"ã",Ef),Ee(n,"ã",_f),Ee(n,"ï¼",Tf),Ee(n,"ï¼",If),Ee(n,"&",Df),Ee(n,"*",Mf),Ee(n,"@",Li),Ee(n,"`",Nf),Ee(n,"^",Of),Ee(n,":",Pa),Ee(n,",",E0),Ee(n,"$",Pf),Ee(n,".",Ns),Ee(n,"=",Lf),Ee(n,"!",_0),Ee(n,"-",Yr),Ee(n,"%",Cd),Ee(n,"|",Ff),Ee(n,"+",$f),Ee(n,"#",zf),Ee(n,"?",wd),Ee(n,'"',T0),Ee(n,"/",Os),Ee(n,";",I0),Ee(n,"~",Sd),Ee(n,"_",Bf),Ee(n,"\\",Rf),Ee(n,"ã»",YO);const r=wn(n,ii,j0,{[Ay]:!0});wn(r,ii,r);const s=wn(r,si,qO,{[bd]:!0}),i=wn(r,mc,GO,{[od]:!0}),o=wn(n,si,ui,{[My]:!0});wn(o,ii,s),wn(o,si,o),wn(s,ii,s),wn(s,si,s);const l=wn(n,mc,Oy,{[Ry]:!0});wn(l,si),wn(l,ii,i),wn(l,mc,l),wn(i,ii,i),wn(i,si),wn(i,mc,i);const c=Ee(n,bx,k0,{[mx]:!0}),d=Ee(n,iE,Fy,{[mx]:!0}),u=wn(n,xx,Fy,{[mx]:!0});Ee(n,yx,u),Ee(d,bx,c),Ee(d,yx,u),wn(d,xx,u),Ee(u,iE),Ee(u,bx),wn(u,xx,u),Ee(u,yx,u);const p=wn(n,gx,KO,{[HO]:!0});Ee(p,"#"),wn(p,gx,p),Ee(p,Jte,p);const h=Ee(p,Xte);Ee(h,"#"),wn(h,gx,p);const f=[[si,o],[ii,s]],g=[[si,null],[mc,l],[ii,i]];for(let x=0;x<Cp.length;x++)Di(n,Cp[x],Py,ui,f);for(let x=0;x<wp.length;x++)Di(n,wp[x],Ly,Oy,g);Oa(Py,{tld:!0,ascii:!0},t),Oa(Ly,{utld:!0,alpha:!0},t),Di(n,"file",Ch,ui,f),Di(n,"mailto",Ch,ui,f),Di(n,"http",Bo,ui,f),Di(n,"https",Bo,ui,f),Di(n,"ftp",Bo,ui,f),Di(n,"ftps",Bo,ui,f),Oa(Ch,{scheme:!0,ascii:!0},t),Oa(Bo,{slashscheme:!0,ascii:!0},t),e=e.sort((x,b)=>x[0]>b[0]?1:-1);for(let x=0;x<e.length;x++){const b=e[x][0],v=e[x][1]?{[Gte]:!0}:{[Yte]:!0};b.indexOf("-")>=0?v[Ny]=!0:si.test(b)?ii.test(b)?v[bd]=!0:v[My]=!0:v[Ay]=!0,sE(n,b,b,v)}return sE(n,"localhost",Gd,{ascii:!0}),n.jd=new _r(Uf),{start:n,tokens:Object.assign({groups:t},QO)}}function JO(e,t){const n=ene(t.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,s=[];let i=0,o=0;for(;o<r;){let l=e,c=null,d=0,u=null,p=-1,h=-1;for(;o<r&&(c=l.go(n[o]));)l=c,l.accepts()?(p=0,h=0,u=l):p>=0&&(p+=n[o].length,h++),d+=n[o].length,i+=n[o].length,o++;i-=p,o-=h,d-=p,s.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return s}function ene(e){const t=[],n=e.length;let r=0;for(;r<n;){let s=e.charCodeAt(r),i,o=s<55296||s>56319||r+1===n||(i=e.charCodeAt(r+1))<56320||i>57343?e[r]:e.slice(r,r+2);t.push(o),r+=o.length}return t}
vendor: 9,256 bytes, lines 174-177
174function Di(e,t,n,r,s){let i;const o=t.length;for(let l=0;l<o-1;l++){const c=t[l];e.j[c]?i=e.j[c]:(i=new _r(r),i.jr=s.slice(),e.j[c]=i),e=i}return i=new _r(n),i.jr=s.slice(),e.j[t[o-1]]=i,i}function aE(e){const t=[],n=[];let r=0,s="0123456789";for(;r<e.length;){let i=0;for(;s.indexOf(e[r+i])>=0;)i++;if(i>0){t.push(n.join(""));for(let o=parseInt(e.substring(r,r+i),10);o>0;o--)n.pop();r+=i}else n.push(e[r]),r++}return t}const Yd={defaultProtocol:"http",events:null,format:oE,formatHref:oE,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function D0(e,t=null){let n=Object.assign({},Yd);e&&(n=Object.assign(n,e instanceof D0?e.o:e));const r=n.ignoreTags,s=[];for(let i=0;i<r.length;i++)s.push(r[i].toUpperCase());this.o=n,t&&(this.defaultRender=t),this.ignoreTags=s}D0.prototype={o:Yd,ignoreTags:[],defaultRender(e){return e},check(e){return this.get("validate",e.toString(),e)},get(e,t,n){const r=t!=null;let s=this.o[e];return s&&(typeof s=="object"?(s=n.t in s?s[n.t]:Yd[e],typeof s=="function"&&r&&(s=s(t,n))):typeof s=="function"&&r&&(s=s(t,n.t,n)),s)},getObj(e,t,n){let r=this.o[e];return typeof r=="function"&&t!=null&&(r=r(t,n.t,n)),r},render(e){const t=e.render(this);return(this.get("render",null,e)||this.defaultRender)(t,e.t,e)}};function oE(e){return e}function XO(e,t){this.t="token",this.v=e,this.tk=t}XO.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){const t=this.toString(),n=e.get("truncate",t,this),r=e.get("format",t,this);return n&&r.length>n?r.substring(0,n)+"â¦":r},toFormattedHref(e){return e.get("formatHref",this.toHref(e.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=Yd.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get("validate",this.toString(),this)},render(e){const t=this,n=this.toHref(e.get("defaultProtocol")),r=e.get("formatHref",n,this),s=e.get("tagName",n,t),i=this.toFormattedString(e),o={},l=e.get("className",n,t),c=e.get("target",n,t),d=e.get("rel",n,t),u=e.getObj("attributes",n,t),p=e.getObj("events",n,t);return o.href=r,l&&(o.class=l),c&&(o.target=c),d&&(o.rel=d),u&&Object.assign(o,u),{tagName:s,attributes:o,content:i,eventListeners:p}}};function Xm(e,t){class n extends XO{constructor(s,i){super(s,i),this.t=e}}for(const r in t)n.prototype[r]=t[r];return n.t=e,n}const tne=Xm("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),lE=Xm("text"),nne=Xm("nl"),Sp=Xm("url",{isLink:!0,toHref(e=Yd.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){const e=this.tk;return e.length>=2&&e[0].t!==Gd&&e[1].t===Pa}}),Gr=e=>new _r(e);function rne({groups:e}){const t=e.domain.concat([Df,Mf,Li,Rf,Nf,Of,Pf,Lf,Yr,j0,Cd,Ff,$f,zf,Os,Uf,Sd,Bf]),n=[Af,Pa,E0,Ns,_0,Cd,wd,T0,I0,vf,Cf,yd,vd,xf,gf,bf,yf,wf,Sf,jf,kf,Ef,_f,Tf,If],r=[Df,Af,Mf,Rf,Nf,Of,Pf,Lf,Yr,yd,vd,Cd,Ff,$f,zf,wd,Os,Uf,Sd,Bf],s=Gr(),i=Ee(s,Sd);ht(i,r,i),ht(i,e.domain,i);const o=Gr(),l=Gr(),c=Gr();ht(s,e.domain,o),ht(s,e.scheme,l),ht(s,e.slashscheme,c),ht(o,r,i),ht(o,e.domain,o);const d=Ee(o,Li);Ee(i,Li,d),Ee(l,Li,d),Ee(c,Li,d);const u=Ee(i,Ns);ht(u,r,i),ht(u,e.domain,i);const p=Gr();ht(d,e.domain,p),ht(p,e.domain,p);const h=Ee(p,Ns);ht(h,e.domain,p);const f=Gr(tne);ht(h,e.tld,f),ht(h,e.utld,f),Ee(d,Gd,f);const g=Ee(p,Yr);Ee(g,Yr,g),ht(g,e.domain,p),ht(f,e.domain,p),Ee(f,Ns,h),Ee(f,Yr,g);const x=Ee(o,Yr),b=Ee(o,Ns);Ee(x,Yr,x),ht(x,e.domain,o),ht(b,r,i),ht(b,e.domain,o);const y=Gr(Sp);ht(b,e.tld,y),ht(b,e.utld,y),ht(y,e.domain,o),ht(y,r,i),Ee(y,Ns,b),Ee(y,Yr,x),Ee(y,Li,d);const v=Ee(y,Pa),C=Gr(Sp);ht(v,e.numeric,C);const w=Gr(Sp),S=Gr();ht(w,t,w),ht(w,n,S),ht(S,t,w),ht(S,n,S),Ee(y,Os,w),Ee(C,Os,w);const E=Ee(l,Pa),k=Ee(c,Pa),j=Ee(k,Os),_=Ee(j,Os);ht(l,e.domain,o),Ee(l,Ns,b),Ee(l,Yr,x),ht(c,e.domain,o),Ee(c,Ns,b),Ee(c,Yr,x),ht(E,e.domain,w),Ee(E,Os,w),Ee(E,wd,w),ht(_,e.domain,w),ht(_,t,w),Ee(_,Os,w);const D=[[yd,vd],[gf,xf],[bf,yf],[vf,Cf],[wf,Sf],[jf,kf],[Ef,_f],[Tf,If]];for(let M=0;M<D.length;M++){const[N,O]=D[M],R=Ee(w,N);Ee(S,N,R);const L=Gr(Sp);ht(R,t,L);const P=Gr();ht(R,n,P),Ee(R,O,w),ht(L,t,L),ht(L,n,P),ht(P,t,L),ht(P,n,P),Ee(L,O,w),Ee(P,O,w)}return Ee(s,Gd,y),Ee(s,k0,nne),{start:s,tokens:QO}}function sne(e,t,n){let r=n.length,s=0,i=[],o=[];for(;s<r;){let l=e,c=null,d=null,u=0,p=null,h=-1;for(;s<r&&!(c=l.go(n[s].t));)o.push(n[s++]);for(;s<r&&(d=c||l.go(n[s].t));)c=null,l=d,l.accepts()?(h=0,p=l):h>=0&&h++,s++,u++;if(h<0)s-=u,s<r&&(o.push(n[s]),s++);else{o.length>0&&(i.push(vx(lE,t,o)),o=[]),s-=h,u-=h;const f=p.t,g=n.slice(s-u,s);i.push(vx(f,t,g))}}return o.length>0&&i.push(vx(lE,t,o)),i}function vx(e,t,n){const r=n[0].s,s=n[n.length-1].e,i=t.slice(r,s);return new e(i,n)}const ine=typeof console<"u"&&console&&console.warn||(()=>{}),ane="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",nn={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function one(){return _r.groups={},nn.scanner=null,nn.parser=null,nn.tokenQueue=[],nn.pluginQueue=[],nn.customSchemes=[],nn.initialized=!1,nn}function cE(e,t=!1){if(nn.initialized&&ine(`linkifyjs: already initialized - will not register custom scheme "${e}" ${ane}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(e))throw new Error(`linkifyjs: incorrect scheme format. 1751. Must only contain digits, lowercase ASCII letters or "-" 1762. Cannot start or end with "-" 1773. "-" cannot repeat`);nn.customSchemes.push([e,t])}function lne(){nn.scanner=Zte(nn.customSchemes);for(let e=0;e<nn.tokenQueue.length;e++)nn.tokenQueue[e][1]({scanner:nn.scanner});nn.parser=rne(nn.scanner.tokens);for(let e=0;e<nn.pluginQueue.length;e++)nn.pluginQueue[e][1]({scanner:nn.scanner,parser:nn.parser});return nn.initialized=!0,nn}function A0(e){return nn.initialized||lne(),sne(nn.parser.start,e,JO(nn.scanner.start,e))}A0.scan=JO;function ZO(e,t=null,n=null){if(t&&typeof t=="object"){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}const r=new D0(n),s=A0(e),i=[];for(let o=0;o<s.length;o++){const l=s[o];l.isLink&&(!t||l.t===t)&&r.check(l)&&i.push(l.toFormattedObject(r))}return i}var M0="[\0-  áá â-\u2029âã]",cne=new RegExp(M0),dne=new RegExp(`${M0}$`),une=new RegExp(M0,"g");function pne(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?["()","[]"].includes(e[0].value+e[2].value):!1}function hne(e){return new pn({key:new hn("autolink"),appendTransaction:(t,n,r)=>{const s=t.some(d=>d.docChanged)&&!n.doc.eq(r.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!s||i)return;const{tr:o}=r,l=XN(n.doc,[...t]);if(nO(l).forEach(({newRange:d})=>{const u=wJ(r.doc,d,f=>f.isTextblock);let p,h;if(u.length>1)p=u[0],h=r.doc.textBetween(p.pos,p.pos+p.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!dne.test(f))return;p=u[0],h=r.doc.textBetween(p.pos,d.to,void 0," ")}if(p&&h){const f=h.split(cne).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],x=p.pos+h.lastIndexOf(g);if(!g)return!1;const b=A0(g).map(y=>y.toObject(e.defaultProtocol));if(!pne(b))return!1;b.filter(y=>y.isLink).map(y=>({...y,from:x+y.start+1,to:x+y.end+1})).filter(y=>r.schema.marks.code?!r.doc.rangeHasMark(y.from,y.to,r.schema.marks.code):!0).filter(y=>e.validate(y.value)).filter(y=>e.shouldAutoLink(y.value)).forEach(y=>{o0(y.from,y.to,r.doc).some(v=>v.mark.type===e.type)||o.addMark(y.from,y.to,e.type.create({href:y.href}))})}}),!!o.steps.length)return o}})}function fne(e){return new pn({key:new hn("handleClickLink"),props:{handleClick:(t,n,r)=>{var s,i;if(r.button!==0||!t.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{const c=r.target;if(!c)return!1;const d=e.editor.view.dom;o=c.closest("a"),o&&!d.contains(o)&&(o=null)}if(!o)return!1;let l=!1;if(e.enableClickSelection&&(l=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){const c=OJ(t.state,e.type.name),d=(s=o.href)!=null?s:c.href,u=(i=o.target)!=null?i:c.target;d&&(window.open(d,u),l=!0)}return l}}})}function mne(e){return new pn({key:new hn("handlePasteLink"),props:{handlePaste:(t,n,r)=>{const{shouldAutoLink:s}=e,{state:i}=t,{selection:o}=i,{empty:l}=o;if(l)return!1;let c="";r.content.forEach(u=>{c+=u.textContent});const d=ZO(c,{defaultProtocol:e.defaultProtocol}).find(u=>u.isLink&&u.value===c);return!c||!d||s!==void 0&&!s(d.value)?!1:e.editor.commands.setMark(e.type,{href:d.href})}}})}function ja(e,t){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(r=>{const s=typeof r=="string"?r:r.scheme;s&&n.push(s)}),!e||e.replace(une,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var gne=Rl.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `val
177idate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(e=>{if(typeof e=="string"){cE(e);return}cE(e.scheme,e.optionalSlashes)})},onDestroy(){one()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(e,t)=>!!ja(e,t.protocols),validate:e=>!!e,shouldAutoLink:e=>{const t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e),n=/^[a-z][a-z0-9+.-]*:/i.test(e);if(t||n&&!e.includes("@"))return!0;const s=(e.includes("@")?e.split("@").pop():e).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||!/\./.test(s))}}},addAttributes(){return{href:{default:null,parseHTML(e){return e.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:e=>{const t=e.getAttribute("href");return!t||!this.options.isAllowedUri(t,{defaultValidate:n=>!!ja(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:e}){return this.options.isAllowedUri(e.href,{defaultValidate:t=>!!ja(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",an(this.options.HTMLAttributes,e),0]:["a",an(this.options.HTMLAttributes,{...e,href:""}),0]},markdownTokenName:"link",parseMarkdown:(e,t)=>t.applyMark("link",t.parseInline(e.tokens||[]),{href:e.href,title:e.title||null}),renderMarkdown:(e,t)=>{var n,r,s,i;const o=(r=(n=e.attrs)==null?void 0:n.href)!=null?r:"",l=(i=(s=e.attrs)==null?void 0:s.title)!=null?i:"",c=t.renderChildren(e);return l?`[${c}](${o} "${l}")`:`[${c}](${o})`},addCommands(){return{setLink:e=>({chain:t})=>{const{href:n}=e;return this.options.isAllowedUri(n,{defaultValidate:r=>!!ja(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,e).setMeta("preventAutolink",!0).run():!1},toggleLink:e=>({chain:t})=>{const{href:n}=e||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:r=>!!ja(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:t().toggleMark(this.name,e,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:e})=>e().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[ro({find:e=>{const t=[];if(e){const{protocols:n,defaultProtocol:r}=this.options,s=ZO(e).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:o=>!!ja(o,n),protocols:n,defaultProtocol:r}));s.length&&s.forEach(i=>{this.options.shouldAutoLink(i.value)&&t.push({text:i.value,data:{href:i.href},index:i.start})})}return t}
177,type:this.type,getAttributes:e=>{var t;return{href:(t=e.data)==null?void 0:t.href}}})]},addProseMirrorPlugins(){const e=[],{protocols:t,defaultProtocol:n}=this.options;return this.options.autolink&&e.push(hne({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:s=>!!ja(s,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),e.push(fne({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&e.push(mne({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),e}}),jp=" ",Cx="Â ",xne=Gn.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:e}){return["p",an(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{const n=e.tokens||[];if(n.length===1&&n[0].type==="image")return t.parseChildren([n[0]]);const r=t.parseInline(n);return n.length===1&&n[0].type==="text"&&(n[0].raw===jp||n[0].text===jp||n[0].raw===Cx||n[0].text===Cx)&&r.length===1&&r[0].type==="text"&&(r[0].text===jp||r[0].text===Cx)?t.createNode("paragraph",void 0,[]):t.createNode("paragraph",void 0,r)},renderMarkdown:(e,t,n)=>{var r,s;if(!e)return"";const i=Array.isArray(e.content)?e.content:[];if(i.length===0){const o=Array.isArray((r=n?.previousNode)==null?void 0:r.content)?n.previousNode.content:[];return((s=n?.previousNode)==null?void 0:s.type)==="paragraph"&&o.length===0?jp:""}return t.renderChildren(i)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),bne=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,yne=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,vne=Rl.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:e=>e.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:e}){return["s",an(this.options.HTMLAttributes,e),0]},markdownTokenName:"del",parseMarkdown:(e,t)=>t.applyMark("strike",t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[cl({find:bne,type:this.type})]},addPasteRules(){return[ro({find:yne,type:this.type})]}}),Cne=Gn.create({name:"text",group:"inline",parseMarkdown:e=>({type:"text",text:e.text||""}),renderMarkdown:e=>e.text||""}),wne=Rl.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:e=>e.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:e}){return["u",an(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||"underline",t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`++${t.renderChildren(e)}++`},markdownTokenizer:{name:"underline",level:"inline",start(e){return e.indexOf("++")},tokenize(e,t,n){const s=/^(\+\+)([\s\S]+?)(\+\+)/.exec(e);if(!s)return;const i=s[2].trim();return{type:"underline",raw:s[0],text:i,tokens:n.inlineTokens(i)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleUnderline:()=>({commands:e})=>e.toggleMark(this.name),unsetUnderline:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function Sne(e={}){return new pn({view(t){return new jne(t,e)}})}class jne{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(s=>{let i=o=>{this[s](o)};return t.dom.addEventListener(s,i),{name:s,handler:i}})}
vendor: 4,302 bytes, line 177
177destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,s=this.editorView.dom,i=s.getBoundingClientRect(),o=i.width/s.offsetWidth,l=i.height/s.offsetHeight;if(n){let p=t.nodeBefore,h=t.nodeAfter;if(p||h){let f=this.editorView.nodeDOM(this.cursorPos-(p?p.nodeSize:0));if(f){let g=f.getBoundingClientRect(),x=p?g.bottom:g.top;p&&h&&(x=(x+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*l;r={left:g.left,right:g.right,top:x-b,bottom:x+b}}}}if(!r){let p=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*o;r={left:p.left-h,right:p.left+h,top:p.top,bottom:p.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let p=c.getBoundingClientRect(),h=p.width/c.offsetWidth,f=p.height/c.offsetHeight;d=p.left-c.scrollLeft*h,u=p.top-c.scrollTop*f}this.element.style.left=(r.left-d)/o+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),s=r&&r.type.spec.disableDropCursor,i=typeof s=="function"?s(this.editorView,n,t):s;if(n&&!i){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=ZR(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}class kn extends nt{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return kn.valid(r)?new kn(r):nt.near(r)}content(){return Te.empty}eq(t){return t instanceof kn&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new kn(t.resolve(n.pos))}getBookmark(){return new R0(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!kne(t)||!Ene(t))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let s=n.contentMatchAt(t.index()).defaultType;return s&&s.isTextblock}static findGapCursorFrom(t,n,r=!1){e:for(;;){if(!r&&kn.valid(t))return t;let s=t.pos,i=null;for(let o=t.depth;;o--){let l=t.node(o);if(n>0?t.indexAfter(o)<l.childCount:t.index(o)>0){i=l.child(n>0?t.indexAfter(o):t.index(o)-1);break}else if(o==0)return null;s+=n;let c=t.doc.resolve(s);if(kn.valid(c))return c}for(;;){let o=n>0?i.firstChild:i.lastChild;if(!o){if(i.isAtom&&!i.isText&&!Ye.isSelectable(i)){t=t.doc.resolve(s+i.nodeSize*n),r=!1;continue e}break}i=o,s+=n;let l=t.doc.resolve(s);if(kn.valid(l))return l}return null}}}kn.prototype.visible=!1;kn.findFrom=kn.findGapCursorFrom;nt.jsonID("gapcursor",kn);class R0{constructor(t){this.pos=t}map(t){return new R0(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return kn.valid(n)?new kn(n):nt.near(n)}}function eP(e){return e.isAtom||e.spec.isolating||e.spec.createGapCursor}function kne(e){for(let t=e.depth;t>=0;t--){let n=e.index(t),r=e.node(t);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(n-1);;s=s.lastChild){if(s.childCount==0&&!s.inlineContent||eP(s.type))return!0;
vendor: 9,724 bytes, line 177
177if(s.inlineContent)return!1}}return!0}function Ene(e){for(let t=e.depth;t>=0;t--){let n=e.indexAfter(t),r=e.node(t);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(n);;s=s.firstChild){if(s.childCount==0&&!s.inlineContent||eP(s.type))return!0;if(s.inlineContent)return!1}}return!0}function _ne(){return new pn({props:{decorations:Ane,createSelectionBetween(e,t,n){return t.pos==n.pos&&kn.valid(n)?new kn(n):null},handleClick:Ine,handleKeyDown:Tne,handleDOMEvents:{beforeinput:Dne}}})}const Tne=qN({ArrowLeft:kp("horiz",-1),ArrowRight:kp("horiz",1),ArrowUp:kp("vert",-1),ArrowDown:kp("vert",1)});function kp(e,t){const n=e=="vert"?t>0?"down":"up":t>0?"right":"left";return function(r,s,i){let o=r.selection,l=t>0?o.$to:o.$from,c=o.empty;if(o instanceof Ke){if(!i.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(t>0?l.after():l.before())}let d=kn.findGapCursorFrom(l,t,c);return d?(s&&s(r.tr.setSelection(new kn(d))),!0):!1}}function Ine(e,t,n){if(!e||!e.editable)return!1;let r=e.state.doc.resolve(t);if(!kn.valid(r))return!1;let s=e.posAtCoords({left:n.clientX,top:n.clientY});return s&&s.inside>-1&&Ye.isSelectable(e.state.doc.nodeAt(s.inside))?!1:(e.dispatch(e.state.tr.setSelection(new kn(r))),!0)}function Dne(e,t){if(t.inputType!="insertCompositionText"||!(e.state.selection instanceof kn))return!1;let{$from:n}=e.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(e.state.schema.nodes.text);if(!r)return!1;let s=we.empty;for(let o=r.length-1;o>=0;o--)s=we.from(r[o].createAndFill(null,s));let i=e.state.tr.replace(n.pos,n.pos,new Te(s,0,0));return i.setSelection(Ke.near(i.doc.resolve(n.pos+1))),e.dispatch(i),!1}function Ane(e){if(!(e.selection instanceof kn))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Bt.create(e.doc,[Qn.widget(e.selection.head,t,{key:"gapcursor"})])}var Vf=200,Xn=function(){};Xn.prototype.append=function(t){return t.length?(t=Xn.from(t),!this.length&&t||t.length<Vf&&this.leafAppend(t)||this.length<Vf&&t.leafPrepend(this)||this.appendInner(t)):this};Xn.prototype.prepend=function(t){return t.length?Xn.from(t).append(this):this};Xn.prototype.appendInner=function(t){return new Mne(this,t)};Xn.prototype.slice=function(t,n){return t===void 0&&(t=0),n===void 0&&(n=this.length),t>=n?Xn.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Xn.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Xn.prototype.forEach=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(t,n,r,0):this.forEachInvertedInner(t,n,r,0)};Xn.prototype.map=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var s=[];return this.forEach(function(i,o){return s.push(t(i,o))},n,r),s};Xn.from=function(t){return t instanceof Xn?t:t&&t.length?new tP(t):Xn.empty};var tP=(function(e){function t(r){e.call(this),this.values=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(s,i){return s==0&&i==this.length?this:new t(this.values.slice(s,i))},t.prototype.getInner=function(s){return this.values[s]},t.prototype.forEachInner=function(s,i,o,l){for(var c=i;c<o;c++)if(s(this.values[c],l+c)===!1)return!1},t.prototype.forEachInvertedInner=function(s,i,o,l){for(var c=i-1;c>=o;c--)if(s(this.values[c],l+c)===!1)return!1},t.prototype.leafAppend=function(s){if(this.length+s.length<=Vf)return new t(this.values.concat(s.flatten()))},t.prototype.leafPrepend=function(s){if(this.length+s.length<=Vf)return new t(s.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t})(Xn);Xn.empty=new tP([]);var Mne=(function(e){function t(n,r){e.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},t.prototype.forEachInner=function(r,s,i,o){var l=this.left.length;if(s<l&&this.left.forEachInner(r,s,Math.min(i,l),o)===!1||i>l&&this.right.forEachInner(r,Math.max(s-l,0),Math.min(this.length,i)-l,o+l)===!1)return!1},t.prototype.forEachInvertedInner=function(r,s,i,o){var l=this.left.length;if(s>l&&this.right.forEachInvertedInner(r,s-l,Math.max(i,l)-l,o+l)===!1||i<l&&this.left.forEachInvertedInner(r,Math.min(s,l),i,o)===!1)return!1},t.prototype.sliceInner=function(r,s){if(r==0&&s==this.length)return this;var i=this.left.length;return s<=i?this.left.slice(r,s):r>=i?this.right.slice(r-i,s-i):this.left.slice(r,i).append(this.right.slice(0,s-i))},t.prototype.leafAppend=function(r){var s=this.right.leafAppend(r);if(s)return new t(this.left,s)},t.prototype.leafPrepend=function(r){var s=this.left.leafPrepend(r);if(s)return new t(s,this.right)},t.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new t(this.left,new t(this.right,r)):new t(this,r)},t})(Xn);const Rne=500;class ds{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let s,i;n&&(s=this.remapping(r,this.items.length),i=s.maps.length);let o=t.tr,l,c,d=[],u=[];return this.items.forEach((p,h)=>{if(!p.step){s||(s=this.remapping(r,h+1),i=s.maps.length),i--,u.push(p);return}if(s){u.push(new Ps(p.map));let f=p.step.map(s.slice(i)),g;f&&o.maybeStep(f).doc&&(g=o.mapping.maps[o.mapping.maps.length-1],d.push(new Ps(g,void 0,void 0,d.length+u.length))),i--,g&&s.appendMap(g,i)}else o.maybeStep(p.step);if(p.selection)return l=s?p.selection.map(s.slice(i)):p.selection,c=new ds(this.items.slice(0,r).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(t,n,r,s){let i=[],o=this.eventCount,l=this.items,c=!s&&l.length?l.get(l.length-1):null;for(let u=0;u<t.steps.length;u++){let p=t.steps[u].invert(t.docs[u]),h=new Ps(t.mapping.maps[u],p,n),f;(f=c&&c.merge(h))&&(h=f,u?i.pop():l=l.slice(0,l.length-1)),i.push(h),n&&(o++,n=void 0),s||(c=h)}let d=o-r.depth;return d>One&&(l=Nne(l,d),o-=d),new ds(l.append(i),o)}remapping(t,n){let r=new $d;return this.items.forEach((s,i)=>{let o=s.mirrorOffset!=null&&i-s.mirrorOffset>=t?r.maps.length-s.mirrorOffset:void 0;r.appendMap(s.map,o)},t,n),r}addMaps(t){return this.eventCount==0?this:new ds(this.items.append(t.map(n=>new Ps(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],s=Math.max(0,this.items.length-n),i=t.mapping,o=t.steps.length,l=this.eventCount;this.items.forEach(h=>{h.selection&&l--},s);let c=n;this.items.forEach(h=>{let f=i.getMirror(--c);if(f==null)return;o=Math.min(o,f);let g=i.maps[f];if(h.step){let x=t.steps[f].invert(t.docs[f]),b=h.selection&&h.selection.map(i.slice(c+1,f));b&&l++,r.push(new Ps(g,x,b))}else r.push(new Ps(g))},s);let d=[];for(let h=n;h<o;h++)d.push(new Ps(i.maps[h]));let u=this.items.slice(0,s).append(d).append(r),p=new ds(u,l);return p.emptyItemCount()>Rne&&(p=p.compress(this.items.length-r.length)),p}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),r=n.maps.length,s=[],i=0;return this.items.forEach((o,l)=>{if(l>=t)s.push(o),o.selection&&i++;else if(o.step){let c=o.step.map(n.slice(r)),d=c&&c.getMap();if(r--,d&&n.appendMap(d,r),c){let u=o.selection&&o.selection.map(n.slice(r));u&&i++;let p=new Ps(d.invert(),c,u),h,f=s.length-1;(h=s.length&&s[f].merge(p))?s[f]=h:s.push(p)}}else o.map&&r--},this.items.length,0),new ds(Xn.from(s.reverse()),i)}}ds.empty=new ds(Xn.empty,0);function Nne(e,t){let n;return e.forEach((r,s)=>{if(r.selection&&t--==0)return n=s,!1}),e.slice(n)}class Ps{constructor(t,n,r,s){this.map=t,this.step=n,this.selection=r,this.mirrorOffset=s}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new Ps(n.getMap().invert(),n,this.selection)}}}class Fi{constructor(t,n,r,s,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=s,this.prevComposition=i}}const One=20;function Pne(e,t,n,r){let s=n.getMeta(Ha),i;if(s)return s.historyState;n.getMeta($ne)&&(e=new Fi(e.done,e.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return e;if(o&&o.getMeta(Ha))return o.getMeta(Ha).redo?new Fi(e.done.addTransform(n,void 0,r,wh(t)),e.undone,dE(n.mapping.maps),e.prevTime,e.prevComposition):new Fi(e.done,e.undone.addTransform(n,void 0,r,wh(t)),null,e.prevTime,e.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),c=e.prevTime==0||!o&&e.prevComposition!=l&&(e.prevTime<(n.time||0)-r.newGroupDelay||!Lne(n,e.prevRanges)),d=o?wx(e.prevRanges,n.mapping):dE(n.mapping.maps);return new Fi(e.done.addTransform(n,c?t.selection.getBookmark():void 0,r,wh(t)),ds.empty,d,n.time,l??e.prevComposition)}else return(i=n.getMeta("rebased"))?new Fi(e.done.rebased(n,i),e.undone.rebased(n,i),wx(e.prevRanges,n.mapping),e.prevTime,e.prevComposition):new Fi(e.done.addMaps(n.mapping.maps),e.undone.addMaps(n.mapping.maps),wx(e.prevRanges,n.mapping),e.prevTime,e.prevComposition)}function Lne(e,t){if(!t)return!1;if(!e.docChanged)return!0;let n=!1;return e.mapping.maps[0].forEach((r,s)=>{for(let i=0;i<t.length;i+=2)r<=t[i+1]&&s>=t[i]&&(n=!0)}),n}function dE(e){let t=[];for(let n=e.length-1;n>=0&&t.length==0;
177n--)e[n].forEach((r,s,i,o)=>t.push(i,o));return t}function wx(e,t){if(!e)return null;let n=[];for(let r=0;r<e.length;r+=2){let s=t.map(e[r],1),i=t.map(e[r+1],-1);s<=i&&n.push(s,i)}return n}function Fne(e,t,n){let r=wh(t),s=Ha.get(t).spec.config,i=(n?e.undone:e.done).popEvent(t,r);if(!i)return null;let o=i.selection.resolve(i.transform.doc),l=(n?e.done:e.undone).addTransform(i.transform,t.selection.getBookmark(),s,r),c=new Fi(n?l:i.remaining,n?i.remaining:l,null,0,-1);return i.transform.setSelection(o).setMeta(Ha,{redo:n,historyState:c})}let Sx=!1,uE=null;function wh(e){let t=e.plugins;if(uE!=t){Sx=!1,uE=t;for(let n=0;n<t.length;n++)if(t[n].spec.historyPreserveItems){Sx=!0;break}}return Sx}const Ha=new hn("history"),$ne=new hn("closeHistory");function zne(e={}){return e={depth:e.depth||100,newGroupDelay:e.newGroupDelay||500},new pn({key:Ha,state:{init(){return new Fi(ds.empty,ds.empty,null,0,-1)},apply(t,n,r){return Pne(n,r,t,e)}},config:e,props:{handleDOMEvents:{beforeinput(t,n){let r=n.inputType,s=r=="historyUndo"?rP:r=="historyRedo"?sP:null;return!s||!t.editable?!1:(n.preventDefault(),s(t.state,t.dispatch))}}}})}function nP(e,t){return(n,r)=>{let s=Ha.getState(n);if(!s||(e?s.undone:s.done).eventCount==0)return!1;if(r){let i=Fne(s,n,e);i&&r(t?i.scrollIntoView():i)}return!0}}const rP=nP(!1,!0),sP=nP(!0,!0);ln.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:e=>e.length,wordCounter:e=>e.split(" ").filter(t=>t!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=e=>{const t=e?.node||this.editor.state.doc;if((e?.mode||this.options.mode)==="textSize"){const r=t.textBetween(0,t.content.size,void 0," ");return this.options.textCounter(r)}return t.nodeSize},this.storage.words=e=>{const t=e?.node||this.editor.state.doc,n=t.textBetween(0,t.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let e=!1;return[new pn({key:new hn("characterCount"),appendTransaction:(t,n,r)=>{if(e)return;const s=this.options.limit,i=this.options.autoTrim;if(s==null||s===0||i===!1){e=!0;return}const o=this.storage.characters({node:r.doc});if(o>s){const l=o-s,c=0,d=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${s} characters. Content was automatically trimmed.`);const u=r.tr.deleteRange(c,d);return e=!0,u}e=!0},filterTransaction:(t,n)=>{const r=this.options.limit;if(!t.docChanged||r===0||r===null||r===void 0)return!0;const s=this.storage.characters({node:n.doc}),i=this.storage.characters({node:t.doc});if(i<=r||s>r&&i>r&&i<=s)return!0;if(s>r&&i>r&&i>s||!t.getMeta("paste"))return!1;const l=t.selection.$head.pos,c=i-r,d=l-c,u=l;return t.deleteRange(d,u),!(this.storage.characters({node:t.doc})>r)}})]}});var Bne=ln.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Sne(this.options)]}});ln.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new pn({key:new hn("focus"),props:{decorations:({doc:e,selection:t})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:s}=t,i=[];if(!n||!r)return Bt.create(e,[]);let o=0;this.options.mode==="deepest"&&e.descendants((c,d)=>{if(c.isText)return;if(!(s>=d&&s<=d+c.nodeSize-1))return!1;o+=1});let l=0;return e.descendants((c,d)=>{if(c.isText||!(s>=d&&s<=d+c.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(Qn.node(d,d+c.nodeSize,{class:this.options.className}))}),Bt.create(e,i)}}})]}});var Une=ln.create({name:"gapCursor",addProseMirrorPlugins(){return[_ne()]},extendNodeSchema(e){var t;const n={name:e.name,options:e.options,storage:e.storage};return{allowGapCursor:(t=It(st(e,"allowGapCursor",n)))!=null?t:null}}}),iP="placeholder",Kd=new hn("tiptap__placeholder"),pE=200;function hE(e){const{editor:t,placeholder:n,dataAttribute:r,pos:s,node:i,isEmptyDoc:o,hasAnchor:l,classes:{emptyNode:c,emptyEditor:d}}=e,u=[c];return o&&u.push(d),Qn.node(s,s+i.nodeSize,{class:u.join(" "),[r]:typeof n=="function"?n({editor:t,node:i,pos:s,hasAnchor:l}):n}
177)}function Vne({editor:e,options:t,dataAttribute:n,doc:r,selection:s}){var i,o;if(!(e.isEditable||!t.showOnlyWhenEditable))return null;const{anchor:c}=s,d=[],u=e.isEmpty,p={emptyEditor:t.emptyEditorClass,emptyNode:t.emptyNodeClass};if(t.showOnlyCurrent&&!t.includeChildren){const f=r.resolve(c),g=f.depth>0?f.node(1):f.nodeAfter,x=f.depth>0?f.before(1):c;if(g&&g.type.isTextblock&&df(g)){const b=c>=x&&c<=x+g.nodeSize;d.push(hE({editor:e,isEmptyDoc:u,dataAttribute:n,hasAnchor:b,placeholder:t.placeholder,classes:p,node:g,pos:x}))}}else{const f=Kd.getState(e.state),g=(i=f?.topPos)!=null?i:0,x=(o=f?.bottomPos)!=null?o:r.content.size;r.nodesBetween(g,x,(b,y)=>{const v=c>=y&&c<=y+b.nodeSize,C=!b.isLeaf&&df(b);return b.type.isTextblock&&(v||!t.showOnlyCurrent)&&C&&d.push(hE({editor:e,isEmptyDoc:u,dataAttribute:n,hasAnchor:v,placeholder:t.placeholder,classes:p,node:b,pos:y})),t.includeChildren})}return Bt.create(r,d)}function Wne(e){return e.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function Hne(e){const t=getComputedStyle(e),n=`${t.overflow} ${t.overflowY} ${t.overflowX}`;return/auto|scroll|overlay/.test(n)}function qne(e){let t=e;for(;t;){if(Hne(t))return t;const n=t.parentElement;if(!n){const r=t.getRootNode();if(r instanceof ShadowRoot){t=r.host;continue}return window}t=n}return window}function Gne(e){return e===window?{top:0,bottom:window.innerHeight}:e.getBoundingClientRect()}function Yne({doc:e,view:t,scrollContainer:n}){const r=t.dom.getBoundingClientRect(),s=n?Gne(n):{top:0,bottom:window.innerHeight},i=Math.max(r.top,s.top)-pE,o=Math.min(r.bottom,s.bottom)+pE;if(i>=o)return{top:0,bottom:e.content.size};const c=getComputedStyle(t.dom).direction==="rtl"?Math.max(r.right-2,r.left+2):r.left+2,d=t.posAtCoords({left:c,top:i+2}),u=t.posAtCoords({left:c,top:o-2});return{top:d?d.pos:0,bottom:u?u.pos:e.content.size}}var Kne={init(){return{topPos:null,bottomPos:null}},apply(e,t){const n=e.getMeta(Kd);return n?.positions?{topPos:n.positions.top,bottomPos:n.positions.bottom}:e.docChanged?{topPos:t.topPos!==null?e.mapping.map(t.topPos):null,bottomPos:t.bottomPos!==null?e.mapping.map(t.bottomPos):null}:t}};function Qne(e){const t=qne(e.dom),n=()=>{const l=Yne({view:e,doc:e.state.doc,scrollContainer:t}),c=Kd.getState(e.state);if(c?.topPos===l.top&&c?.bottomPos===l.bottom)return;const d=e.state.tr.setMeta(Kd,{positions:l});e.dispatch(d)};let r=null,s=0;const i=150,o=()=>{r===null&&(r=requestAnimationFrame(()=>{r=null;const l=performance.now();l-s>=i?(s=l,n()):o()}))};return t.addEventListener("scroll",o,{passive:!0}),n(),{update(l,c){e.state.doc.content.size!==c.doc.content.size&&o()},destroy:()=>{r!==null&&cancelAnimationFrame(r),t.removeEventListener("scroll",o)}}}function Jne({editor:e,options:t}){const n=t.dataAttribute?`data-${Wne(t.dataAttribute)}`:`data-${iP}`;return new pn({key:Kd,state:Kne,view:Qne,props:{decorations:({doc:r,selection:s})=>Vne({editor:e,options:t,dataAttribute:n,doc:r,selection:s})}})}ln.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:iP,placeholder:"Write something â¦",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[Jne({editor:this.editor,options:this.options})]}});ln.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:e,options:t}=this;return[new pn({key:new hn("selection"),props:{decorations(n){return n.selection.empty||e.isFocused||!e.isEditable||rO(n.selection)||e.view.dragging?null:Bt.create(n.doc,[Qn.inline(n.selection.from,n.selection.to,{class:t.className})])}}})]}});var Xne="skipTrailingNode";function fE({types:e,node:t}){return t&&Array.isArray(e)&&e.includes(t.type)||t?.type===e}var Zne=ln.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var e;const t=new hn(this.name),n=this.options.node||((e=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:e.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,s])=>s).filter(s=>(this.options.notAfter||[]).concat(n).includes(s.name));return[new pn({key:t,appendTransaction:(s,i,o)=>{const{doc:l,tr:c,schema:d}=o,u=t.getState(o),p=l.content.size,h=d.nodes[n];if(!s.some(f=>f.getMeta(Xne))&&u)return c.insert(p,h.create())},state:{init:(s,i)=>{const o=i.tr.doc.lastChild;return!fE({node:o,types:r})},apply:(s,i)=>{if(!s.docChanged||s.getMeta("__uniqueIDTransaction"))return i;const o=s.doc.lastChild;return!fE({node:o,types:r})}}})]}}),ere=ln.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:e,dispatch:t})=>rP(e,t),redo:()=>({state:e,dispatch:t})=>sP(e,t)}},addProseMirrorPlugins(){return[zne(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-Ñ":()=>this.editor.commands.undo(),"Shift-Mod-Ñ":()=>this.editor.commands.redo()}}});ln.create({name:"starterKit",addExtensions(){var e,t,n,r;const s=[];return this.options.bold!==!1&&s.push(Ite.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(jte.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(jO.configure(this.options.bulletList)),this.options.code!==!1&&s.push(Mte.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(Ote.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(Pte.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(Bne.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(Une.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(Lte.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(Fte.configure(this.options.heading)),this.options.undoRedo!==!1&&s.push(ere.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&s.push($te.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(Wte.configure(this.options.italic)),this.options.listItem!==!1&&s.push(kO.configure(this.options.listItem)),this.options.listKeymap!==!1&&s.push(AO.configure((e=this.options)==null?void 0:e.listKeymap)),this.options.link!==!1&&s.push(gne.configure((t=this.options)==null?void 0:t.link)),this.options.orderedList!==!1&&s.push(RO.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(xne.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(vne.configure(this.options.strike)),this.options.text!==!1&&s.push(Cne.configure(this.options.text)),this.options.underline!==!1&&s.push(wne.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&s.push(Zne.configure((r=this.options)==null?void 0:r.trailingNode)),s}});const tre=m.createContext({}),nre=()=>m.useContext(tre),rre=({node:e})=>{const t=nre(),n=typeof e.attrs.name=="string"?e.attrs.name:"",r=n?t[n]:void 0,s=n?`Missing file: ${n}`:"Invalid file reference";return a.jsx(VX,{as:"span",className:"canvas-file-reference",contentEditable:!1,"data-file-name":n,children:r?a.jsx(zB,{name:n,type:r.type,url:r.url}):a.jsx(T,{component:"span","aria-label":s,sx:{backgroundColor:"action.hover",borderRadius:1,color:"text.secondary",display:"inline-block",fontSize:"0.875rem",px:1,py:.25},children:s})})},gc="fileReference",sre=/^\[file:([^\]]+)\]/;Gn.create({name:gc,group:"inline",inline:!0,atom:!0,selectable:!0,draggable:!1,addAttributes(){return{name:{default:"",parseHTML:e=>e.getAttribute("data-file-name")??"",renderHTML:e=>({"data-file-name":typeof e.name=="string"?e.name:""})}}},parseHTML(){return[{tag:"span[data-file-name]"}]},renderHTML({HTMLAttributes:e}){return["span",e]},addNodeView(){return YX(rre)},markdownTokenName:gc,markdownTokenizer:{name:gc,level:"inline",start:e=>{Bk.lastIndex=0;const t=Bk.exec(e);return t?t.index:-1},tokenize:e=>{const t=sre.exec(e);if(!t)return;const[n,r]=t;return{type:gc,raw:n,name:r?.trim()??""}}},parseMarkdown:(e,t)=>{const n=typeof e.name=="string"?e.name:"";return t.createNode(gc,{name:n})},renderMarkdown:e=>`[file:${typeof e.attrs?.name=="string"?e.attrs.name:""}]`});const xc=new hn("persistSelectionHighlight"),ire="canvas-persisted-selection";ln.create({name:"persistSelectionHighlight",addProseMirrorPlugins(){return[new pn({key:xc,state:{init:()=>({focused:!1}),apply:(e,t)=>e.getMeta(xc)??t},props:{decorations:e=>{const t=xc.getState(e),{from:n,to:r,empty:s}=e.selection;return!t||t.focused||s?null:Bt.create(e.doc,[Qn.inline(n,r,{class:ire})])}
177,handleDOMEvents:{focus:e=>(e.dispatch(e.state.tr.setMeta(xc,{focused:!0})),!1),blur:e=>(e.dispatch(e.state.tr.setMeta(xc,{focused:!1})),!1)}}})]}});function are(e){var t;const{char:n,allowSpaces:r,allowToIncludeChar:s,allowedPrefixes:i,startOfLine:o,$position:l}=e,c=r&&!s,d=_X(n),u=new RegExp(`\\s${d}$`),p=o?"^":"",h=s?"":d,f=c?new RegExp(`${p}${d}.*?(?=\\s${h}|$)`,"gm"):new RegExp(`${p}(?:^)?${d}[^\\s${h}]*`,"gm"),g=((t=l.nodeBefore)==null?void 0:t.isText)&&l.nodeBefore.text;if(!g)return null;const x=l.pos-g.length,b=Array.from(g.matchAll(f)).pop();if(!b||b.input===void 0||b.index===void 0)return null;const y=b.input.slice(Math.max(0,b.index-1),b.index),v=new RegExp(`^[${i?.join("")}\0]?$`).test(y);if(i!==null&&!v)return null;const C=x+b.index;let w=C+b[0].length;return c&&u.test(g.slice(w-1,w+1))&&(b[0]+=" ",w+=1),C<l.pos&&w>=l.pos?{range:{from:C,to:w},query:b[0].slice(n.length),text:b[0]}:null}function ore(e){return e.docChanged?e.steps.some(t=>{const n=t.slice;if(!n?.content)return!1;const r=n.content.textBetween(0,n.content.size,` 178`);return/\s/.test(r)}):!1}var lre=new hn("suggestion");function cre({pluginKey:e=lre,editor:t,char:n="@",allowSpaces:r=!1,allowToIncludeChar:s=!1,allowedPrefixes:i=[" "],startOfLine:o=!1,decorationTag:l="span",decorationClass:c="suggestion",decorationContent:d="",decorationEmptyClass:u="is-empty",command:p=()=>null,items:h=()=>[],render:f=()=>({}),allow:g=()=>!0,findSuggestionMatch:x=are,shouldShow:b,shouldResetDismissed:y}){let v;const C=f?.(),w=r&&!s,S=()=>{const D=t.state.selection.$anchor.pos,M=t.view.coordsAtPos(D),{top:N,right:O,bottom:R,left:L}=M;try{return new DOMRect(L,N,O-L,R-N)}catch{return null}},E=(D,M)=>M?()=>{const N=e.getState(t.state),O=N?.decorationId,R=D.dom.querySelector(`[data-decoration-id="${O}"]`);return R?.getBoundingClientRect()||null}:S,k=({match:D,dismissedRange:M,state:N,transaction:O})=>y?.({editor:t,state:N,range:M,match:D,transaction:O,allowSpaces:w})?!1:w?D.range.from===M.from:D.range.from===M.from&&!ore(O);function j(D,M){var N;try{const R=e.getState(D.state),L=R?.decorationId?D.dom.querySelector(`[data-decoration-id="${R.decorationId}"]`):null,P={editor:t,range:R?.range||{from:0,to:0},query:R?.query||null,text:R?.text||null,items:[],command:F=>p({editor:t,range:R?.range||{from:0,to:0},props:F}),decorationNode:L,clientRect:E(D,L)};(N=C?.onExit)==null||N.call(C,P)}catch{}const O=D.state.tr.setMeta(M,{exit:!0});D.dispatch(O)}const _=new pn({key:e,view(){return{update:async(D,M)=>{var N,O,R,L,P,F,z;const B=(N=this.key)==null?void 0:N.getState(M),W=(O=this.key)==null?void 0:O.getState(D.state),H=B.active&&W.active&&B.range.from!==W.range.from,V=!B.active&&W.active,G=B.active&&!W.active,X=!V&&!G&&B.query!==W.query,K=V||H&&X,ie=X||H,le=G||H&&X;if(!K&&!ie&&!le)return;const ce=le&&!K?B:W,J=D.dom.querySelector(`[data-decoration-id="${ce.decorationId}"]`);v={editor:t,range:ce.range,query:ce.query,text:ce.text,items:[],command:he=>p({editor:t,range:ce.range,props:he}),decorationNode:J,clientRect:E(D,J)},K&&((R=C?.onBeforeStart)==null||R.call(C,v)),ie&&((L=C?.onBeforeUpdate)==null||L.call(C,v)),(ie||K)&&(v.items=await h({editor:t,query:ce.query})),le&&((P=C?.onExit)==null||P.call(C,v)),ie&&((F=C?.onUpdate)==null||F.call(C,v)),K&&((z=C?.onStart)==null||z.call(C,v))},destroy:()=>{var D;v&&((D=C?.onExit)==null||D.call(C,v))}}},state:{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(D,M,N,O){const{isEditable:R}=t,{composing:L}=t.view,{selection:P}=D,{empty:F,from:z}=P,B={...M},W=D.getMeta(e);if(W&&W.exit)return B.active=!1,B.decorationId=null,B.range={from:0,to:0},B.query=null,B.text=null,B.dismissedRange=M.active?{...M.range}:M.dismissedRange,B;if(B.composing=L,D.docChanged&&B.dismissedRange!==null&&(B.dismissedRange={from:D.mapping.map(B.dismissedRange.from),to:D.mapping.map(B.dismissedRange.to)}),R&&(F||t.view.composing)){(z<M.range.from||z>M.range.to)&&!L&&!M.composing&&(B.active=!1);const H=x({char:n,allowSpaces:r,allowToIncludeChar:s,allowedPrefixes:i,startOfLine:o,$position:P.$from}),V=`id_${Math.floor(Math.random()*4294967295)}`;H&&g({editor:t,state:O,range:H.range,isActive:M.active})&&(!b||b({editor:t,range:H.range,query:H.query,text:H.text,transaction:D}
178))?(B.dismissedRange!==null&&!k({match:H,dismissedRange:B.dismissedRange,state:O,transaction:D})&&(B.dismissedRange=null),B.dismissedRange===null?(B.active=!0,B.decorationId=M.decorationId?M.decorationId:V,B.range=H.range,B.query=H.query,B.text=H.text):B.active=!1):(H||(B.dismissedRange=null),B.active=!1)}else B.active=!1;return B.active||(B.decorationId=null,B.range={from:0,to:0},B.query=null,B.text=null),B}},props:{handleKeyDown(D,M){var N,O;const{active:R,range:L}=_.getState(D.state);if(!R)return!1;if(M.key==="Escape"||M.key==="Esc"){const F=_.getState(D.state);return(N=C?.onKeyDown)==null||N.call(C,{view:D,event:M,range:F.range}),j(D,e),!0}return((O=C?.onKeyDown)==null?void 0:O.call(C,{view:D,event:M,range:L}))||!1},decorations(D){const{active:M,range:N,decorationId:O,query:R}=_.getState(D);if(!M)return null;const L=!R?.length,P=[c];return L&&P.push(u),Bt.create(D.doc,[Qn.inline(N.from,N.to,{nodeName:l,class:P.join(" "),"data-decoration-id":O,"data-decoration-content":d})])}}});return _}const aP=m.forwardRef(({items:e,command:t},n)=>{const[r,s]=m.useState(0);m.useEffect(()=>{s(0)},[e]);const i=o=>{const l=e[o];l&&t(l)};return m.useImperativeHandle(n,()=>({onKeyDown:o=>e.length===0?!1:o.key==="ArrowUp"?(s(l=>(l+e.length-1)%e.length),!0):o.key==="ArrowDown"?(s(l=>(l+1)%e.length),!0):o.key==="Enter"?(i(r),!0):!1})),e.length===0?null:a.jsx(Br,{elevation:3,sx:{maxHeight:320,overflowY:"auto",width:240},children:a.jsx(rB,{dense:!0,disablePadding:!0,children:e.map((o,l)=>a.jsxs(Se,{selected:l===r,onMouseEnter:()=>s(l),onClick:()=>i(l),sx:{alignItems:"flex-start",flexDirection:"column",gap:.25,py:1},children:[a.jsx(I,{variant:"body2",sx:{fontWeight:"medium"},children:o.title}),o.description?a.jsx(I,{variant:"caption",color:"text.secondary",children:o.description}):null]},o.title))})})});aP.displayName="SlashCommandMenu";const mE=[{title:"Heading 1",description:"Large section heading",run:(e,t)=>e.chain().focus().deleteRange(t).setNode("heading",{level:1}).run()},{title:"Heading 2",description:"Medium section heading",run:(e,t)=>e.chain().focus().deleteRange(t).setNode("heading",{level:2}).run()},{title:"Heading 3",description:"Small section heading",run:(e,t)=>e.chain().focus().deleteRange(t).setNode("heading",{level:3}).run()},{title:"Bullet list",description:"Unordered list",run:(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()},{title:"Numbered list",description:"Ordered list",run:(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()},{title:"Task list",description:"Checklist with checkboxes",run:(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()},{title:"Quote",description:"Blockquote",run:(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()},{title:"Code block",description:"Fenced code block",run:(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()},{title:"Table",description:"3Ã3 table with header row",run:(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()},{title:"Divider",description:"Horizontal rule",run:(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()}],dre=e=>{const t=e.trim().toLowerCase();return t?mE.filter(n=>n.title.toLowerCase().includes(t)):mE};ln.create({name:"slashCommand",addOptions(){return{items:dre}},addProseMirrorPlugins(){return[cre({editor:this.editor,char:"/",startOfLine:!1,command:({editor:e,range:t,props:n})=>n.run(e,t),items:({query:e})=>this.options.items(e),render:()=>{let e=null,t=null;const n=r=>{if(!t||!r)return;const s=r();s&&(t.style.left=`${s.left}px`,t.style.top=`${s.bottom+4}px`)};return{onStart:r=>{e=new pO(aP,{editor:r.editor,props:{items:r.items,command:r.command}}),t=document.createElement("div"),t.style.position="fixed",t.style.zIndex="1300",t.appendChild(e.element),document.body.appendChild(t),n(r.clientRect)},onUpdate:r=>{e?.updateProps({items:r.items,command:r.command}),n(r.clientRect)},onKeyDown:r=>r.event.key==="Escape"?(t?.remove(),e?.destroy(),t=null,e=null,!0):e?.ref?.onKeyDown(r.event)??!1,onExit:()=>{t?.remove(),e?.destroy(),t=null,e=null}}}})]}});
178const ure=[{id:"kpi-overview",version:"0.1.3",name:"KPI overview",description:"One KPI over a date range, with a trend line and a breakdown by a grouping column.",file:"kpi-overview.html",config_schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:!1,required:["title","kpi","date_range","group_by","data_request"],properties:{title:{type:"string",minLength:1,maxLength:200},engagement:{$comment:"Injected server-side from the authz context. NOT part of the model-facing tool input: strip it if the model supplies it, inject, then validate. See §4.",type:"object",additionalProperties:!1,required:["nice_id","label"],properties:{nice_id:{type:"string"},label:{type:"string"}}},kpi:{type:"object",additionalProperties:!1,required:["id","name","format","up_is_good","aggregation"],properties:{id:{$comment:"Must be a kpi_nice_id active for this engagement (erm_kpi).",type:"string",minLength:1},name:{type:"string",minLength:1},format:{type:"string",enum:["currency","number","percent"]},currency:{$comment:"Required when format is currency.",type:"string",pattern:"^[A-Z]{3}$"},up_is_good:{type:"boolean"},aggregation:{$comment:"v0.1.x supports sum ONLY. Ratio/rate KPIs (ROAS, CVR, CPA) produce meaningless totals when summed, so the orchestrator declines them for this template until a version honours avg/last in its tiles. See §3.",type:"string",enum:["sum"]}}},date_range:{type:"object",additionalProperties:!1,required:["expression","start","end","grain","reresolve_on_refresh"],properties:{expression:{$comment:'What the user actually said ("last 30 days", "Q1 2026"). Never lost.',type:"string",minLength:1},start:{type:"string",format:"date",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},end:{type:"string",format:"date",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},grain:{type:"string",enum:["day","week","month"]},reresolve_on_refresh:{$comment:"true for relative expressions (they re-resolve to now on refresh, and the new start/end are written into the new version); false for absolute ones. This is the ONE config change a refresh may make.",type:"boolean"}}},group_by:{type:"object",additionalProperties:!1,required:["column","label"],properties:{column:{type:"string",minLength:1},label:{type:"string",minLength:1}}},comparison:{$comment:"Absent or null means no delta is rendered, and data.totals.previous is then not required.",type:["string","null"],enum:["previous_period","same_period_last_year",null]},data_request:{$comment:"Natural-language instruction the orchestrator replays to leaf agents on refresh. Subordinate to the structured fields above: the leaf request is composed from config + this, and returned data is validated against config before writing.",type:"string",minLength:1,maxLength:2e3}}},data_schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:!1,required:["as_of","timeseries","breakdown"],properties:{as_of:{type:"string",format:"date-time"},totals:{type:"object",additionalProperties:!1,properties:{previous:{type:["number","null"]}}},timeseries:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["date","value"],properties:{date:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},value:{type:"number"}}}},breakdown:{$comment:'Largest first; fold the tail into an "Other" row. Its sum is the ONE denominator for every share figure on the page.',type:"array",items:{type:"object",additionalProperties:!1,required:["key","value"],properties:{key:{type:"string"},value:{type:"number"}}}}}},cross_field_rules:[{id:"currency_required_for_currency_format",applies_to:"config",rule:"config.kpi.currency is required when config.kpi.format == 'currency'"},{id:"date_range_ordered",applies_to:"config",rule:"config.date_range.start <= config.date_range.end"},{id:"timeseries_within_range",applies_to:"config+data",rule:"every data.timeseries[].date falls within [config.date_range.start, config.date_range.end]"},{id:"breakdown_reconciles_with_timeseries",applies_to:"data",rule:"abs(sum(breakdown.value) - sum(timeseries.value)) / sum(timeseries.value) <= 0.02 â reject or annotate beyond 2%, so no two figures on the page disagree"},{id:"no_negative_values",applies_to:"data",rule:"v1 rejects negative values in timeseries and breakdown; the template degrades gracefully but the contract does not permit them"},{id:"previous_required_with_comparison",applies_to:"config+data",rule:"data.totals.previous must be present and numeric when config.comparison is set; the delta is hidden otherwise"}]},{id:"datasource-tracker",version:"0.1.3",name:"Data tracker",description:"Operational status of an engagement's datasources: ingestion freshness, owners, and pending actions by timeslice.",file:"datasource-tracker.html",config_schema:{$schema:"https://json-schema.org/draft/2020-12/schema",$comment:"Deliberately thin. This template is almost entirely data; there is nothing for a user to parameterise beyond the title. It has NO kpi and NO date_range â which is exactly why config schemas are per-template rather than frozen globally (§3).",type:"object",additionalProperties:!1,required:["title","data_request"],properties:{title:{type:"string",minLength:1,maxLength:200},engagement:{type:"object",additionalProperties:!1,required:["nice_id","label"],properties:{nice_id:{type:"string"},label:{type:"string"}}},data_request:{type:"string",minLength:1,maxLength:2e3}}},data_schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:!1,required:["as_of","summary","datasources"],properties:{as_of:{type:"string",format:"date-time"},summary:{$comment:"NOTE the absence of `statuses`. Status counts are DERIVED from datasources[] by the template, never stored â storing them beside the rows they summarise is the same defect class as two disagreeing share denominators. See §10.",type:"object",additionalProperties:!1,properties:{period_label:{type:"string"},next_timeslice:{type:"string"},meta:{type:"array",items:{type:"object",additionalProperties:!1,required:["label","value"],properties:{label:{type:"string"},value:{type:"string"},ok:{type:"boolean"}}}},extras:{type:"array",items:{type:"object",additionalProperties:!1,required:["label","value"],properties:{label:{type:"string"},value:{type:"string"},sub:{type:"string"}}}},warnings:{type:"array",items:{type:"object",additionalProperties:!1,required:["text"],properties:{text:{type:"string"}}}}}},actions:{type:"array",items:{type:"object",additionalProperties:!1,required:["label","urgency","items"],properties:{label:{type:"string"},note:{type:"string"},urgency:{type:"string",enum:["critical","upcoming","info"]},items:{type:"array",items:{type:"object",additionalProperties:!1,required:["datasource","db_through","owner","needed"],properties:{datasource:{type:"string"},db_through:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},owner:{$ref:"#/$defs/owner"},needed:{type:"string"}}}}}}},datasources:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","db_through","owner"],properties:{name:{type:"string"},status:{$comment:"Fixed four-state taxonomy in v1. The template maps these to the app status palette and always renders glyph + label, never colour alone.",type:"string",enum:["current","needs_action","expected_lag","inactive"]},db_through:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},owner:{$ref:"#/$defs/owner"},note:{type:"string"}}}},contacts:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","org"],properties:{name:{type:"string"},org:{type:"string"},owns:{type:"array",items:{type:"string"}},tbd:{type:"boolean"}}}}},$defs:{owner:{type:"object",additionalProperties:!1,required:["label"],properties:{label:{type:"string"},tbd:{type:"boolean"}}}}},cross_field_rules:[{id:"action_datasources_exist",applies_to:"data",rule:"every actions[].items[].datasource must appear in datasources[].name â an action referencing an unknown datasource is a data error, not a rendering edge case"},{id:"no_stored_status_counts",applies_to:"data",rule:"summary must NOT carry a statuses/count field; counts are derived from datasources[] by the template"}]}],pre={templates:ure};pre.templates.map(({id:e,name:t,description:n})=>({id:e,name:t,description:n}));m.lazy(()=>KZ(()=>import("./DashboardView-DFKNlqEN.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])).then(e=>({default:e.DashboardView})));const hre=3;Array.from({length:hre},(e,t)=>`file-list-skeleton-${t}`);const fre=3;Array.from({length:fre},(e,t)=>`version-history-skeleton-${t}`);m.createContext(null);m.createContext(null);const gE={type_name:["gl_type_name","type"],vehicle_name:["gl_vehicle_name","vehicle"],platform_name:["gl_platform_name","platform"],tactic_name:["gl_tactic_name","tactic"],account_name:["account_name"],campaign_name:["campaign_name"],adgroup_name:["adgroup_name","ad_group_name"],name:["media","placement_name"],program_name:["gl_program_name","program_name"],account_id:["account_id"],campaign_id:["campaign_id"],adgroup_id:["adgroup_id","ad_group_id"],country_name:["gl_country_name","country"],market_name:["gl_market_name","market"],datasource_name:["datasource_name","data_source"],vendor_nice_id:["vendor_nice_id"]},N0={vehicle:"vehicle_name",type:"type_name",platform:"platform_name",tactic:"tactic_name",country:"country_name",market:"market_name",data_source:"datasource_name"},mre=[/^theme_\d+$/,/^attribute_\d+$/],gre=new Set(["type_name","vehicle_name","platform_name","tactic_name","account_name","campaign_name","adgroup_name","name","program_name","account_id","campaign_id","adgroup_id","country_name","market_name","datasource_name","vendor_nice_id",...Object.keys(N0)]),oP=e=>gre.has(e)?!0:mre.some(t=>t.test(e)),xre=({active:e,dimension:t})=>e&&oP(t),bre=({dimension:e,dimension_type:t,title:n})=>{const r=e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ");return{label:n||r,value:e.startsWith("theme")?e:`${t}_${e}`}},yre=({universalPivots:e,flexPivotData:t,fieldDefinitions:n,filterFn:r,mapFn:s})=>{const i=new Set(e.map(f=>f.value)),o=n?[...n.taxonomy_fields||[],...n.campaign_fields||[],...n.campaign_id_fields||[],...n.data_source_fields||[]]:[],l=new Map(o.flatMap(f=>{const g=f.dimension.toLowerCase(),x=gE[g],b=[[g,f.active]];return x&&x.forEach(y=>{b.push([y,f.active])}),b})),{dimensionTitleMap:c,mappedDimensions:d}=t.filter(r).filter(f=>f.title).reduce((f,g)=>{const{dimension:x,title:b}=g,y=N0[x]||x;i.has(y)&&(f.dimensionTitleMap.set(y,b),f.mappedDimensions.add(x));const v=gE[y];return v&&v.filter(C=>
178i.has(C)).forEach(C=>{f.dimensionTitleMap.set(C,b),f.mappedDimensions.add(x)}),f},{dimensionTitleMap:new Map,mappedDimensions:new Set}),u=e.filter(f=>l.get(f.value)!==!1).map(f=>{const g=c.get(f.value);return g?{...f,label:g}:f}),h=t.filter(r).filter(f=>!d.has(f.dimension)).map(s).filter((f,g,x)=>g===x.findIndex(b=>b.value===f.value));return u.concat(h).sort((f,g)=>f.label.toLowerCase().localeCompare(g.label.toLowerCase()))},O0=(e,{filterFn:t=xre,mapFn:n=bre}={})=>{const{engagementId:r,engagementNiceId:s}=pe(),{data:i=[],isFetching:o}=Qs(r),l=i[0]?.brand_nice_id??"",{data:c=[],isFetching:d}=wm({brandNiceId:l,engagementNiceId:s},{skip:!l||!s}),{data:u=[],isFetching:p}=dC({brandNiceId:l,engagementNiceId:s},{skip:!l||!s}),{data:h,isFetching:f}=wA({engagementNiceId:s,brandNiceId:l},{skip:!l||!s}),g=o||d||p||f,x=m.useMemo(()=>yre({universalPivots:e,flexPivotData:[...c,...u],fieldDefinitions:h,filterFn:t,mapFn:n}),[c,h,t,n,u,e]);return{pivotsLoading:g,pivotOptions:x}},pr=({actionMap:e,eventName:t})=>{const{mpTrack:n}=tr();return(s,i)=>{n(hR[t],{actionType:e[s],actionData:{...i}})}},vre=(e,t)=>{let n=e;return t&&Object.entries(t).forEach(([r,s])=>{n=n.replace(`:${r}`,String(s))}),n},en=()=>{const e=Hv();return(n,{pathParams:r,searchParams:s,state:i,replace:o=!1}={})=>{const l=vre(n,r);e({pathname:l,search:s?BB(s).toString():void 0},{state:i,replace:o})}},lP=()=>{const{engagementId:e}=pe(),t=yn({authorized:"ROAS"}),{data:n=null,isFetching:r}=SA(e);return{getKpiConfig:m.useCallback(i=>{if(!n)return{valuePerConversion:null,kpiScalar:null};const o=n.kpis.find(l=>l.kpi_nice_id===i);return{valuePerConversion:t?o?.value_per_conversion??null:null,kpiScalar:o?.kpi_scalar??null}},[n,t]),isLoadingConfig:r}},Zm=e=>{const{getKpiConfig:t,isLoadingConfig:n}=lP();return{...m.useMemo(()=>t(e),[t,e]),isLoadingConfig:n}},cP=e=>{const{valuePerConversion:t}=Zm(e);return t},Cre=()=>pr({actionMap:g7,eventName:"chatbot"}),wre=()=>pr({actionMap:x7,eventName:"chatbotFeedback"}),Sre=()=>{const{accessToken:e,userGivenName:t}=gt(),{engagementId:n}=pe(),{llmAssistantName:r,providerNiceId:s,pushNotification:i,raiseConversationIcon:o}=jt(),l=Cre(),c=wre(),d=m.useCallback(({promptPreview:u,status:p})=>
178{i({content:p==="complete"?`Background task completed: "${u}"`:`Background task failed: "${u}"`,severity:p==="complete"?"success":"error",timeout:8e3})},[i]);return a.jsx(m7,{accessToken:e,feedbackMpTrack:c,engagementId:n,llmAssistantName:r,mpTrack:l,onJobNotification:d,providerNiceId:s,raiseConversationIcon:o,userGivenName:t})},xE=40,$y=rt(T,{shouldForwardProp:e=>e!=="collapsed"})(({collapsed:e,theme:t})=>({backgroundColor:t.palette.background.paper,borderRight:`1px solid ${t.palette.divider}`,boxShadow:t.palette.mode==="dark"?"2px 0 4px rgba(0, 0, 0, 0.5)":"2px 0 4px rgba(0, 0, 0, 0.04)",display:"flex",flexDirection:"column",flexShrink:0,gap:t.spacing(1),height:`calc(100vh - ${xE}px)`,justifyContent:"space-between",paddingBottom:t.spacing(1),paddingLeft:t.spacing(e?1:2),paddingRight:t.spacing(e?1:2),paddingTop:t.spacing(3),position:"sticky",top:xE,transition:t.transitions.create("width",{duration:t.transitions.duration.shorter,easing:t.transitions.easing.easeInOut}),width:e?60:240,zIndex:1e3,"& > .MuiIconButton-root":{position:"absolute"}})),jre=()=>a.jsxs($y,{"data-testid":"navbar-header-loading",sx:{overflow:"hidden"},children:[a.jsx(fe,{variant:"rectangular",height:40,sx:{width:"100%"}}),a.jsx(fe,{variant:"rectangular",sx:{flexGrow:1,width:"100%"}}),a.jsx(fe,{variant:"rounded",height:60,sx:{width:"100%"}})]}),kre=()=>{const{isAppError:e,isAppLoading:t,supportLink:n}=jt(),{userIsInternal:r}=gt(),{engagementId:s}=pe(),i=jA(),{currentUserEngagement:o,userEngagements:l}=yu(s);return m.useMemo(()=>({currentUserEngagement:o,isAppError:e,isAppLoading:t,setErmState:i,supportLink:n,userEngagements:l,userIsInternal:r}),[o,e,t,i,n,l,r])},Ere=250,_re=()=>{const[e,t]=m.useState(!1),n=_l(),r=en(),{pathname:s}=es(),{currentUserEngagement:i,isAppError:o,isAppLoading:l,setErmState:c,supportLink:d,userEngagements:u,userIsInternal:p}=kre(),h=x=>{c({clientId:x.client_id,engagementId:x.engagement_id})},f=x=>{r(x)},g=m.useCallback(()=>{t(x=>!x),setTimeout(()=>{window.dispatchEvent(new Event("resize"))},Ere)},[]);return o?(We("Cannot load app."),a.jsx($y,{component:"nav",collapsed:!1,children:a.jsx(T,{sx:{display:"flex",flexDirection:"column",flexGrow:1,gap:3,mb:1,overflow:"hidden"}})})):l||!i?a.jsx(jre,{}):a.jsxs($y,{component:"nav",collapsed:e,"data-testid":"nav:container",children:[a.jsx(be,{title:e?"Expand sidebar":"Collapse sidebar",placement:"right",children:a.jsx(Ie,{onClick:g,size:"small",sx:{bgcolor:"background.paper",border:"1px solid",borderColor:"border.default",position:"absolute",right:-12,top:16,zIndex:1,"&:hover":{bgcolor:"background.neutral.hovered"}},"aria-label":e?"Expand sidebar":"Collapse sidebar",children:e?a.jsx(yl,{size:16}):a.jsx(UB,{size:16})})}),a.jsxs(T,{sx:{display:"flex",flexDirection:"column",flexGrow:1,gap:e?2:3,mb:1,overflow:"hidden"},children:[!e&&a.jsx(T,{sx:{alignSelf:"center",width:"100%"},children:a.jsx(VB,{currentEngagement:i,isInternalUser:p,options:u,setCurrentEngagement:h,testId:"nav:erm-selector"})}),a.jsx(rG,{collapsed:e,currentPath:s,featuresConfig:n,onClickMenuItem:f,supportLink:d})]})]})},Tre=({disabled:e,featuresConfig:t,mevoNavigate:n,signUserOut:r,supportLink:s,userIsFeaturesAdmin:i})=>{const{isDarkMode:o,toggleDarkMode:l}=VD(),c=!e&&i,d=!e&&!!t["Settings.UserManagement"],u=!e&&!!t["Settings.UserActivity"],p=m.useCallback(f=>{window.open(f,"_blank","noopener,noreferrer")},[]);return m.useMemo(()=>[{kind:"item",key:"configuration",icon:WB,label:"Configuration",onClick:()=>n("/settings/configuration"),disabled:e},{kind:"item",key:"feature-management",icon:HB,label:"Feature Management",onClick:()=>n("/settings/feature-management"),disabled:e,hidden:!c},{kind:"divider",key:"divider-configuration-users"},{kind:"item",key:"user-management",icon:qB,label:"User Management",onClick:()=>n("/settings/user-management"),disabled:e,hidden:!d},{kind:"item",key:"user-activity",icon:GB,label:"User Activity",onClick:()=>n("/settings/user-activity"),disabled:e,hidden:!u},{kind:"divider",key:"divider-users-links"},{kind:"item",key:"support",icon:YB,label:"Support",onClick:()=>p(s),hidden:!s},{kind:"item",key:"privacy",icon:KB,label:"Privacy & Cookies",onClick:()=>p(A6)},{kind:"divider",key:"divider-links-theme"},{kind:"item",key:"theme",icon:QB,label:o?"Dark":"Light",onClick:l,closeOnClick:!1,trailing:a.jsx(XB,{checked:o,inputProps:{"aria-label":"toggle theme"},size:"small"})},{kind:"divider",key:"divider-theme-signout"},{kind:"item",key:"signout",icon:JB,label:"Sign Out",onClick:()=>{r()},tone:"danger"}],[e,p,o,n,c,d,u,r,s,l])},Ire=()=>{const e=en(),{isAppError:t,isAppLoading:n,signUserOut:r,supportLink:s,userLoading:i}=jt(),{userInitials:o,userIsFeaturesAdmin:l,userIsInternal:c,userFamilyName:d,userGivenName:u}=gt(),{clientNiceId:p,engagementNiceId:h}=pe(),{alertCounts:f,alertsLoading:g}=MC({clientNiceId:p,engagementNiceId:h,userIsInternal:c}
178),x=_l(),b=f.dataingestion[h]??0,{palette:y}=Re(),v=y.name==="plusco",C=v?"AIOS":"Marketing Evolution",w=v?$h:hs.companyLogoDark,S=`${u} ${d}`,k=Tre({disabled:t||n||i||g,featuresConfig:x,mevoNavigate:e,signUserOut:r,supportLink:s,userIsFeaturesAdmin:l}),j=m.useCallback(()=>{e("/settings/alerts")},[e]);return m.useMemo(()=>({alertsLoading:g,companyLogoDark:w,currentEngagementAlertsCount:b,onClickAlerts:j,settingsMenuDescriptors:k,title:C,userFullName:S,userInitials:o,userLoading:i}),[g,w,b,j,k,C,S,o,i])},Dre=({onOpenProfileModal:e})=>{const{alertsLoading:t,companyLogoDark:n,currentEngagementAlertsCount:r,onClickAlerts:s,settingsMenuDescriptors:i,title:o,userFullName:l,userInitials:c,userLoading:d}=Ire();return a.jsxs(ZB,{sx:{pl:4},title:n?a.jsx(T,{alt:`${o} logo`,component:"img",src:n,sx:{display:"block",flexShrink:0,height:24,width:"auto"}}):a.jsx(I,{sx:{color:"common.white",flexShrink:0,fontSize:14,fontWeight:600},variant:"h6",children:o}),children:[a.jsx(eU,{disabled:t,onClick:s,unreadCount:r}),a.jsx(tU,{items:i}),a.jsx(nU,{ariaLabel:l?void 0:"User profile",fullName:l,initials:c,isLoading:d,onClick:e})]})},Are="2.30.0",Mre="4448",Rre=()=>a.jsx(T,{sx:{height:"100%",p:8,width:"100%"},children:a.jsx(fe,{variant:"rounded",height:"100%",width:"100%"})}),Nre=e=>JSON.stringify({mcpServers:{[e.engagement_nice_id]:{command:"<your-mcp-command-here>",args:[],env:{ENGAGEMENT_ID:String(e.engagement_id),CLIENT_ID:String(e.client_id)}}}},null,2),Ore=e=>`https://mcp.example.com/connect?engagement=${e.engagement_nice_id}`,Pre=e=>JSON.stringify({engagement_id:e.engagement_id,engagement_name:e.engagement_name,client_id:e.client_id,client_name:e.client_name},null,2),Lre=()=>{const[e,{isLoading:t}]=uC(),n=lC(),r=m.useCallback(async()=>{const l=await EC(),c=await sl({forceRefresh:!0}),d=cC.parse({username:l.username,userId:l.userId,signInDetails:l.signInDetails,session:c});n({validatedUser:d})},[n]),s=m.useCallback(async(l,c)=>{await e({body:l,username:c}).unwrap(),await r()},[e,r]),i=m.useCallback(async(l,c)=>{await BH({oldPassword:l,newPassword:c})},[]),o=m.useCallback(async l=>{await new Promise(c=>{setTimeout(c,500)})},[]);return{handleUpdateProfile:s,handleChangePassword:i,handleSaveMcpEngagement:o,isUpdatingProfile:t}},Fre=()=>{const{engagementId:e}=pe(),{currentUserEngagement:t,userEngagements:n}=yu(e),{userEmail:r,userFamilyName:s,userGivenName:i,userInitials:o,username:l}=gt(),{handleUpdateProfile:c,handleChangePassword:d,handleSaveMcpEngagement:u}=Lre();return{modalProps:{currentUserEngagement:t,generateChatGptUrl:Ore,generateClaudeDesktopConfig:Nre,generateOtherClientsConfig:Pre,onChangePassword:d,onSaveMcpEngagement:u,onUpdateProfile:c,userData:{userEmail:r??"",userFamilyName:s??"",userGivenName:i??"",userInitials:o??"",username:l??""},userEngagements:n??[]}}},$re=40,zre=["/data-pipeline/processing","/data-sources/name-cleaning","/settings/alerts","/settings/user-management"],bE=({pageName:e=null,suspense:t=!1})=>{const{pathname:n}=es(),{isAppLoading:r,isAppError:s,pushNotification:i}=jt(),{notifications:o,clearNotification:l}=OD(),{modalProps:c}=Fre(),u=!!_l()["Chat.MCP"],[p,h]=m.useState(!1),f=m.useCallback(()=>{h(!0)},[]),g=m.useCallback(()=>{h(!1)},[]),x=m.useCallback(({message:y,severity:v})=>{i({content:y,severity:v,timeout:4e3})},[i]),b=!zre.includes(n);return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",minHeight:"100vh"},children:[a.jsx(Dre,{onOpenProfileModal:f}),a.jsxs(T,{sx:{display:"flex",flexGrow:1,minHeight:`calc(100vh - ${$re}px)`},children:[a.jsx(_re,{}),a.jsx(ar,{authorized:"Chat",children:a.jsx(Sre,{})}),a.jsxs(T,{component:"main",sx:y=>({background:y.palette.surface.brand,display:"flex",flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",padding:"28px 32px 44px 32px"}),children:[a.jsx(T,{sx:{flexGrow:1,minWidth:0,overflow:"auto"},children:r||t?a.jsx(Rre,{}):s?a.jsxs(T,{sx:{alignItems:"center",display:"flex",flexDirection:"column",gap:2,justifyContent:"center",minHeight:400},children:[a.jsx(I,{color:"error",variant:"h6",children:"Unable to load application data"}),a.jsx(I,{color:"text.secondary",variant:"body2",children:"Please try refreshing the page or contact support if the issue persists."})]}):a.jsx(BY,{FallbackComponent:_6,children:b?a.jsx(wj,{}):a.jsxs(T,{sx:{display:"flex",flexDirection:"column",m:0},children:[e?a.jsx(I,{variant:"h5",sx:{mb:3},children:e}):a.jsx(T,{sx:{height:52}}),a.jsx(Br,{sx:{p:2},children:a.jsx(wj,{})})]})})}),a.jsx(rU,{build:Mre,version:Are})]}),a.jsx(sU,{notifications:o,onClose:l})]}),a.jsx(iU,{...c,onClose:g,onNotify:x,open:p,showMcpTab:u})]})},Bre=[["/data-utilities/dashboards/:id","/visualize/dashboards/:id"],["/data-utilities/dashboards","/visualize/dashboards"],["/insights/conversion-summary","/reports-insights/conversion-summary"],["/insights/conversion-lookback","/reports-insights/conversion-lookback"],["/insights/journey","/reports-insights/journey"],["/insights/geography","/reports-insights/geography"],["/insights/external-factors","/reports-insights/external-factors"],["/audience","/reports-insights/audiences"],["/data-exports/media-reporting","/reports-insights/media-reporting"],["/data-exports/attribution-reporting","/exports/attribution"],["/data-exports/data-delivery","/exports/export-configuration"],["/data-utilities/data-sources","/data-sources/configurations"],["/data-utilities/data-connections","/data-sources/connections"],["/data-utilities/file-upload","/data-sources/file-upload"],["/data-utilities/query-studio","/data-sources/query-studio"],["/data-utilities/name-cleaning","/data-sources/name-cleaning"],["/data-utilities/data-verification","/data-pipeline/data-validation"],["/data-utilities/data-orchestration","/data-pipeline/processing"],["/data-utilities/machine-learning/objective/:objective_id","/data-pipeline/machine-learning/objective/:objective_id"],["/data-utilities/machine-learning","/data-pipeline/machine-learning"],["/data-utilities/data-display-settings","/data-pipeline/display-settings"]],P0=m.createContext(null),Du=()=>m.useContext(P0),dP={allUsers:"All Users",internal:"Internal",external:"External"},lr={overview:"Overview",visualize:"Visualize","reports-insights":"Reports & Insights",planning:"Planning",exports:"Exports","data-sources":"Data Sources","data-
178pipeline":"Data Pipeline",alerts:"Alerts"},Ure=e=>e in lr,jd={users:"users",applications:"applications",date:"date",activity:"activity"},jx=(e,t,n)=>{const{engagementNiceId:r}=pe(),[s]=z5(),i=ct(),{selectedActivityFilterValue:o,selectedApplicationFilterValue:l,selectedUserFilterValue:c,dateRange:d,currentSelectedFilter:u,timePeriod:p}=n;m.useEffect(()=>{if(!d?.[0]||!d?.[1]||u===jd.activity&&e===Fs.activity)return;t({type:e===Fs.activity?"updateActivityLoading":"updateActivityDetailsLoading",value:!0}),t({type:"updateError",value:null});const h={engagement_nice_id:r,start_date:d[0].format("YYYY-MM-DD"),end_date:d[1].format("YYYY-MM-DD"),group_by:e,time_period:p};o&&o!=="allActivity"&&u==="activity"&&(h.activity=Sl[o]),l.length>0&&l.length<Object.keys(lr).length&&(h.applications=[...l]),c&&c!==nl.allUsers&&(h.user_type=c),s(h).then(g=>{if(!i())return;if(t({type:e===Fs.activity?"updateActivityLoading":"updateActivityDetailsLoading",value:!1}),g.error){const b=e===Fs.application?"updateDataByApplication":e===Fs.userType?"updateDataByUserType":"updateDataByActivityType";t({type:b,value:null}),t({type:"updateError",value:"Unable to load user activity data. Please try again later."});return}const x=e===Fs.application?"updateDataByApplication":e===Fs.userType?"updateDataByUserType":"updateDataByActivityType";g.data&&g.data.data.length?t({type:x,value:g.data}):t({type:x,value:null})})},[t,i,o,c,l,s,r,e,d,p])},Vre=({children:e,state:t,dispatch:n})=>{const r=m.useMemo(()=>({state:t,dispatch:n}),[t,n]);return jx(Fs.activity,n,t),jx(Fs.application,n,t),jx(Fs.userType,n,t),a.jsx(P0.Provider,{value:r,children:e})},Wre=(e,t)=>{switch(t.type){case"updateDialogState":return{...e,dialogState:{...t.value,filtersState:e.dialogState.filtersState}};case"updateDialogFilter":return{...e,dialogState:{...e.dialogState,filtersState:{...e.dialogState.filtersState,[t.filterName]:t.value}}};case"updateDataByActivityType":return{...e,dataByActivityType:t.value};case"updateDataByApplication":return{...e,dataByApplication:t.value};case"updateDataByUserType":return{...e,dataByUserType:t.value};case"updateUserFilterValue":return{...e,selectedUserFilterValue:t.value,dialogState:{...e.dialogState,filtersState:{...e.dialogState.filtersState,userFilter:t.value}}};case"updateApplicationFilterValue":return{...e,selectedApplicationFilterValue:t.value,dialogState:{...e.dialogState,filtersState:{...e.dialogState.filtersState,applicationsFilter:t.value}}};case"updateActivityFilterValue":return{...e,selectedActivityFilterValue:t.value,dialogState:{...e.dialogState,filtersState:{...e.dialogState.filtersState,activityFilter:t.value}}};case"updateActivityLoading":return{...e,activityLoading:t.value};case"updateActivityDetailsLoading":return{...e,activityDetailsLoading:t.value};case"updateDateRange":return{...e,dateRange:t.value,dialogState:{...e.dialogState,filtersState:{...e.dialogState.filtersState,dateRange:t.value}}};case"updateCurrentSelectedFilter":return{...e,currentSelectedFilter:t.value};case"updateTimePeriod":return{...e,timePeriod:t.value};case"updateError":return{...e,error:t.value};default:return e}},uP=e=>Z(e).format("MMM YYYY"),pP=e=>{const t=[];return e?.data&&e.data.forEach(n=>{const{timePeriod:r}=n;let s=t.find(o=>o.timePeriod===r);s||(s={timePeriod:r,actions:0,visits:0},t.push(s));const i=n.activityName==="Actions"?"actions":"visits";s[i]+=n.activity}),t},Hre=({data:e})=>{const t=[];return e.forEach(n=>{const{timePeriod:r}=n;let s=t.find(o=>o.timePeriod===r);s||(s={timePeriod:r,internal:0,external:0},t.push(s));const i=n.userType==="internal"?"internal":"external";s[i]+=n.uniqueVisitors}),t},qre=e=>[{field:"timePeriod",headerName:e==="week"?"Week":"Month",sortable:!1,width:220,valueFormatter:t=>e==="week"?`Week ${t.value}`:Date.parse(`${t.value}`)?uP(`${t.value}`):t.value},{field:"visits",headerName:"Visiting",sortable:!1,width:220,renderCell:t=>a.jsx(ft,{fractionDigits:0,value:Number(t.value)})},{field:"actions",headerName:"Activity",sortable:!1,width:220,renderCell:t=>a.jsx(ft,{fractionDigits:0,value:Number(t.value)})},{field:"total",headerName:"Total",sortable:!1,width:220,flex:1,renderCell:t=>a.jsx(ft,{fractionDigits:0,value:Number(t.value)})}],Gre=[{field:"internal",headerName:"Internal",sortable:!1,width:220,renderCell:e=>a.jsx(ft,{fractionDigits:0,value:Number(e.value)})},{field:"external",headerName:"External",sortable:!1,width:220,renderCell:e=>a.jsx(ft,{fractionDigits:0,value:Number(e.value)})}],Yre=(e,t)=>
178[{field:"timePeriod",headerName:t==="week"?"Week":"Month",width:220,flex:1,valueFormatter:n=>Date.parse(`${n.value}`)?t==="week"?`Week ${n.value}`:uP(`${n.value}`):n.value},...e?Gre:[],{field:"total",headerName:"Total",sortable:!1,flex:1,width:220,renderCell:n=>a.jsx(ft,{fractionDigits:0,value:Number(n.value)})}],Kre=e=>e.map(t=>({id:t.timePeriod,timePeriod:t.timePeriod,actions:t.actions,visits:t.visits,total:(t.actions||0)+(t.visits||0)})),Qre=e=>e.map(t=>({id:t.timePeriod,timePeriod:t.timePeriod,internal:t.internal,external:t.external,total:(t.internal||0)+(t.external||0)})),Jre=e=>`${e}-${new Date().toISOString()}`,Xre=e=>({export:{csv:{filename:e},png:{filename:e},svg:{filename:e}}}),yE=(e,t)=>({...t,toolbar:{...t?.toolbar,...Xre(e)}}),hP=e=>({chart:{type:"bar",height:350,stacked:!0,foreColor:e.palette.grey[600],fontFamily:e.typography.fontFamily,events:{click:(t,n,r)=>{const{className:s}=t.target;if(typeof s!="string")return;let i;if(s.includes("exportCSV")?i="csv":s.includes("exportSVG")?i="svg":s.includes("exportPNG")&&(i="png"),i){const{[i]:o}=r.config.chart.toolbar.export;o.filenameWithoutTimestamp||=o.filename,o.filename=Jre(o.filenameWithoutTimestamp)}}},toolbar:{show:!0,tools:{download:`<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none !important"> 179 <path d="M17.5 12.5V15.8333C17.5 16.2754 17.3244 16.6993 17.0118 17.0118C16.6993 17.3244 16.2754 17.5 15.8333 17.5H4.16667C3.72464 17.5 3.30072 17.3244 2.98816 17.0118C2.67559 16.6993 2.5 16.2754 2.5 15.8333V12.5" stroke="#5A566A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 180 <path d="M5.8335 8.33337L10.0002 12.5L14.1668 8.33337" stroke="#5A566A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 181 <path d="M10 12.5V2.5" stroke="#5A566A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 182</svg>`}},zoom:{enabled:!1}},responsive:[{breakpoint:480,options:{legend:{position:"bottom",offsetX:-10,offsetY:0}}}],plotOptions:{bar:{horizontal:!1,columnWidth:"60%",borderRadius:6,dataLabels:{total:{enabled:!1}}}},xaxis:{categories:[],axisBorder:{show:!1},axisTicks:{show:!1}},yaxis:{labels:{offsetX:-6,formatter:t=>new Intl.NumberFormat("en",{notation:"compact"}).format(t)}},dataLabels:{enabled:!1},legend:{position:"top",horizontalAlign:"right",markers:{radius:8}},fill:{opacity:1},grid:{show:!1,padding:{left:-5,right:0,top:0,bottom:0}},tooltip:{y:{formatter:t=>new Intl.NumberFormat("en",{maximumFractionDigits:0}).format(t)}}}),Zre=e=>({...hP(e)}),fP=rt(ua)(({theme:e})=>({".apexcharts-menu-icon svg":{fill:"none !important"},".apexcharts-menu-icon":{transform:"none"},".apexcharts-tooltip.apexcharts-theme-light":{backgroundColor:e.palette.background.paper,border:`1px solid ${e.palette.border.default}`,color:e.palette.text.primary},".apexcharts-tooltip.apexcharts-theme-light .apexcharts-tooltip-title":{backgroundColor:e.palette.surface.tertiary,borderBottom:`1px solid ${e.palette.border.default}`,color:e.palette.text.primary},".apexcharts-toolbar":{marginTop:"-28px !important",position:"sticky",left:0},".apexcharts-canvas":{display:"flex",flexDirection:"row",alignItems:"flex-start"},".apexcharts-svg":{overflow:"visible",padding:"2px"}})),mP=(e,t)=>{const n=hP(e);return{...n,chart:{...n.chart,stacked:!1,type:"line",toolbar:{}},legend:{...n.legend,showForSingleSeries:!0,horizontalAlign:"left"},stroke:{curve:"straight",width:2},xaxis:{...n.xaxis,categories:t},yaxis:{labels:{offsetX:-15,formatter:r=>new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:0}).format(r)}},tooltip:{y:{formatter:r=>new Intl.NumberFormat("en",{maximumFractionDigits:0}).format(r||0)}}}},gP=({...e})=>a.jsxs($,{alignItems:"center",direction:"column",sx:{minHeight:"150px"},justifyContent:"center",gap:1.5,...e,children:[a.jsx(IM,{sx:{width:40,height:40},color:"disabled"}),a.jsx(I,{variant:"subtitle1",color:"text.disabled",children:"not available"})]}),L0=({children:e,isDataEmpty:t})=>t?a.jsx(gP,{}):a.jsx("div",{children:e}),ese=["33%","55%","80%","65%","55%","43%"],tse=()=>a.jsxs(T,{height:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:30,width:"50%"}),a.jsx($,{sx:{width:"100%",pl:"40px",pb:"40px",height:"250px"},direction:"row",spacing:2,alignItems:"flex-end",children:ese.map((e,t)=>a.jsx(fe,{variant:"rounded",animation:"pulse",height:e,sx:{flex:1}},`skeleton-item-${t}`))})]}),nse=rt(ua)(({theme:e})=>({".apexcharts-menu-icon svg":{fill:"none !important"},".apexcharts-menu-icon":{transform:"none",top:"-45px",right:"30px"},".apexcharts-tooltip.apexcharts-theme-light":{backgroundColor:e.palette.background.paper,border:`1px solid ${e.palette.border.default}`,color:e.palette.text.primary},".apexcharts-tooltip.apexcharts-theme-light .apexcharts-tooltip-title":{backgroundColor:e.palette.surface.tertiary,borderBottom:`1px solid ${e.palette.border.default}`,color:e.palette.text.primary}})),vE=({title:e,titleValue:t,tableType:n,options:r,series:s})=>{const{state:i,dispatch:o}=Du(),{activityLoading:l,dataByActivityType:c}=i,{palette:d}=Re(),u=()=>{o({type:"updateDialogState",value:{isOpen:!0,tableType:n}})};return a.jsx(Ve,{sx:{flex:1},children:a.jsx(Ue,{sx:{height:"100%",position:"relative"},children:l?a.jsx(tse,{}):a.jsxs(a.Fragment,{children:[typeof t=="string"?a.jsx(I,{variant:"h5",children:t}):t||a.jsx(I,{variant:"h5",color:"text.disabled",children:"n/a"}),a.jsx(I,{children:e}),a.jsx(gi,{onClick:u,sx:{position:"absolute",right:"27px",top:"37px",cursor:"pointer",color:d.text.secondary},children:a.jsx(GD,{size:20})}),a.jsx(L0,{isDataEmpty:!l&&c?.data?.length===0,children:a.jsx(nse,{options:r,series:s,type:"bar"})})]})})})},rse=()=>{const e=Re(),{palette:{chartBrand:t}}=e,{state:n}=m.useContext(P0),r=Zre(e),s=(l,c)=>c.map(d=>{let u=d;if(n.timePeriod==="month"){const p=Z(d,{format:"YYYY-MM-DD HH:mm:ss"});u=p.isValid()?p.format("MMM"):"Invalid Date"}return{y:l[d]||0,x:u}}),i=l=>l.sort((c,d)=>Z(c).isAfter(Z(d))?1:-1),o=m.useMemo(()=>{const l={},c={},d={},u=new Set,p=n.dataByActivityType?.data||[];pP(n.dataByActivityType).forEach(({actions:f,visits:g,timePeriod:x})=>{x&&(u.add(x),l[x]=f,c[x]=g)}),p.forEach(({uniqueVisitorsByTimePeriod:f,timePeriod:g})=>{g&&(u.add(g),d[g]=f)});const h=i(Array.from(u));return{chartSeriesActions:s(l,h),chartSeriesVisits:s(c,h),chartSeriesVisitors:s(d,h)}},[n]);return a.jsxs(T,{children:[a.jsx(I,{variant:"h6",mb:3,children:"Summary"}),a.jsxs($,{direction:{base:"column",lg:"row"},gap:4,alignItems:"stretch",justifyContent:"stretch",children:[a.jsx(vE,{title:"Total activity",titleValue:a.jsx(I,{variant:"h5",display:"flex",flexDirection:"row",alignItems:"center",color:"inherit",children:n.dataByActivityType?.totalActivity}),tableType:"actions",options:{...r,colors:[t.main.bolder,t.main.light],chart:yE("Total-Activity",r.chart)},series:[{data:o.chartSeriesActions,name:"Actions"},{data:o.chartSeriesVisits,name:"Page Visits"}]}),a.jsx(vE,{title:"Unique visitors",titleValue:a.jsx(I,{variant:"h5",display:"flex",flexDirection:"row",alignItems:"center",color:"inherit",children:n.dataByActivityType?.totalUniqueVisitors}),tableType:"visitors",options:{...r,colors:[t.secondary.bold],chart:yE("Unique-Visitors",r.chart)},series:[{name:"Unique Visitors",data:o.chartSeriesVisitors}]})]})]})},xP=({barWidths:e=["86%","67%","46%","38%","23%","18%","8%","6%"],containerHeight:t="250px"})=>a.jsxs(T,{height:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:30,width:"30%"}),a.jsx($,{justifyContent:"center",direction:"row",sx:{mt:"40px"},children:a.jsx(fe,{variant:"rounded",animation:"wave",height:25,width:"50%"})}),a.jsx($,{sx:{width:"100%",pl:"40px",pb:"10px",mt:"20px"},direction:"column",spacing:1.5,alignItems:"flex-start",height:t,children:e.map((n,r)=>a.jsx(fe,{variant:"rounded",animation:"wave",width:n,sx:{flex:1}},`skeleton-item-${r}`))})]}),sse={"01":"Jan","02":"Feb","03":"Mar","04":"Apr","05":"May","06":"Jun","07":"Jul","08":"Aug","09":"Sep",10:"Oct",11:"Nov",12:"Dec"},ise=e=>{const t=[];return e.forEach((n,r)=>{t.push({name:r.charAt(0).toUpperCase()+r.slice(1)||"N/A",data:n.map(s=>({x:s.timePeriod,y:s.activity}))})}),t},ase=e=>{const t=[];return e.forEach((n,r)=>{if(Ure(r)&&lr[r]){const s=n.map(i=>({x:i.timePeriod,y:i.activity}));t.push({name:lr[r],data:s})}}),t},bP=(e,t)=>Object.keys(Ws(e,n=>n.timePeriod)).map(n=>{if(t==="month"||!t){const r=n.split("-");return`${sse[r[1]]} ${r[0]}`}return n}),ose=(e,t)=>e[t?Object.values(lr).findIndex(n=>n===t):0],lse=(e,t,n)=>{if(!e?.data?.length)return{series:[],categories:[]};const{data:r}=e,s=Ws(r,c=>c.applicationName),i=ase(new Map(Object.entries(s))),o=bP(r,n);return{series:i.map(c=>({name:c.name,color:ose(t,c.name??""),data:o.map(d=>{const u=c.data.find(p=>n==="month"||!n?Z(p.x).format("MMM YYYY")===d:d===p.x);return u?u.y:0})})),categories:o}},cse=(e,t)=>e[t?Object.values(nl).findIndex(n=>n===t.toLowerCase()):0],dse=(e,t,n)=>{if(!e||!e.length)return{series:[],categories:[]};const r=Ws(e,l=>l.userType),s=ise(new Map(Object.entries(r))),i=bP(e,n);return{series:s.map(l=>({name:l.name,color:cse(t,l.name??""),data:i.map(c=>{const d=l.data.find(u=>n==="month"||!n?Z(u.x).format("MMM YYYY")===c:c===u.x);return d?d.y:0})})),categories:i}},use=({activityType:e,activities:t,isLoading:n,timePeriod:r})=>{const s=Re(),{palette:{chartSet:i}}=s,o=mP(s),l=m.useMemo(()=>lse(t,i,r),[t,i,r]);return a.jsx(Ve,{children:a.jsx(Ue,{children:n?a.jsx(xP,{}):a.jsxs(a.Fragment,{children:[a.jsxs(I,{variant:"h6",mb:3,children:[Sl[e]," Over Time"]}),a.jsx(T,{sx:{overflow:"visible"},children:a.jsx(L0,{isDataEmpty:!n&&(!t||t?.data?.length===0),children:a.jsx(fP,{options:{...o,xaxis:{...o.xaxis,categories:l.categories},markers:{size:l.categories.length===1?5:0}},series:l.series,height:350})})})]})})})},pse=Ne.memo(use),hse=({activityType:e,activities:t,isLoading:n,timePeriod:r})=>{const s=Re(),{palette:{chartSet:i}}=s,{userIsInternal:o}=gt(),l=mP(s),c=m.useMemo(()=>{const d=dse(t?.data||[],i,r);return!o&&d.series[0]&&(d.series[0].name="Users"),d},[t,i,r,o]);return a.jsx(Ve,{children:a.jsx(Ue,{children:n?a.jsx(xP,{}):a.jsxs(a.Fragment,{children:[a.jsxs(I,{variant:"h6",mb:3,children:[Sl[e]," Over Time by Users"]}),a.jsx(T,{sx:{overflow:"visible"},children:a.jsx(L0,{isDataEmpty:!t||t?.data?.length===0,children:a.jsx(fP,{options:{...l,xaxis:{...l.xaxis,categories:c.categories},markers:{size:c.categories.length===1?5:0},legend:{...l.legend,show:o}},series:c.series,height:350})})})]})})})},fse=Ne.memo(hse),yP=({selectedActivityType:e,userActivity:t,applicationActivities:n,isLoading:r,timePeriod:s})=>{const{state:i,dispatch:o}=Du();return a.jsx(T,{sx:{marginTop:4},children:a.jsxs($,{spacing:2,children:[a.jsxs($,{direction:"row",spacing:2,justifyContent:"space-between",children:[a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:a.jsx(I,{variant:"h6",children:"Activity Details"})}),a.jsxs($,{direction:"row",spacing:2,children:[a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:"Show: "}),a.jsx(T,{sx:{width:"240px",maxWidth:"300px"},children:a.jsx(Ar,{disabled:r,fullWidth:!0,value:i.selectedActivityFilterValue,options:Sl,onChange:l=>{const{value:c}=l.target;c!=="allActivity"&&c!=="actions"&&c!=="pageVisits"||(o({type:"updateCurrentSelectedFilter",value:jd.activity}),o({type:"updateActivityFilterValue",value:c}))}})})]})]}),a.jsxs($,{spacing:3,children:[a.jsx(pse,{activities:n,activityType:e,isLoading:r,timePeriod:s}),a.jsx(fse,{activities:t,activityType:e,isLoading:r,timePeriod:s})]})]})})};Ne.memo(yP);const zy=rt(Mn)(({theme:e})=>{const{background:t}=e.palette,{spacing:n}=e,r={backgroundColor:"white",":hover":{backgroundColor:"white"}};return{".MuiDataGrid-cell":{border:"none",paddingLeft:n(2),paddingRight:n(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&.MuiDataGrid-cell--editing":{":focus-within":{outline:"none"}},"&.editable-cell-cursor:hover":{cursor:"pointer"}},".MuiDataGrid-cellCheckbox":{paddingLeft:n(1)},".MuiDataGrid-columnHeader":{":focus-within":{outline:"none"}},".MuiDataGrid-columnHeadersInner":{".MuiDataGrid-columnHeader:not(:first-of-type)":{paddingLeft:n(2),paddingRight:n(2)}},".MuiDataGrid-columnHeaders":{backgroundColor:t.tableHeader,border:"none",borderRadius:n(1)},".MuiDataGrid-columnHeaderTitleContainerContent":{fontSize:12,height:18,textTransform:"uppercase"},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-row":{...r},".MuiDataGrid-row:nth-of-type(even)":{...r},".MuiDataGrid-row:last-of-type":{borderBottomLeftRadius:n(1),borderBottomRightRadius:n(1)},".MuiDataGrid-toolbarContainer":{padding:0}}}),CE={top:"-56px",position:"absolute"},mse=({csvFileName:e,isLoading:t=!1,onClickDownload:n})=>a.jsx(km,{sx:{display:"flex",justifyContent:"flex-end"},children:a.jsx(Nt,{isLoading:t,sx:CE,children:a.jsx(vC,{disabled:t,variant:"outlined",color:"secondary",printOptions:{disableToolbarButton:!0},sx:{...CE,position:t?"relative":"absolute"},csvOptions:{fileName:`${e}-${new Date().toISOString()}`},onClick:n})})});zy.defaultProps={...zy.defaultProps,checkboxSelection:!1,columnHeaderHeight:40,disableColumnMenu:!0,disableColumnPinning:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,hideFooter:!0,rowHeight:58,components:{Toolbar:mse},localeText:{toolbarExport:"Download"}};const gse=({csvFileName:e})=>a.jsx(km,{sx:{display:"flex",justifyContent:"flex-end"},children:a.jsx(vC,{variant:"outlined",color:"secondary",printOptions:{disableToolbarButton:!0},sx:{position:"absolute",top:"-140px",right:"40px"},csvOptions:{fileName:`${e}-${new Date().toISOString()}`}})}),xse=()=>a.jsx(xn,{sx:{gap:.5,my:"6px",mx:.5},children:Array(2).fill(null).map((e,t)=>a.jsx(fe,{variant:"rounded",height:38},`${t}-skeleton-item`))}),bse=()=>a.jsx(gP,{sx:{minHeight:"100px"}}),yse=({rows:e,tableType:t,isLoading:n,userIsInternal:r,timePeriod:s})=>a.jsx(xn,{direction:"column",alignItems:"center",gap:"20px",children:a.jsx("div",{style:{width:"100%"},children:a.jsx(zy,{sx:{border:"1px solid",borderColor:"neutral.100",position:"relative"},components:{LoadingOverlay:xse,NoRowsOverlay:bse,Toolbar:gse},columns:t==="actions"?qre(s):Yre(r,s),hideFooter:!0,autoHeight:!0,rows:e,loading:n,componentsProps:{toolbar:{csvFileName:`UserActivityDetails-${t}`}}})})}),vse={"& .MuiSelect-select":{py:"6px"},"& .MuiSelect-icon":{width:"16px",height:"16px"}},vP=({disabled:e=!1,onClose:t,selectedApplicationsValue:n})=>{const[r,s]=m.useState(n.length>0?[...n]:Object.keys(lr));m.useEffect(()=>{s(n.length>0?[...n]:Object.keys(lr))},[n]);const i=l=>{const c=l.target.value;c.includes("all")?s(c.length>Object.keys(lr).length?[]:Object.keys(lr)):s([...c])},o=()=>{r.length===0&&s(Object.keys(lr)),!(JSON.stringify(n)===JSON.stringify(r)||n.length===0&&r.length===Object.keys(lr).length)&&t(r)};return a.jsxs(tt,{disabled:e,multiple:!0,value:r,onChange:i,onClose:o,renderValue:l=>a.jsxs("span",{children:[a.jsx(LD,{size:"16px",style:{verticalAlign:"middle"}}),a.jsx("span",{style:{marginLeft:7,overflow:"hidden",textOverflow:"ellipsis",verticalAlign:"middle"},children:l.length===Object.keys(lr).length?"All Platform Apps":l.map(c=>lr[c]).join(", ")})]}),IconComponent:vs,sx:vse,children:[a.jsxs(Se,{value:"all",children:[a.jsx(et,{checked:r.length===Object.keys(lr).length}),a.jsx(Kt,{primary:"All Applications"})]}),Object.entries(lr).map(([l,c])=>a.jsxs(Se,{value:l,children:[a.jsx(et,{checked:r.includes(l)}),a.jsx(Kt,{primary:c})]},l))]})},Sh=()=>Ui(Z(),"last3Months"),CP=Z("2024-01-01"),Cse=({detailsType:e,disabled:t=!1,selectedUserType:n,selectedActivityType:r,selectedApplications:s,selectedDateRange:i,onFilterChange:o})=>a.jsxs($,{sx:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",columnGap:2},children:[e==="actions"?a.jsx(Ar,{disabled:t,options:dP,menuItemStartIcon:a.jsx(ym,{size:"16px"}),value:n,onChange:l=>o("userFilter",l.target.value)}):a.jsx(Ar,{disabled:t,options:Sl,value:r,onChange:l=>{o("activityFilter",l.target.value)}}),a.jsx(vP,{disabled:t,selectedApplicationsValue:s&&[...s],onClose:l=>{o("applicationsFilter",l)}}),a.jsx(ts,{disabled:t,fullWidth:!0,minDate:CP,value:i,setValue:l=>{o("dateRange",l)}})]}),wse=()=>{const{state:{activityDetailsLoading:e,dialogState:t},dispatch:n}=Du(),{userFilter:r,activityFilter:s,applicationsFilter:i,dateRange:o}=t.filtersState,l=(c,d)=>{n({type:"updateDialogFilter",filterName:c,value:d})};return a.jsx(Cse,{detailsType:t.tableType,disabled:e,selectedUserType:r,selectedActivi
182tyType:s,selectedApplications:i,selectedDateRange:o,onFilterChange:l})},Sse=({handleClose:e,open:t,detailsType:n,isLoading:r,rows:s,onFiltersReset:i,userIsInternal:o,timePeriod:l})=>a.jsxs(yt,{fullWidth:!0,maxWidth:"md",open:t,children:[a.jsx(vt,{variant:"h6",sx:{pt:4},children:a.jsxs(xn,{direction:"row",justifyContent:"space-between",height:24,children:[n==="actions"?"Total activity details":"Unique visitors details",a.jsx(He,{disableRipple:!0,onClick:e,sx:{color:"text.secondary"},children:a.jsx(Jt,{size:24})})]})}),a.jsx(Ct,{sx:{pb:2,overflowY:"visible"},children:a.jsxs(gi,{children:[a.jsx(wse,{}),a.jsx(re,{variant:"text",color:"secondary",onClick:i,size:"small",disabled:r,sx:{alignSelf:"flex-start",mb:1},children:"Reset All Filters"}),a.jsx(yse,{rows:s,tableType:n,isLoading:r,userIsInternal:o,timePeriod:l})]})})]}),jse=()=>{const{engagementNiceId:e}=pe(),{state:{dialogState:t,timePeriod:n},dispatch:r}=Du(),{userFilter:s,activityFilter:i,applicationsFilter:o,dateRange:l}=t.filtersState,{userIsInternal:c}=gt(),d=m.useMemo(()=>{const x={engagement_nice_id:e,start_date:l?.[0]?.format("YYYY-MM-DD")||"",end_date:l?.[1]?.format("YYYY-MM-DD")||"",group_by:t.tableType==="actions"?"activity_name":"user_type",activity:i==="allActivity"?void 0:Sl[i],user_type:s===nl.allUsers?void 0:s};return o.length<Object.keys(lr).length&&(x.applications=[...o]),n&&(x.time_period=n),x.start_date=l?.[0]?.format("YYYY-MM-DD")||"",x},[t,e,s,o,i,l,n]),{data:u,isFetching:p}=B5(d),h=m.useMemo(()=>u?.data.length&&t.isOpen&&!p?t.tableType==="actions"?Kre(pP(u)):Qre(Hre(u)):[],[u,t.isOpen,t.tableType,p]),f=()=>{r({type:"updateDialogFilter",filterName:"userFilter",value:nl.allUsers}),r({type:"updateDialogFilter",filterName:"applicationsFilter",value:[]}),r({type:"updateDialogFilter",filterName:"activityFilter",value:"allActivity"}),r({type:"updateDialogFilter",filterName:"dateRange",value:Sh()})},g=()=>{f(),r({type:"updateDialogState",value:{isOpen:!1,tableType:"actions"}})};return a.jsx(Sse,{handleClose:g,open:t.isOpen,detailsType:t.tableType,isLoading:p,rows:h,onFiltersReset:f,userIsInternal:c,timePeriod:n})},wP=()=>{const{dispatch:e,state:t}=Du(),{userIsInternal:n}=gt(),r=Re(),s=l=>{e({type:"updateCurrentSelectedFilter",value:jd.users}),e({type:"updateUserFilterValue",value:l})},i=l=>{e({type:"updateCurrentSelectedFilter",value:jd.applications}),e({type:"updateApplicationFilterValue",value:l})},o=l=>{e({type:"updateTimePeriod",value:l})};return a.jsxs(T,{sx:{mb:3,display:"flex",flexDirection:"column",rowGap:2,[r.breakpoints.up("md")]:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",columnGap:2}},children:[n&&a.jsx(Ar,{disabled:t.activityLoading,value:t.selectedUserFilterValue,options:dP,menuItemStartIcon:a.jsx(ym,{size:"16px"}),onChange:l=>{const c=`${l.target.value}`;c!=="allUsers"&&c!=="internal"&&c!=="external"||s(c)}}),a.jsx(vP,{disabled:t.activityLoading,onClose:i,selectedApplicationsValue:t.selectedApplicationFilterValue}),a.jsx(xn,{direction:"row",justifyContent:"flex-end",flexGrow:1,children:a.jsx(sn,{label:"Show by:",labelPlacement:"start",sx:{gap:2},control:a.jsx(Ar,{sx:{width:208},onChange:({target:{value:l}})=>{l!=="week"&&l!=="month"||o(l)},options:{month:"Month",week:"Week"},value:t.timePeriod,disabled:!1})})}),a.jsx(ts,{disabled:t.activityLoading,fullWidth:!0,minDate:CP,value:t.dateRange,setValue:l=>{e({type:"updateCurrentSelectedFilter",value:jd.date}),e({type:"updateDateRange",value:l})}})]})};Ne.memo(wP);const kse=({selectedActivityType:e,userActivityData:t,applicationActivityData:n,timePeriod:r,isLoading:s,error:i,onFiltersReset:o})=>a.jsxs(T,{children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",pb:2},children:[a.jsx(I,{variant:"h5",children:"User Activity"}),a.jsx(re,{variant:"text",color:"secondary",onClick:o,size:"small",disabled:s,sx:{alignSelf:"flex-start"},children:"Reset All Filters"})]}),a.jsx(wP,{}),i&&a.jsx(vn,{severity:"error",sx:{mb:2},children:i}),a.jsx(rse,{}),a.jsx(yP,{userActivity:t,applicationActivities:n,isLoading:s,selectedActivityType:e,timePeriod:r}),a.jsx(jse,{})]}),Ese=()=>{const[e,t]=m.useReducer(Wre,{activityLoading:!0,activityDetailsLoading:!0,dialogState:{isOpen:!1,tableType:"actions",filtersState:{userFilter:"allUsers",activityFilter:"allActivity",applicationsFilter:[],dateRange:Sh()}},dataByActivityType:null,dataByApplication:null,dataByUserType:null,selectedActivityFilterValue:"allActivity",selectedApplicationFilterValue:[],selectedUserFilterValue:nl.allUsers,dateRange:Sh(),currentSelectedFilter:null,timePeriod:"month",error:null}),n=()=>{t({type:"updateUserFilterValue",value:nl.allUsers}),t({type:"updateApplicationFilterValue",value:[]}),t({type:"updateActivityFilterValue",value:"allActivity"}),t({type:"updateActivityFilterValue",value:"allActivity"}),t({type:"updateDateRange",value:Sh()}),t({type:"updateCurrentSelectedFilter",value:null}),t({type:"updateTimePeriod",value:"month"})};return a.jsx(Vre,{state:e,dispatch:t,children:a.jsx(kse,{onFiltersReset:n,selectedActivityType:e.selectedActivityFilterValue,userActivityData:e.dataByUserType,isLoading:e.activityLoading,error:e.error,applicationActivityData:e.dataByApplication,timePeriod:e.timePeriod})})},_se={create:"Create Audience",delete:"Delete Audience",edit:"Start Edit Audience",new:"Start New Audience",saveEdits:"Save Audience Edits"},SP=()=>pr({actionMap:_se,eventName:"audience"}),Tse=e=>{const{title:t,titleNiceId:n,brandNiceId:r}=e||{};return!t||!n||!r?null:{body:{title:t,title_nice_id:n,brand_nice_id:r}}},Ise=()=>{const{engagementId:e,engagementNiceId:t}=pe(),[n]=U5(),[r]=kA(),s=SP();return{deleteAudience:async o=>{const l=Tse(o);if(!l)return;const c=await n({engagementNiceId:t,engagementId:e,body:l.body});"data"in c&&c.data.status==="success"&&(s("delete",{name:o.title}),await r(null))}}},By=rt(Mn)(({theme:e})=>{const{background:t}=e.palette,{spacing:n}=e,r={backgroundColor:t.paper,":hover":{backgroundColor:e.palette.mode==="dark"?t.brand.subtle.hovered:t.paper}};return{border:"none",".MuiDataGrid-cell":{border:"none",paddingLeft:n(2),paddingRight:n(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&.MuiDataGrid-cell--editing":{":focus-within":{outline:"none"}},"&.editable-cell-cursor:hover":{cursor:"pointer"}},".MuiDataGrid-cellCheckbox":{paddingLeft:n(1)},".MuiDataGrid-columnHeader":{":focus-within":{outline:"none"}},".MuiDataGrid-columnHeadersInner":{".MuiDataGrid-columnHeader:not(:first-of-type)":{paddingLeft:n(2),paddingRight:n(2)}},".MuiDataGrid-columnHeaders":{backgroundColor:t.tableHeader,border:"none",borderRadius:n(1)},".MuiDataGrid-columnHeaderTitleContainerContent":{fontSize:12,height:18,textTransform:"uppercase"},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-row":{...r},".MuiDataGrid-row:nth-of-type(even)":{...r},".MuiDataGrid-row:last-of-type":{borderBottomLeftRadius:n(1),borderBottomRightRadius:n(1)}}});By.defaultProps={...By.defaultProps,checkboxSelection:!1,columnHeaderHeight:40,disableColumnMenu:!0,disableColumnPinning:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,hideFooter:!0,rowHeight:58};const jP=8,qi={overall:{value:"overall",label:"Total"}
182,converting:{value:"converting",label:"Converting"}},kx={population:[],total:0},Dse=(e,t)=>{const n=[];return e.forEach(r=>{const{DEMO_DIMENSION_NAME:s,DEMO_DIMENSION_NICE_ID:i,DEMO_VALUE_NAME:o,DEMO_VALUE_NICE_ID:l}=r;if(s){const c=n.find(d=>d.DEMO_DIMENSION_NAME===s);c?c.DEMOS.push({DEMO_VALUE_NICE_ID:l,DEMO_VALUE_NAME:o,SELECTED:t}):n.push({DEMO_DIMENSION_NICE_ID:i,DEMO_DIMENSION_NAME:s,DEMOS:[{DEMO_VALUE_NICE_ID:l,DEMO_VALUE_NAME:o,SELECTED:t}]})}}),n},Wf=e=>e>0&&e<.001?"< 0.1%":e.toLocaleString("en-US",{style:"percent",minimumFractionDigits:Number.isInteger(e)?0:1}),Ase=(e,t)=>{let n=e.length===0?1:0;return e.forEach(r=>{const s=t.find(i=>i.DEMO_VALUE_NAME===r.DEMO_VALUE_NAME);n+=s?.RATIO||0}),parseFloat((n*100).toFixed(1))},Mse=(e,t)=>t===0?0:e===t?100:e===0?0:e===100?t:parseFloat((t/e*100).toFixed(1)),kP=m.createContext(null),js=()=>m.useContext(kP),Rse={editingProperty:null,isCheckingTitle:!1,kpiName:null,populationSource:qi.overall.value,propertiesData:[],savingAudience:!1,title:"",titleHasError:!1,titleNiceId:""},Nse=(e,t)=>t.type==="reset"?{...e,isCheckingTitle:!1,kpiName:null,savingAudience:!1,title:"",titleHasError:!1,titleNiceId:""}:t.type in e?{...e,[t.type]:t.value}:e,Ose=[];function Ol(){const{engagementId:e}=pe(),{data:t=Ose,isLoading:n,error:r}=hu(e,{skip:!e}),s=m.useMemo(()=>t?new Set(t.map(l=>l.objective_nice_id)):new Set,[t]),i=m.useMemo(()=>t?new Set(t.map(l=>l.objective_name)):new Set,[t]),o=m.useMemo(()=>{if(r)return typeof r=="string"?r:"Failed to load KPI data"},[r]);return{activeKpiNiceIds:s,activeKpiNames:i,activeKpis:t,kpisLoading:n,error:o}}const Pse=(e,t)=>{const n={source:e,where:{}};return e===qi?.converting?.value&&(n.where={kpi_name:[t]}),n},wE=(e,t,n)=>{const r={source:e,where:{}};return t.forEach(s=>{const i=s.DEMOS.filter(o=>o.SELECTED);i.length&&i.length!==s.DEMOS.length&&(r.where[s.DEMO_DIMENSION_NICE_ID]||(r.where[s.DEMO_DIMENSION_NICE_ID]=[]),r?.where?.[s.DEMO_DIMENSION_NICE_ID]?.push(...i.map(o=>o.DEMO_VALUE_NAME)))}),e===qi?.converting?.value&&(r.where.kpi_name=[n]),r},Lse=(e,t)=>{const n=Object.keys(e)||[],r=t.map(s=>({...s,DEMOS:s.DEMOS.map(i=>({...i,SELECTED:!n.includes(s.DEMO_DIMENSION_NICE_ID.replace("demo_",""))}))}));return n.forEach(s=>{const i=s==="geo"?s:`demo_${s}`,o=r.findIndex(c=>c.DEMO_DIMENSION_NICE_ID===i);if(o===-1)return;const l=[...r[o].DEMOS];e[s]&&e[s].forEach(c=>{const d=l.findIndex(u=>u.DEMO_VALUE_NICE_ID===c);d!==-1&&(l[d].SELECTED=!0)}),r[o].DEMOS=l}),r},Fse=e=>{const t={};return e.forEach(n=>{const r=n.DEMO_DIMENSION_NICE_ID.replace("demo_",""),s=n.DEMOS.filter(o=>o.SELECTED),i=s.length===n.DEMOS.length;s.length&&!i&&(t[r]=s.map(o=>o.DEMO_VALUE_NICE_ID))}),t},$se=({editingProperty:e,kpiName:t,populationSource:n,propertiesData:r})=>{const{engagementNiceId:s}=pe(),i=m.useMemo(()=>({body:wE(n,r,t),engagementNiceId:s}),[s,t,n,r]),{data:o=kx,isFetching:l}=Ig(i),c=m.useMemo(()=>{const w=r.map(S=>S.DEMO_DIMENSION_NICE_ID===e?.DEMO_DIMENSION_NICE_ID?e:S);return{body:wE(n,w,t),engagementNiceId:s}},[e,s,t,n,r]),{data:d=kx,isFetching:u}=Ig(c),p=m.useMemo(()=>({body:Pse(n,t),engagementNiceId:s}),[s,t,n]),{data:h=kx,isFetching:f}=Ig(p),{data:{kpis:g=[],legend:x=[]}={},isLoading:b}=V5(s),{activeKpiNames:y,kpisLoading:v}=Ol(),C=m.useMemo(()=>!g.length||!y.size?[]:g.filter(w=>y.has(w.KPI_NAME)),[g,y]);return{audience:o,audienceLoading:l,kpis:C,legend:x,legendLoading:b||v,pendingAudience:d,pendingAudienceLoading:u,universe:h,universeLoading:f}},zse=({children:e})=>{const[t,n]=m.useReducer(Nse,Rse),{editingProperty:r,kpiName:s,populationSource:i,propertiesData:o}=t,{audience:l,audienceLoading:c,kpis:d,legend:u,legendLoading:p,pendingAudience:h,pendingAudienceLoading:f,universe:g,universeLoading:x}=$se({editingProperty:r,kpiName:s,populationSource:i,propertiesData:o});m.useEffect(()=>{if(u.length){const y=Dse(u,!0);n({type:"propertiesData",value:y})}},[u]);const b=m.useMemo(()=>({audience:l,audienceLoading:c,dispatch:n,kpis:d,legend:u,legendLoading:p,pendingAudience:h,pendingAudienceLoading:f,state:t,universe:g,universeLoading:x}),[l,c,d,u,p,h,f,t,g,x]);return a.jsx(kP.Provider,{value:b,children:e})},Bse={chart:{type:"donut"},legend:{show:!1},dataLabels:{enabled:!1},plotOptions:{pie:{donut:{labels:{show:!1}}}},yaxis:{labels:{formatter:e=>
182(e/100).toLocaleString("en-US",{style:"percent",minimumFractionDigits:1})}},labels:["Audience","Other"],states:{hover:{filter:{type:"none"}}},tooltip:{enabled:!1}},Use=({audiencePercentage:e})=>{const{palette:t}=Re(),{audience:n,universe:r,state:s}=js(),{propertiesData:i,populationSource:o}=s,[l,c]=m.useState(()=>new Set([0])),d=u=>c(p=>{const h=new Set(p);return h.has(u)?h.delete(u):h.add(u),h});return a.jsxs($,{direction:"column",gap:2,minWidth:"414px",children:[a.jsx($,{justifyContent:"center",direction:"row",children:a.jsx(ua,{options:{...Bse,colors:[t.chartBrand.main.bold,t.surface.tertiary]},series:[e,100-e],width:"300px",type:"donut"})}),a.jsx(Br,{variant:"secondary",sx:{py:4},children:a.jsxs($,{direction:"column",alignItems:"center",children:[a.jsxs(I,{gutterBottom:!0,variant:"h4",component:"div",children:[e," %"]}),a.jsxs(I,{color:"text.secondary",children:["of ",o==="overall"?"Total":"Converting","Â Population"]})]})}),i.length>0&&a.jsxs(Br,{variant:"secondary",sx:{padding:"16px",paddingRight:"20px","th, td":{textTransform:"none !important",fontSize:"12px",color:"text.secondary",padding:"4px 12px 4px 0px",border:"none"},"td:last-child , th:last-child":{paddingRight:0}},children:[a.jsx(I,{fontWeight:"500",mb:"8px",children:"Audience Details"}),a.jsx(Ki,{children:a.jsx(Ya,{children:a.jsxs(bn,{children:[a.jsx($e,{width:"100%",children:a.jsx(I,{fontWeight:"500",color:"text.secondary",children:"Dimension"})}),a.jsx($e,{align:"right",children:a.jsx(I,{fontWeight:"500",color:"text.primary",children:"Audience"})}),a.jsx($e,{align:"right",children:a.jsx(I,{color:"text.secondary",fontWeight:"500",children:"Population"})})]})})}),a.jsx($,{gap:1,mt:.5,children:i.map((u,p)=>{const h=r.population.filter(f=>f.DEMO_DIMENSION_NICE_ID===u.DEMO_DIMENSION_NICE_ID);return a.jsxs(T,{children:[a.jsx(Ki,{children:a.jsx(Ya,{children:a.jsxs(bn,{children:[a.jsx($e,{sx:{paddingLeft:"0 !important"},children:a.jsxs($,{direction:"row",alignItems:"center",gap:.5,children:[a.jsx(Ie,{"aria-label":"exp
182and row",size:"small",onClick:()=>d(p),children:l.has(p)?a.jsx(Qv,{color:t.text.secondary,size:20}):a.jsx(vs,{color:t.text.secondary,size:20})}),a.jsxs($,{direction:"row",alignItems:"center",gap:1,sx:{cursor:"pointer"},onClick:()=>d(p),children:[a.jsx(T,{bgcolor:t.chartSet[p],width:"10px",height:"10px",borderRadius:"2px",children:"Â "}),a.jsx(I,{fontWeight:"500",color:"text.secondary",children:u.DEMO_DIMENSION_NAME})]})]})}),a.jsx($e,{align:"right",width:"76px"}),a.jsx($e,{align:"right",width:"76px"})]})})}),a.jsx(Yt,{in:l.has(p),timeout:"auto",unmountOnExit:!0,children:a.jsx(Ki,{children:a.jsx(xl,{children:u.DEMOS.filter(({SELECTED:f})=>f).map(f=>{const g=n.population.find(b=>f.DEMO_VALUE_NAME===b.DEMO_VALUE_NAME&&u.DEMO_DIMENSION_NICE_ID===b.DEMO_DIMENSION_NICE_ID)?.RATIO||0,x=h.find(b=>f.DEMO_VALUE_NAME===b.DEMO_VALUE_NAME&&u.DEMO_DIMENSION_NICE_ID===b.DEMO_DIMENSION_NICE_ID)?.RATIO||0;return a.jsxs(bn,{children:[a.jsx($e,{sx:{paddingLeft:"40px !important"},children:f.DEMO_VALUE_NAME}),a.jsx($e,{align:"right",width:"76px",children:a.jsx(I,{color:"text.primary",fontSize:"12px",children:Wf(g)})}),a.jsx($e,{align:"right",width:"76px",children:a.jsx(I,{color:"text.secondary",fontSize:"12px",children:Wf(x)})})]},f.DEMO_VALUE_NAME)})})})})]},u.DEMO_DIMENSION_NAME)})})]})]})},Vse=()=>{const e=ct(),{state:t,dispatch:n}=js(),[r,s]=m.useState(""),[i]=W5(),{engagementNiceId:o}=pe(),l=d=>{n({type:"title",value:d.target.value.replace(/[&$%]/g,"")});const u=ND(d.target.value,{lower:!0,replacement:"",strict:!0});n({type:"titleNiceId",value:u}),t.titleHasError&&(n({type:"titleHasError",value:!1}),s(""))},c=async()=>{if(t.title){n({type:"isCheckingTitle",value:!0});const d={engagement_nice_id:o,title:t.title,title_nice_id:t.titleNiceId};try{const u=await i({body:d});if(e())if("data"in u){const{status:p,message:h}=u.data;p===500&&d.title===t.title&&(n({type:"titleHasError",value:!0}),s(h))}else We(u.error),n({type:"titleHasError",value:!0}),s("Network error, can't verify name.")}catch(u){We(u),e()&&n({type:"titleHasError",value:!0}),s("Network error, can't verify name.")}finally{e()&&n({type:"isCheckingTitle",value:!1})}}};return a.jsx(Tl,{error:!!r,helperText:r,label:"Audience name",name:"title",value:t.title,onChange:l,onBlur:c})},Wse=()=>a.jsxs(a.Fragment,{children:[a.jsx(fe,{variant:"rounded",width:"100%",height:60,animation:"wave"}),a.jsx(fe,{variant:"rounded",width:"100%",height:60,animation:"wave"}),a.jsx(fe,{variant:"rounded",width:"100%",height:60,animation:"wave"})]}),Hse=({propertyName:e,percentage:t})=>{const{palette:n}=Re();return a.jsxs($,{flexDirection:"row",alignItems:"center",gap:.5,children:[a.jsxs(I,{component:"p",color:n.text.gray,children:[e,":"," "]}),a.jsxs(I,{component:"span",color:n.primary.contrastText,children:[t,"%"]})]})},qse=rt(({className:e,...t})=>a.jsx(be,{...t,classes:{popper:e}}))({[`& .${zv.tooltip}`]:{maxWidth:500}}),Gse=({color:e})=>{const{pendingAudience:t,pendingAudienceLoading:n,state:r,universe:s}=js(),{editingProperty:i}=r,o=m.useMemo(()=>i?.DEMOS.filter(({SELECTED:u})=>u)??[],[i?.DEMOS]),l=m.useMemo(()=>t.population.filter(({DEMO_DIMENSION_NICE_ID:u,RATIO:p})=>u===i?.DEMO_DIMENSION_NICE_ID&&p*100>.1),[i?.DEMO_DIMENSION_NICE_ID,t]),c=m.useMemo(()=>{if(s.total===0)return 0;const u=parseFloat((t.total/s.total*100).toFixed(1));return u>100?100:u},[t,s]),d=l.length>10;return i?a.jsxs(T,{sx:{borderRadius:2.5,p:4,backgroundColor:"surface.tertiary",minHeight:d?134:168,mb:3.5},children:[a.jsxs($,{direction:"row",spacing:1.2,justifyContent:"space-between",alignItems:"center",width:"100%",mb:2,children:[a.jsx(I,{gutterBottom:!0,variant:"body2",children:"Audience Details"}),n?a.jsx(fe,{variant:"rounded",width:"300px",height:"21px",animation:"wave"}):a.jsx(I,{gutterBottom:!0,variant:"body2",children:o.length?`Your audience captured ${c}% of selected properties`:"Please select at least one property below"})]}),n?a.jsx(fe,{variant:"rounded",width:"100%",height:"65px",animation:"wave"}):a.jsx($,{direction:"row",gap:d?"1px":"8px",children:o.map(u=>{const p=l.find(f=>f.DEMO_VALUE_NAME===u.DEMO_VALUE_NAME);if(!p)return null;const h=parseFloat((p.RATIO*100).toFixed(1));return a.jsx(qse,{title:a.jsx(Hse,{propertyName:u.DEMO_VALUE_NAME,percentage:h}),placement:"top",children:a.jsxs($,{direction:"column",sx:{width:`${h}%`},children:[a.jsx(T,{sx:{height:"32px",backgroundColor:e,borderRadius:.5}}),!d&&a.jsxs(I,{gutterBottom:!0,variant:"body2",mt:.75,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:[h,"% ",i.DEMO_DI
182MENSION_NAME," ",u.DEMO_VALUE_NAME]})]})},`row${u.DEMO_VALUE_NICE_ID}`)})})]}):null},Yse=()=>{const{dispatch:e,state:t,universe:n}=js(),{editingProperty:r}=t,s=m.useMemo(()=>r?.DEMOS.filter(({SELECTED:h})=>h)??[],[r?.DEMOS]),i=s.length===r?.DEMOS.length,o=s.length===0,l=m.useMemo(()=>n.population.filter(({DEMO_DIMENSION_NICE_ID:h,RATIO:f})=>h===r?.DEMO_DIMENSION_NICE_ID&&f*100>.1),[r?.DEMO_DIMENSION_NICE_ID,n]),c=h=>{if(!r)return;const f={...r,DEMOS:h};e({type:"editingProperty",value:f})},d=h=>()=>{const f=r?.DEMOS.map(g=>g.DEMO_VALUE_NICE_ID===h?{...g,SELECTED:!g.SELECTED}:g)??[];c(f)},u=()=>{const h=r?.DEMOS.map(f=>({...f,SELECTED:!0}))??[];c(h)},p=()=>{const h=r?.DEMOS.map(f=>({...f,SELECTED:!1}))??[];c(h)};return r?a.jsxs(a.Fragment,{children:[a.jsxs($,{direction:"row",justifyContent:"space-between",alignItems:"center",mt:3.5,children:[a.jsx(I,{gutterBottom:!0,variant:"body2",color:"text.default",children:"Select properties"}),a.jsxs(sB,{children:[a.jsx(re,{variant:"text",onClick:p,disabled:o,children:"Deselect all"}),a.jsx(re,{variant:"text",onClick:u,disabled:i,children:"Select all"})]})]}),a.jsx($,{direction:"row",flexWrap:"wrap",gap:2.5,justifyContent:"space-between",width:"100%",mt:2.5,children:r.DEMOS.map(h=>{const f=l.find(x=>x.DEMO_VALUE_NAME===h.DEMO_VALUE_NAME),g=f?parseFloat((f.RATIO*1e3).toFixed(1)):0;return a.jsx(T,{sx:{width:"calc(50% - 20px)"},children:a.jsxs($,{direction:"row",justifyContent:"space-between",alignItems:"center",p:2,border:"1px solid",borderColor:h.SELECTED?"border.brand":"border.default",borderRadius:2,children:[a.jsxs(He,{onClick:d(h.DEMO_VALUE_NICE_ID),sx:{display:"flex",alignItems:"center",flexGrow:1,justifyContent:"flex-start"},children:[a.jsx(et,{checked:h.SELECTED}),a.jsx(I,{gutterBottom:!0,variant:"body2",mt:.75,children:h.DEMO_VALUE_NAME})]}),a.jsx(ut,{label:`${Wf(g/1e3)} in population`,color:h.SELECTED?"primary":"default",sx:{borderRadius:1.5,height:24,px:.75,py:.375,".MuiChip-label":{pl:.5,pr:.25}}})]})},h.DEMO_VALUE_NICE_ID)})})]}):null},Kse=({color:e,open:t})=>{const{dispatch:n,state:r}=js(),{editingProperty:s,propertiesData:i}=r,o=s?.DEMO_DIMENSION_NICE_ID||null,l=()=>{n({type:"editingProperty",value:null})},c=()=>{if(!s||!o)return;const u=i.map(p=>
182p.DEMO_DIMENSION_NICE_ID===o?s:p);n({type:"propertiesData",value:u}),l()},d=!!s&&s?.DEMOS.filter(({SELECTED:u})=>u).length===0;return a.jsxs(yt,{fullWidth:!0,maxWidth:"lg",open:t,transitionDuration:{enter:225,exit:0},children:[a.jsx(vt,{variant:"h6",sx:{pt:4},children:a.jsx($,{direction:"row",justifyContent:"space-between",height:24,children:a.jsxs(I,{variant:"body2",color:"text.primary",children:["Edit ",s?.DEMO_DIMENSION_NAME," values"]})})}),a.jsxs(Ct,{children:[a.jsx(Gse,{color:e}),a.jsx(St,{}),a.jsx(Yse,{})]}),a.jsx(un,{sx:{p:2},children:a.jsxs(T,{sx:{display:"flex",gap:2,height:36,pr:2},children:[a.jsx(re,{color:"secondary",variant:"outlined",onClick:l,children:"Cancel"}),a.jsx(re,{disabled:d,variant:"contained",onClick:c,children:"Save Changes"})]})})]})},Qse=({audiencePercentage:e,color:t,item:n})=>{const{audienceLoading:r,dispatch:s,state:i,universe:o,universeLoading:l}=js(),{editingProperty:c}=i,{DEMO_DIMENSION_NAME:d,DEMOS:u}=n,p=m.useMemo(()=>u.filter(w=>w.SELECTED),[u]),h=m.useMemo(()=>p.length===u.length,[u,p]),f=m.useMemo(()=>o.population.filter(w=>w.DEMO_DIMENSION_NICE_ID===n.DEMO_DIMENSION_NICE_ID),[o.population,n.DEMO_DI
182MENSION_NICE_ID]),g=m.useMemo(()=>Ase(p,f),[p,f]),x=m.useMemo(()=>Mse(g,e),[g,e]),b=m.useMemo(()=>c?.DEMO_DIMENSION_NAME===d,[c?.DEMO_DIMENSION_NAME,d]),y=r||l,v=m.useMemo(()=>{let w="",S=0;if(p.length===1)w=p?.[0]?.DEMO_VALUE_NAME||"";else if(p.length===u.length||p.length===0)w="All";else{const k=p.map(j=>j.DEMO_VALUE_NAME);k.forEach((j,_)=>{w.length>0&&w[w.length-2]!==","&&(w+=", "),w.length+j.length<=32?w+=j:S=k.length-_})}return S>0&&(w.length>0&&w[w.length-1]!==","&&(w+=", "),w+=`and ${S} others`),w},[u.length,p]),C=m.useMemo(()=>{const w=u.filter(_=>_.SELECTED),S=[],E=[];w.forEach(_=>{E.push(a.jsx(I,{component:"div",variant:"body2",sx:{pl:2},children:_.DEMO_VALUE_NAME},_.DEMO_VALUE_NAME))});const k=a.jsx(T,{sx:{width:"10px",height:"10px",backgroundColor:t,mt:"6px"}}),j=a.jsxs(xn,{flexDirection:"row",children:[k,a.jsx(T,{children:E})]});return S.push(j),S},[t,u]);return a.jsxs(a.Fragment,{children:[a.jsx(T,{onClick:()=>{s({type:"editingProperty",value:n})},sx:{display:"flex",p:1.9,borderRadius:"6px",border:"1px solid rgba(104, 97, 135, 0.20)",cursor:"pointer"},children:a.jsxs(xn,{direction:"row",spacing:1.2,justifyContent:"space-between",alignItems:"center",width:"100%",children:[a.jsxs(xn,{direction:"row",spacing:1.2,alignItems:"center",children:[a.jsx(T,{sx:{backgroundColor:t,borderRadius:.5,height:16,width:16}}),a.jsx(I,{gutterBottom:!0,variant:"body2",children:d}),a.jsx(be,{title:h||p.length===1?"":C,placement:"bottom",children:a.jsx(ut,{label:v,color:"primary",sx:{borderRadius:1.5,height:24,px:.5,py:.375}})})]}),y?a.jsx(fe,{width:250,height:22,variant:"rounded"}):a.jsxs(xn,{direction:"row",spacing:1.2,width:250,justifyContent:"flex-end",children:[a.jsxs(I,{variant:"body2",sx:{color:"text.secondary"},children:[a.jsxs("span",{children:[x,"%"]})," captured"]}),a.jsxs(I,{variant:"body2",sx:{color:"text.secondary"},children:[a.jsx("span",{children:Wf(g/100)})," in population"]})]})]})}),a.jsx(Kse,{color:t,open:b})]})},Jse=()=>{const{dispatch:e,kpis:t,legendLoading:n,state:r}=js(),{kpiName:s}=r,i=o=>{e({type:"kpiName",value:o.target.value})};return a.jsx(tt,{disabled:n,fullWidth:!0,inputProps:{sx:{px:1.5,py:.75,display:"flex"}},onChange:i,sx:{"&.Mui-focused":{".MuiOutlinedInput-notchedOutline":{boxShadow:"none"}}},value:s||"",variant:"outlined",children:t.map(o=>a.jsx(Se,{value:o.KPI_NAME,children:o.KPI_NAME},o.KPI_NAME))})},Xse=()=>{const{dispatch:e,kpis:t,state:n}=js(),{populationSource:r}=n,s=(i,o)=>{const l=o==="converting"&&t?.[0]?.KPI_NAME||null;e({type:"populationSource",value:o}),e({type:"kpiName",value:l})};return a.jsxs(ml,{color:"primary",value:r,exclusive:!0,onChange:s,"aria-label":"Audience",children:[a.jsx(yi,{value:qi.overall.value,sx:{width:"105px"},children:qi.overall.label}),a.jsx(yi,{value:qi.converting.value,sx:{width:"105px"},children:qi.converting.label})]})},Zse=()=>{const{audience:e,legendLoading:t,state:n,universe:r}=js(),{populationSource:s,propertiesData:i}=n,{chartSet:o}=Re().palette,l=m.useMemo(()=>{if(e.total===0)return 0;if(r.total===0)return 100;const c=parseFloat((e.total/r.total*100).toFixed(1));return Math.min(c,100)},[e.total,r.total]);return a.jsx(Ct,{children:a.jsxs($,{spacing:2,direction:{xs:"column",md:"row"},children:[a.jsxs($,{sx:{gap:3,py:2,px:1},flex:"1",children:[a.jsx(Xt,{title:"Audience Details"}),a.jsx(Vse,{}),a.jsxs($,{direction:"row",spacing:2,children:[a.jsx(Xse,{}),s===qi.converting.value&&a.jsx(Jse,{})]}),a.jsx(I,{variant:"h6",children:"Audience Properties"}),t||!i.length?a.jsx(Wse,{}):i.map((c,d)=>a.jsx(Qse,{audiencePercentage:l,color:o[d]||"",item:c},c.DEMO_DIMENSION_NICE_ID))]}),a.jsx($,{flex:"1",justifyContent:"center",direction:"row",children:a.jsx(Use,{audiencePercentage:l})})]})})},eie=({audienceToEdit:e,onClose:t,onCreateAudience:n,toggleAudienceCheckingState:r,toggleErrorDialog:s})=>{const i=ct(),{state:o,dispatch:l}=js(),{engagementId:c,engagementName:d,engagementNiceId:u}=pe(),[p]=H5(),[h]=q5(),f=()=>{if(!o.title||!o.titleNiceId)return null;const C={title:o.title,title_nice_id:o.titleNiceId,brand_id:c,brand_name:d,brand_nice_id:u,audience_definition:{},audience_description:{}};return o.propertiesData.forEach(w=>
182{const S=w.DEMO_DIMENSION_NICE_ID.replace("demo_",""),E=w.DEMOS.filter(j=>j.SELECTED),k=E.length===w.DEMOS.length;E.length&&!k&&(C.audience_definition[S]=E.map(j=>j.DEMO_VALUE_NICE_ID),C.audience_description[w.DEMO_DIMENSION_NAME]=E.map(j=>j.DEMO_VALUE_NAME))}),C},g=m.useMemo(()=>e&&!Kn(e.audience.definition,Fse(o.propertiesData)),[o.propertiesData,e]),x=m.useMemo(()=>e&&e.titleNiceId!==o.titleNiceId,[o.titleNiceId,e]),b=async()=>{r(!0),l({type:"savingAudience",value:!0});const C=f();if(C){if(e&&!g&&!x){l({type:"savingAudience",value:!1}),t();return}try{if("error"in(e?await h({body:{...C,previous_title_nice_id:e.titleNiceId},engagementNiceId:u,engagementId:c}):await p({body:C,engagementNiceId:u,engagementId:c}))){i()&&s(!0);return}n(e?"edit":"new",{name:o.title,populationType:o.populationSource==="converting"?"converting":"total"}),t()}catch{}finally{i()&&l({type:"savingAudience",value:!1})}}},y=m.useMemo(()=>o.propertiesData.every(C=>C.DEMOS.every(w=>w.SELECTED)),[o.propertiesData]),v=m.useMemo(()=>o.titleHasError||o.isCheckingTitle||!o.title||y,[o.titleHasError,o.isCheckingTitle,o.title,y]);return a.jsx(un,{sx:{justifyContent:"space-between",py:2},children:a.jsxs($,{direction:"row",gap:1,height:36,alignItems:"center",justifyContent:"space-between",width:"100%",children:[a.jsx(re,{color:"secondary",variant:"outlined",onClick:t,children:"Close"}),a.jsx(Dt,{color:"primary",loading:o.isCheckingTitle,disabled:v,variant:"contained",onClick:b,children:e?"Save Changes":"Create Audience"})]})})},tie=({isEditing:e})=>a.jsxs(xn,{alignItems:"center",p:6.5,children:[a.jsx(Xt,{title:e?"Running Audience Update":"Running Audience Creation"}),a.jsxs(T,{sx:{alignItems:"center",backgroundColor:"background.brand.subtle.default",borderRadius:1,color:"text.default",display:"flex",gap:1.5,py:.75,px:2,mt:2},children:[a.jsx(I,{sx:{display:"flex",alignItems:"center",color:"text.default",height:40},children:a.jsx(Si,{height:16,width:16})}),a.jsxs(I,{color:"primary",variant:"body2",sx:{display:"flex",alignItems:"center",height:40,color:"text.default"},children:["Please do not refresh or close the browser. ",e?"Updating":"Checking"," your created audience can take around 1 min..."]})]}),a.jsxs(xn,{mt:10,alignItems:"center",children:[a.jsx(AM,{icon:a.jsx(YD,{})}),a.jsx(I,{variant:"h6",sx:{mt:4},children:"Checking audience selection"})]})]}),nie=({reset:e,handleClose:t,open:n,isEditing:r})=>a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",open:n,children:[a.jsx(vt,{variant:"h6",sx:{pt:4},children:a.jsxs($,{direction:"row",justifyContent:"space-between",height:24,children:["Selected audience already exist",a.jsx(He,{disableRipple:!0,onClick:t,sx:{color:"text.secondary"},children:a.jsx(Jt,{size:24})})]})}),a.jsx(Ct,{sx:{pb:2},children:a.jsxs(I,{variant:"body2",sx:{display:"flex",alignItems:"center",height:40},children:["The chosen selections for this custom audience already exist. Please update your selections or cancel ",r?"editing":"creation","."]})}),a.jsx(un,{sx:{py:2,px:3},children:a.jsxs($,{direction:"row",gap:1,height:36,children:[a.jsxs(re,{variant:"outlined",color:"secondary",onClick:e,children:["Cancel ",r?"editing":"creation"]}),a.jsx(re,{variant:"outlined",onClick:t,children:"Continue editing"})]})})]}),rie=({audienceToEdit:e,isAudienceCreationDialogOpen:t,onCreateAudience:n,toggleAudienceCreationDialog:r})=>{const{state:s,dispatch:i}=js(),[o,l]=m.useState(!1),[c,d]=m.useState(!1);m.useEffect(()=>{if(e){const h=Lse(e.audience.definition,s.propertiesData);i({type:"title",value:e.title}),i({type:"titleNiceId",value:e.titleNiceId}),i({type:"titleHasError",value:!1}),i({type:"propertiesData",value:h})}},[e,i]);const u=()=>{const{propertiesData:h}=s,f=h.map(g=>({...g,DEMOS:g.DEMOS.map(x=>({...x,SELECTED:!0}))}));i({type:"propertiesData",value:f})},p=()=>{u(),i({type:"reset"}),l(!1),d(!1),r("close")};return a.jsxs(yt,{fullScreen:!0,open:t,onClose:p,children:[a.jsxs(vt,{variant:"h6",children:[e?`Edit ${e.title} Audience`:"Create Custom Audience",a.jsx(Ie,{onClick:()=>p(),sx:{position:"absolute",right:0,top:0},children:a.jsx(Jt,{})})]}),o?a.jsx(tie,{isEditing:!!e}):a.jsxs(a.Fragment,{children:[a.jsx(Zse,{}),a.jsx(eie,{audienceToEdit:e,onClose:p,onCreateAudience:n,toggleAudienceCheckingState:l,toggleErrorDialog:d})]}),a.jsx(nie,{reset:p,open:c,handleClose:()=>d(!1),isEditing:!!e})]})},sie=({audienceToEdit:e,isAudienceCreationDialogOpen:t,onCreateAudience:n,toggleAudienceCreationDialog:r})=>a.jsx(zse,{children:a.jsx(rie,{audienceToEdit:e,isAudienceCreationDialogOpen:t,onCreateAudience:n,toggleAudienceCreationDialog:r})}),EP=m.createContext(null),iie=()=>m.useContext(EP),aie=({audience:e})=>{const{deleteAudience:t}=Ise(),[n,r]=m.useState(!1),{updateAudienceToEdit:s,toggleAudienceCreationDialog:i}=iie(),o=()=>{s(e),i("edit")},l=()=>t(e);return a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx(ar,{authorized:"ReportsInsights.Audiences.EditAudience",children:a.jsx(be,{title:"Edit audience",placement:"top",children:a.jsx("span",{children:a.jsx(Ie,{disabled:e.audience.status==="running",onClick:o,sx:{color:"icon.secondary",":hover":{backgroundColor:"primary.lightest"}},children:a.jsx(ou,{size:20})})})})}),a.jsx(ar,{authorized:"ReportsInsights.Audiences.DeleteAudience",children:a.jsx(be,{title:"Remove audience",placement:"top",children:a.jsx("span",{children:a.jsx(Ie,{disabled:e.audience.status==="running",onClick:()=>{r(!0)},sx:{color:"icon.secondary",":hover":{backgroundColor:"primary.lightest"}},children:a.jsx(Xr,{size:20})})})})}),a.jsx(Cl,{bodyText:`Are you sure you want to delete "${e.title}" audience? This will remove the audience and all its data.`,handleClose:()=>{r(!1)},handleDelete:l,open:n,title:"Delete Audience?"})]})},oie=rt(({children:e,className:t,...n})=>a.jsx(be,{...n,classes:{popper:t},children:e}))({[`& .${zv.tooltip}`]:{maxWidth:500}}),lie=({audience:e})=>{const{palette:t}=Re(),{description:n}
182=e?.audience||{},r=m.useMemo(()=>{const s=[];return Object.keys(n).forEach((i,o)=>{const l=n[i],c=t.chartSet[o];if(Array.isArray(l)){const d=a.jsx(gi,{children:a.jsxs(xn,{flexDirection:"row",gap:1,alignItems:"center",children:[a.jsx(gi,{sx:{width:"10px",height:"10px",backgroundColor:c}}),a.jsx(I,{children:i})]})}),u=l.map(h=>a.jsx(I,{component:"div",variant:"body2",sx:{pl:2},color:t.text.gray,children:h},h)),p=a.jsxs(gi,{children:[d,u]},i);s.push(p)}}),s},[n,t]);return a.jsx(oie,{title:a.jsx("div",{children:r.map(s=>a.jsx(Ne.Fragment,{children:s},s.key))}),children:a.jsx(I,{component:"div",variant:"body2",sx:{color:"text.primary"},children:e.title})})},cie=({audience:e})=>{const t=e?.audience?.status||"error",n=t==="running"?"warning":t==="complete"?"success":"error";return a.jsx(ut,{label:t,color:n,sx:{textTransform:"uppercase",borderRadius:1.5,height:24,px:.75,py:.375,".MuiChip-label":{pl:.5,pr:.25}}})},die=(e,t)=>{const n=Z(e.split(" - ")[0]),r=Z(t.split(" - ")[0]);return n.isAfter(r)?1:-1},uie=(e,t)=>Z(e).isAfter(t)?1:-1,pie=(e,t)=>{const n={running:1,complete:2,error:0},r=n[e.status.toLowerCase()]||Number.MAX_SAFE_INTEGER,s=n[t.status.toLowerCase()]||Number.MAX_SAFE_INTEGER;return r-s},hie=[{field:"title",headerName:"Name",renderCell:e=>a.jsx(lie,{audience:e.row}),flex:3,minWidth:175},{field:"audience",headerName:"Status",sortable:!0,sortComparator:pie,renderCell:e=>a.jsx(cie,{audience:e.row}),flex:1,minWidth:90},{field:"titleNiceId",headerName:"",renderCell:e=>a.jsx(aie,{audience:e.row}),sortable:!1,filterable:!1,minWidth:70}],fie=()=>a.jsx($,{sx:{gap:1,my:.5},children:Array(jP).fill(null).map((e,t)=>a.jsx(fe,{variant:"rounded",height:50},t))}),mie=({audiencesLoading:e,audienceToEdit:t,data:n,isAudienceCreationDialogOpen:r,onCreateAudience:s,toggleAudienceCreationDialog:i})=>{const o=zn(),l=c=>c.titleNiceId;return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",minWidth:600,width:"100%"},children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",pb:1},children:[a.jsx(Xt,{title:"Audience"}),a.jsx(T,{sx:{display:"flex",gap:2,height:36},children:a.jsx(ar,{authorized:"ReportsInsights.Audiences.CreateCustomAudience",children:a.jsx(re,{variant:"contained",sx:{py:.75,px:2},onClick:()=>{i("new")},disabled:n.length>=jP,children:"Create Custom Audience"})})})]}),a.jsx(I,{variant:"body2",sx:{pb:5},children:"Create custom audiences to view results in Data Exports, Planning, and Insights."}),a.jsx(T,{sx:{height:785},children:a.jsx(By,{apiRef:o,columns:hie,getRowId:c=>l(c),loading:e,rows:n,slots:{loadingOverlay:fie}})}),a.jsx(sie,{audienceToEdit:t,onCreateAudience:s,toggleAudienceCreationDialog:i,isAudienceCreationDialogOpen:r})]})},gie=({audiencesLoading:e,audienceToEdit:t,data:n,isAudienceCreationDialogOpen:r,onCreateAudience:s,toggleAudienceCreationDialog:i,updateAudienceToEdit:o})=>{const l=m.useMemo(()=>({audiencesLoading:e,audienceToEdit:t,data:n,isAudienceCreationDialogOpen:r,onCreateAudience:s,toggleAudienceCreationDialog:i,updateAudienceToEdit:o}),[e,t,n,r,s,i,o]);return a.jsx(EP.Provider,{value:l,children:a.jsx(mie,{audiencesLoading:e,audienceToEdit:t,data:n,isAudienceCreationDialogOpen:r,onCreateAudience:s,toggleAudienceCreationDialog:i,updateAudienceToEdit:o})})},xie=()=>{const{engagementNiceId:e}=pe(),{setRaiseConversationIcon:t}=jt(),[n,r]=m.useState(!1),[s,i]=m.useState(null),{data:{audiences:o=[]}={},isLoading:l}=G5({engagementNiceId:e}),c=SP(),[d]=kA(),{message:u}=fu("Audience");m.useEffect(()=>{u?.data.engagementNiceId===e&&d(null)},[u,e,d]);const p=g=>{switch(n&&i(null),t(!n),r(x=>!x),g){case"new":c("new");break;case"edit":c("edit",{name:s?.title});break}},h=g=>{i(g||null)},f=(g,x)=>{g==="new"?c("create",x):g==="edit"&&c("saveEdits",x)};return a.jsx(gie,{audiencesLoading:l,audienceToEdit:s,data:o,isAudienceCreationDialogOpen:n,onCreateAudience:f,toggleAudienceCreationDialog:p,updateAudienceToEdit:h})},_P=m.createContext(null),bo=()=>m.useContext(_P),bie={assignEngagement:"Assign Engagement",cloneEngagement:"Clone Engagement",clickCloneEngagement:"Open Clone Engagement Form",clickCreateEngagement:"Open Create Engagement Form",createClient:"Create Client",createEngagement:"Create Engagement",deleteEngagement:"Delete Engagement",clickEditEngagement:"Open Edit Engagement Form",editEngagement:"Save Engagement Edits"},ma=()=>{const{mpTrack:e}=tr();return(n,r)=>{e("MEVO_CONFIGURATION",{actionType:bie[n],actionData:{...r}})}},yie=({disableCopy:e,onCopyClicked:t,onCancelClicked:n})=>a.jsxs(T,{sx:{mb:3,display:"flex",gap:4,justifyContent:"flex-end"},children:[a.jsx(re,{"data-testid":"configuration:clone:cancel:button",sx:{width:120},onClick:n,children:"Cancel"}),a.jsx(re,{"data-testid":"configuration:clone:copy:button",sx:{width:120},variant:"contained",disabled:e,onClick:t,children:"Copy"})]}),Hf=["allSources.list","allSources.partitions"],qf=["singleSource.advanced","singleSource.configuration","singleSource.mapAndTransform","singleSource.schedule"],Gf=[...qf,"singleSource.notes","singleSource.overview","singleSource.partitions","singleSource.summary"],vie=[...Hf,...Gf],F0="allSources.list",Cie="singleSource.partitions",Ge={active:"Active",actions:"Actions",api_config:"API Configuration",api_secret:"API Secret",connection_id:"Connection",content_type:"C
182ontent Type",created_at:"Creation Date",delivery_method:"Connector",di_config:"Data Ingestion Configuration",external_contacts:"External Contacts",feed_nice_id:"Feed",file_compression:"File Compression",file_config:"Additional Settings",file_delimiter:"File Delimiter",file_extension:"File Extension",file_filter:"File Filter",frequency:"Frequency",freq_offset:"Offset",id:"Id",internal_assigned:"Internal Assigned",last_run_state:"Status",last_run_ts:"Last Run",name:"Name",path:"File Path",primary_contact:"Primary Contact",s3_bucket:"Bucket",supervisor_scheduling:"Schedule",updated_at:"Last Modified",validation_active:"Verify",vendor_nice_id:"Data Provider"},hr={assignedContacts:"Assigned Contacts",connector:"Connector Configuration",dataProcessing:"Data Processing Configuration",file:"File Configuration",general:"General",headers:"Headers",nameCleaning:"Name Cleaning",runSettings:"Run Settings"},TP=["api","bigquery","snowflake","s3","cm360","dv360","googleads","ga4"],IP={api:"Other API",bigquery:"BigQuery",snowflake:"Snowflake",s3:"S3",cm360:"Campaign Manager 360",dv360:"Display Video 360",googleads:"Google Ads",ga4:"Google Analytics 4"},wie=[".csv",".json",".log",".psv",".tsv",".txt"],Sie=["",".gz",".zip"],jie={":":'Colon (":")',",":'Comma (",")',"|":'Pipe ("|")',";":'Semicolon (";")'," ":'Tab ("\\t")'},Tr={brand:"brand",creative:"creative",glAttributes:["country","market","platform","tactic","type","vehicle"],placement:"placement",type:{full:"full",custom:"custom",none:"none"}},kie={active:!1,api_config:null,api_secret:null,connection_id:null,contacts:null,di_config:null,events_json:null,execution_steps:null,file_compression:null,file_config:null,file_delimiter:null,file_extension:null,file_filter:null,frequency:"monthly",freq_offset:1,header_json:null,name:null,name_cleaning:null,notes:null,path:null,s3_bucket:null,supervisor_scheduling:!1,validation_active:!1},Mr=e=>{if(!e)return"";const{content_type:t,feed_nice_id:n,name:r,vendor_nice_id:s}=e,i=[t,s,n].join("_");return r?`${r} (${i})`:i},Eie=(e,t)=>{const n=e.contacts?.filter(({is_internal:s})=>!s);if(!n?.length)return!1;const r=t.toLowerCase();return n.some(s=>{const i=s.name.toLowerCase(),o=s.email?.toLowerCase()??"";return i.includes(r)||o.includes(r)})},_ie=new Intl.PluralRules("en-US",{type:"ordinal"}),Tie=new Map([["one","st"],["two","nd"],["few","rd"],["other","th"]]),Iie=e=>{const t=_ie.select(e),n=Tie.get(t);return`${e}${n}`},$0=({frequency:e,offset:t})=>{if(!e)return"";let n="";if(t!==null)switch(e.toLowerCase()){case"monthly":n=` (${Iie(t)})`;break;case"weekly":n=` (${Z().day(t+1).format("ddd")})`;break}return`${sh(e.toLowerCase())}${n}`},Ep=({attr:e,step:t})=>`The ${t} execution step is not currently configured. To use ${e} name cleaning, please add this step.`,Die=({executionSteps:e,nameCleaningValues:t})=>{const{attributes:n,placements:r,creatives:s,brand:i}=t,o=e?.find(f=>f.step==="media_resolution"),l=e?.find(f=>f.step==="touchpoint_resolution"),c=e?.find(f=>f.step==="brand_resolution"),d=n?.length&&!o?Ep({attr:"Attribute",step:"Media Resolution"}):"",u=r&&!l?Ep({attr:"Placement",step:"Touchpoint Resolution"}):"",p=s&&!l?Ep({attr:"Creative",step:"Touchpoint Resolution"}):"",h=i&&!c?Ep({attr:"Creative",step:"Brand Resolution"}):"";return{attributes:d,placement:u,creative:p,brand:h}},z0=e=>"step"in e?KD(String(e.step).replaceAll("_"," ")):"output_header"in e?String(e.output_header):"input_header"in e?String(e.input_header):"Unknown",Yf=e=>{if(!e)return null;const t=e.split(".").find(n=>n.trim());return t?`.${t.trim().toLowerCase()}`:null},B0=e=>{switch(e){case"Approved":return{chipColor:"success",color:"success.main"};case"Rejected":return{chipColor:"error",color:"error.main"};case"Ready for QA":return{chipColor:"info",color:"info.main"};case"Pending":return{chipColor:"warning",color:"warning.main"};default:return{chipColor:"default",color:"text.secondary"}}},SE=e=>Tn(qf,e),Ex=({currentView:e,paramsView:t})=>Tn(Hf,t)?t:Tn(Hf,e)?e:F0,jE=({currentView:e,editEnabled:t,paramsView:n})=>Tn(Gf,n)&&(!SE(n)||t)?n:Tn(Gf,e)&&(!SE(e)||t)?e:Cie,Aie=({currentSource:e,currentView:t,dataSources:n,editEnabled:r,paramsId:s,paramsView:i})=>{if(s!==e?.id){if(s!==null){const d=n.find(p=>p.id===s);return d?{nextView:jE({currentView:t,editEnabled:r,paramsView:i}),nextSource:d}:{nextView:Ex({currentView:t,paramsView:i}),nextSource:null}}return{nextView:Ex({currentView:t,paramsView:i}),nextSource:null}}return e!==null?{nextView:jE({currentView:t,editEnabled:r,paramsView:i}),nextSource:e}:{nextView:Ex({currentView:t,paramsView:i}),nextSource:null}},Mie={filterModel:{items:[{id:1,field:"active",operator:"is",value:"true"}]}},DP=({active:e})=>a.jsx(ut,{label:e?"Yes":"No",color:e?"success":"default"}),_x={filterable:!1,sortable:!0,type:"action",flex:1},Rie=[{..._x,field:"id",headerName:"ID",minWidth:250},{..._x,field:"name",headerName:"Data source name",minWidth:250},{..._x,field:"active",headerName:"Active",renderCell:({value:e=!1})=>a.jsx(DP,{active:e}),type:"boolean",filterable:!0,minWidth:100}],Uy=bs(Mn)(({theme:e})=>{const{text:t,background:n,border:r}=e.palette,{spacing:s}=e,i={backgroundColor:"white",color:t.default,":hover":{backgroundColor:n.brand.subtlest.default}};return{border:"none",minHeight:250,maxHeight:400,[`.${xe.main}
182`]:{height:"100%",borderRadius:"6px",border:"1px solid",borderColor:r.default},[`.${xe.cell}`]:{border:"none",paddingLeft:s(2),paddingRight:s(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1)}},[`.${xe.columnHeader}`]:{paddingLeft:s(2.5),paddingRight:s(1),":focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1.5)}},[`.${xe.columnHeaders}`]:{backgroundColor:n.tableHeader,border:"none"},[`.${xe.columnHeaderTitleContainerContent}`]:{textTransform:"uppercase",fontSize:12},[`.${xe.row}`]:{paddingLeft:s(.5),...i},[`.${xe.row}:nth-of-type(even)`]:{...i},[`.${xe.cellCheckbox}`]:{padding:"0"}}});Uy.defaultProps={...Uy.defaultProps,columnHeaderHeight:40,disableColumnPinning:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,rowHeight:40,checkboxSelection:!0,hideFooter:!0};const Nie=({engagementNiceId:e,onSelectionChange:t})=>{const{supportLink:n}=jt(),{data:r,isLoading:s,isError:i}=EA(e),o=m.useMemo(()=>r?r.map(l=>({active:l.active,id:l.id,name:Mr(l)})):[],[r]);return i?a.jsxs(T,{sx:{display:"flex",flexDirection:"row"},children:[a.jsx(I,{children:"There are not available data sources to copy this engagement. If you think this is an error please file a "}),a.jsx(lu,{href:n,text:"support ticket."})]}):a.jsxs(T,{sx:{width:"100%",display:"grid",mb:3},children:[a.jsx(I,{sx:{mb:1},children:"Select the data sources you want to clone:"}),a.jsx(Uy,{columns:Rie,loading:s,rows:o,slots:{loadingOverlay:Cs},initialState:{filter:Mie},onRowSelectionModelChange:l=>t(l)})]})},Oie=({disabled:e,locale:t,dateValues:n,setDateValues:r,startDate:s})=>a.jsx(T,{sx:{mb:3},children:a.jsx(ts,{value:n,disabled:e,setValue:r,locale:t,minDate:s})}),AP=({onValidInput:e,onInvalidInput:t,setPendingValidationStatus:n})=>{const[r]=Y5(),[s,i]=m.useState(null),o=fs(async l=>{try{const{is_valid:c,message:d}=await r({name:l,niceId:TC(l)}).unwrap();if(c&&l.length)i(null),e();else{const u=d??"Name is required";i(u),t(u)}}catch(c){We(c);const d="Validation failed";i(d),t(d)}finally{n(!1)}},500);return{errorMessage:s,debouncedNameValidation:o}},Pie=({value:e,onChange:t,setPendingValidationStatus:n,onInvalidInput:r,onValidInput:s})=>{const{debouncedNameValidation:i,errorMessage:o}=AP({onInvalidInput:r,onValidInput:s,setPendingValidationStatus:n}),l=c=>{const d=c.target.value;t(d),n(!0),i(d)};return a.jsxs(T,{sx:{mb:2,width:260},children:[a.jsx(De,{autoComplete:"off",sx:{width:"100%","& input":{fontSize:14,overflow:"visible"}
182,"& input::placeholder":{overflow:"visible"}},type:"text",name:"name",value:e,onChange:l,label:"Engagement name",inputProps:{"data-testid":"configuration:clone:name:input"}}),!!o&&a.jsx(Zn,{id:"clone-engagement-name-error",error:!0,children:o})]})},Lie=()=>{const{engagementToClone:e,setEngagementToClone:t}=bo(),{userId:n}=gt(),{engagementCountry:r}=pe(),s=ma(),[i,o]=m.useState([null,null]),[l,c]=m.useState(`Copy of ${e?.brand_name}`),[d,u]=m.useState(!1),p=TC(l),[h,f]=m.useState(!0),[g,x]=m.useState([]),b=!g?.length,[y,v]=i,C=y!==null&&v!==null,[w]=K5();if(!e)return null;const S=()=>{t(null)},E=async()=>{s("cloneEngagement",{cloneData:{clientNiceId:e.client_nice_id||"",cloneName:l,cloneNiceId:p,parentEngagementNiceId:e.nice_id}}),await w({client_nice_id:e.client_nice_id,datasource_ids:g,end_date:v?.format("YYYY-MM-DD"),parent_engagement_id:e.id,parent_engagement_brand_name:e.brand_name,parent_engagement_nice_id:e.nice_id,identity_id:n,cloned_engagement_brand_name:l,cloned_engagement_nice_id:p,start_date:y?.format("YYYY-MM-DD")}),t(null)};return a.jsxs(T,{children:[a.jsx($,{direction:"row",justifyContent:"space-between",pb:3,children:a.jsx(Xt,{title:"Configuration"})}),a.jsxs(I,{sx:{mb:3},variant:"h6",children:["Copying ",e.brand_name]}),a.jsx(I,{sx:{mb:1},children:a.jsx("strong",{children:"Please rename the engagement."})}),a.jsx(Pie,{value:l,onChange:c,onInvalidInput:()=>f(!1),onValidInput:()=>f(!0),setPendingValidationStatus:u}),a.jsx(Oie,{dateValues:i,disabled:!r,locale:r,setDateValues:o,startDate:Z(e.created_at)}),a.jsx(Nie,{engagementNiceId:e.nice_id,onSelectionChange:x}),a.jsx(yie,{disableCopy:!h||d||!C||b,onCopyClicked:E,onCancelClicked:S})]})},Fie=({clients:e,engagements:t,userEngagementsIds:n})=>!e.length||!t.length||n.size===0?[]:t.map(r=>{const s=e.find(c=>c.id===r.client_id),i=s?s.name:"",o=s?s.niceId:"",l=n.has(r.id);return{...r,engagement:{name:r.brand_name,id:r.id,status:r.status},client_name:i,client_nice_id:o,assigned:l}}),$ie=({editedAssigned:e,tableRows:t})=>{const n=[];return e.size&&Array.from(e.entries()).forEach(([r,s])=>{const i=t.find(o=>o.id===r);i&&n.push({...i,assigned:s})}),n},kE=(e,t)=>{const n=new Map(e);return Array.from(t.entries()).forEach(([r,s])=>{s?n.set(r,s):!s&&n.has(r)&&n.delete(r)}),Array.from(n.keys())},zie={open:!1,errorText:"",loading:!1},Bie=(e,t)=>{switch(t.type){case"reset":return{...e,open:!1,errorText:"",loading:!1};case"clickAddClientButton":return{...e,open:!0};case"createClientError":return{...e,open:!0,errorText:t.value,loading:!1};case"removeErrorText":return{...e,errorText:""};case"loading":return{...e,loading:!0};default:return{...e}}};var bc={},EE;function Uie(){if(EE)return bc;EE=1;var e=Pt();Object.defineProperty(bc,"__esModule",{value:!0}),bc.default=void 0;var t=e(Lt()),n=Ot();return bc.default=(0,t.default)((0,n.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m5 11h-4v4h-2v-4H7v-2h4V7h2v4h4z"}),"AddCircle"),bc}var Vie=Uie();const Wie=dt(Vie),Hie=({children:e,...t})=>a.jsxs(Fv,{...t,children:[a.jsx(Wie,{sx:{mr:1}}),e]}),qie=({dispatch:e,onCreateClient:t,state:n})=>{const r=ct(),[s,i]=m.useState(""),{errorText:o,loading:l,open:c}=n,d=ma(),u=()=>{e({type:"reset"}),i("")},p=async()=>{u()},h=async()=>{e({type:"loading"});try{d("createClient",{clientName:s}),await t(s),r()&&u()}catch(g){typeof g=="string"&&r()&&e({type:"createClientError",value:g})}},f=a.jsxs(T,{sx:{pt:2},children:[a.jsx(De,{color:"secondary",disabled:l,fullWidth:!0,inputProps:{maxLength:125},label:"Client name",onChange:g=>{i(g.target.value)},value:s}),o&&a.jsx(Zn,{error:!0,children:o})]});return a.jsx(mt,{acceptButtonProps:{loading:l},acceptLabel:"Confirm",body:f,handleAccept:h,handleClose:p,open:c,resetLoadingAfterAccept:!0,title:"Add New Client"})},Gie=rt(ys)(()=>({height:42,width:228,".MuiInputBase-inputAdornedStart":{paddingRight:0,height:24},"&.Mui-focused":{".MuiOutlinedInput-notchedOutline":{boxShadow:"none"}}})),Yie=({clientOptions:e,loading:t,onCreateClient:n,selectedClient:r,updateSearchValue:s,updateSelectedClient:i,userIsSuper:o})=>{const[l,c]=m.useState(""),[d,u]=m.useReducer(Bie,zie),p=fs(s,500),h=x=>{const b=x.target.value;c(b),p(b)},f=({target:{value:x}})=>{x&&(i(x),l&&c(""))},g=()=>{u({type:"clickAddClientButton"})};return a.jsxs($,{direction:"row",justifyContent:"space-between",py:3,children:[a.jsx(Ar,{"data-testid":"configuration:client-filter:select",sx:{width:230},disabled:t,isLoading:t,onChange:f,options:e,customOption:o?a.jsx(Hie,{onClick:g,children:"Add New Client"},"add-client"):null,customOptionPlacement:"first",value:r}),a.jsx(Qe,{children:a.jsx(Gie,{inputProps:{"data-testid":"configuration:search:input"},disabled:t,startAdornment:a.jsx(Mt,{sx:{color:"text.disabled",fontSize:20,mr:1},children:a.jsx(er,{})}),onChange:h,placeholder:"Search",value:l})}),a.jsx(qie,{dispatch:u,onCreateClient:x=>n(x),state:d})]})},eg=({open:e,resourceName:t,resourceType:n,deleting:r,captchaText:s="DELETE",onClose:i,onDelete:o,errorMessage:l})=>a.jsx(Ub,{open:e,title:`Delete ${n}?`,message:a.jsxs(I,{children:["Are you sure you want to delete"," ",a.jsx(I,{component:"span",sx:{fontWeight:"bold",color:"primary.main"},children:t}),"? This will remove the ",n," and all of the supporting data."]}),confirmationText:s,confirmButtonText:"Delete",confirmButtonColor:"error",cancelButtonText:"Close",isProcessing:r,onClose:i,onConfirm:o,errorMessage:l}),Kie=()=>{const{engagementToDelete:e,setEngagementToDelete:t,onDeleteEngagement:n}=bo(),[r,s]=m.useState(""),[i,o]=m.useState(!1),l=ma(),{userIsInternal:c}=gt(),{clientId:d}=pe(),u=()=>{t(null),s("")},p=async()=>
182{if(!e)return;o(!0),l("deleteEngagement",{engagementNiceId:e.nice_id});const h=await n({client_nice_id:e.client_nice_id,engagement_nice_id:e.nice_id,bodyCacheArgs:c?{}:{client_id:d}});if(o(!1),"error"in h){s("An error occurred while trying to delete this engagement");return}u()};return a.jsx(eg,{captchaText:e?.nice_id??"DELETE",deleting:i,errorMessage:r,onClose:u,onDelete:p,open:!!e,resourceName:e?.brand_name??"",resourceType:"Engagement"})},MP=m.createContext(null),yo=()=>m.useContext(MP),Hr=()=>on(),Qie=({engagement:e,clientNiceId:t,editing:n,targets:r,objectives:s})=>({active:n?e?.active??!1:!0,targets:r,objectives:s??[],mfa_flag:e?.mfa_flag??!1,brand_color:e?.brand_color??"",client_nice_id:t??"",country:e?.country??"",currency:e?.currency??"",date_format:e?.date_format??"",ds_license:e?.ds_license??10,engagement_name:e?.brand_name??"",geo_granularity:e?.geo_granularity??"",kpi_license:e?.kpi_license??10,logo:e?.brand_logo??"",dataplatform_flag:e?.dataplatform_flag??!1,notes:e?.notes??""}),Vy=e=>{const t=e.trim();return t===""?"":(t.startsWith("#")?t:`#${t}`).toUpperCase()},RP=e=>{const t=Vy(e??"");return t===""?null:t},Jie=e=>e.size/1024/1024<10,Xie=(e,t)=>{let n="";return e?.name?n=URL.createObjectURL(e):t&&(n=`${t}?${Math.floor(Number(new Date))}`),n},NP=["light","dark"],Tx=(e,t)=>e.toUpperCase()===t.toUpperCase(),OP=(e,t)=>{const n=oU[t],r=QD[t],s=aU(e,n),i=lU({brandColor:e,surface:n,minContrast:Rb,fallback:r});if(s===null||i===null)return null;const o=Sj(s,jj),l=Sj(n,jj),c=pd(s),d=pd(o),u=pd(n);return o===null||l===null||!c||!d||!u?null:{mode:t,surface:n,surfaceInk:l,band:s,bandInk:o,bandInkContrast:kj(d,c),rule:i,canonicalContrast:kj(c,u),ruleAdjusted:!Tx(i,s),ruleFellBack:Tx(i,r)&&!Tx(s,r)}},PP=e=>`${e.toFixed(2)}:1`,Zie={light:"Light theme",dark:"Dark theme"},eae="Q1 Sales Performance",_E={fontSize:20,fontWeight:700,lineHeight:1.3},tae=({chrome:e})=>{const{band:t,bandInk:n,bandInkContrast:r,mode:s,rule:i,surface:o,surfaceInk:l}=e;return a.jsxs($,{sx:{flex:1,gap:1},children:[a.jsx(I,{variant:"body2",sx:{fontWeight:600},children:Zie[s]}),a.jsxs(T,{"data-testid":`brand-color:preview:${s}`,sx:{backgroundColor:o,border:"1px solid",borderColor:"border.input",borderRadius:2,overflow:"hidden"},children:[a.jsx(T,{sx:{backgroundColor:t,px:2,py:1.5},children:a.jsx(I,{sx:{..._E,color:n},children:eae})}),a.jsxs(T,{sx:{px:2,py:2},children:[a.jsx(I,{sx:{..._E,color:l,mb:1},children:"Media Performance"}),a.jsx(T,{sx:{backgroundColor:i,height:3,borderRadius:1}}),a.jsxs(I,{variant:"caption",sx:{color:l,display:"block",mt:1.5},children:["Band ",t," · ink ",n," (",PP(r),") · rule ",i]})]})]})]})},nae=({brandColor:e})=>{const t=NP.map(n=>OP(e,n)).filter(n=>n!==null);return t.length===0?null:a.jsx($,{sx:{gap:1},"data-testid":"brand-color:preview",children:a.jsx($,{direction:{xs:"column",sm:"row"},sx:{gap:2},children:t.map(n=>a.jsx(tae,{chrome:n},n.mode))})})},rae="Uses Darwin branding",sae="Paste a hex from the client's brand guide. Leave blank to use Darwin branding.",iae=e=>{const t=pd(e);return t?JD(t):QD.light},aae=e=>NP.flatMap(t=>{const n=OP(e,t);if(!n?.ruleAdjusted)return[];const r=PP(n.canonicalContrast);return n.ruleFellBack?[`${t==="light"?"Light":"Dark"} theme: at ${r} against the page, no variant of this hue reaches ${Rb}:1, so hairline rules fall back to the Darwin accent. Filled header bands still use your exact color.`]:[`${t==="light"?"Light":"Dark"} theme: at ${r} against the page this is below the ${Rb}:1 floor for a hairline rule, so rules are shifted to ${n.rule}. Filled header bands still use your exact color.`]}),oae=()=>{const{control:e}=Hr();return a.jsx(Et,{control:e,name:"brand_color",render:({field:{onBlur:t,onChange:n,value:r},fieldState:{error:s}})=>{const i=r??"",o=s?[]:aae(i);return a.jsxs($,{sx:{gap:2},children:[a.jsxs($,{direction:"row",sx:{gap:2,alignItems:"flex-start"},children:[a.jsx(T,{"aria-label":"Brand color picker",component:"input","data-testid":"engagement-form:brand-color:swatch",onChange:l=>{n(Vy(l.target.value))},sx:{backgroundColor:"transparent",border:"1px solid",borderColor:"border.input",borderRadius:1,cursor:"pointer",height:56,minWidth:56,p:.5,width:56},type:"color",value:iae(i)}),a.jsx(De,{error:!!s,helperText:s?.message||sae,inputProps:{"data-testid":"engagement-form:brand-color:input",maxLength:9},label:"Brand Color",onBlur:t,onChange:l=>{n(Vy(l.target.value))},placeholder:"#ED1D24",sx:{maxWidth:220},value:i}),a.jsx(re,{disabled:i==="",onClick:()=>{n("")},sx:{mt:1},variant:"outlined",children:"Use Darwin branding"})]}),i===""?a.jsx(I,{variant:"body2","data-testid":"engagement-form:brand-color:empty",children:rae}):null,o.map(l=>a.jsx(vn,{severity:"warning",children:l},l)),a.jsx(nae,{brandColor:i})]})}})},LP=({defaultValue:e=!0,editing:t,fieldName:n,hideButton:r=!1,idPath:s,onDelete:i})=>{const{control:o,watch:l}=Hr(),c=l(s),d=l(n)??!0;return r?null:a.jsx(Et,{control:o,defaultValue:e,name:n,render:({field:{onBlur:u,onCh
182ange:p,value:h}})=>a.jsx(Ie,{onBlur:u,color:d?"default":"error","aria-label":"delete",onClick:()=>{t&&c?p(!h):i()},sx:{fill:({palette:f})=>f.icon.secondary,marginBottom:"19px"},children:a.jsx(Xr,{size:24})})})},ld=({disabled:e=!1,defaultValue:t="",fieldName:n,label:r,required:s=!1,items:i,testId:o})=>{const{control:l}=Hr();return a.jsx(Et,{control:l,name:n,render:({field:{value:c,onBlur:d,onChange:u},fieldState:{error:p}})=>a.jsxs(Qe,{disabled:e,fullWidth:!0,required:s,variant:"filled",children:[a.jsx(wt,{error:!!p,children:r}),a.jsx(tt,{"data-testid":o,error:!!p,label:r,onBlur:d,onChange:h=>{const{value:f}=h.target;u(f)},required:s,value:c??t,children:i.map(h=>a.jsx(Se,{value:h.value,children:h.label},h.value))}),a.jsx(Zn,{error:!!p,children:p?.message||" "})]})})},lae="Maximum size: 10MB, JPG or PNG",ga={audiences:"Target Audience",branding:"Engagement Branding",details:"Engagement Details",engagementSettings:"Settings",kpis:"Key Performance Indicators",notes:"Notes",security:"Security",settings:"Account Settings"},TE={maxWidth:160,minWidth:160,maxHeight:64,minHeight:64,p:.5},cae=({imageSrc:e="",fileInputRef:t})=>e?a.jsx(T,{component:"img",src:e,sx:{...TE,flexGrow:1,objectFit:"contain",objectPosition:"center"}}):a.jsx(T,{sx:{...TE,flexGrow:1,backgroundColor:"action.disabledBackground",alignContent:"center",textAlign:"center"},children:a.jsx(Ie,{onClick:()=>t?.current?.click(),children:a.jsx(cU,{size:24})})}),dae=()=>a.jsxs(I,{fontSize:11,children:["Specs: ",a.jsx("br",{}),"⢠JPG or PNG file type only. ",a.jsx("br",{}),"⢠Your logo will be proportionally scaled."]}),uae=({fieldName:e,fileInputRef:t,nextLogoFile:n,onUpload:r})=>{const{control:s}=Hr(),[i,o]=m.useState(!1);return a.jsx(Et,{control:s,name:e,render:({field:{onChange:l,value:c},fieldState:{error:d}})=>{const u=Xie(n,JSON.stringify(c)),p=!!n||!!c,h=c&&typeof c=="string"?c.split("/").pop():"";return a.jsxs($,{direction:"row",gap:3,children:[a.jsx(cae,{fileInputRef:t,imageSrc:u}),a.jsxs($,{direction:"column",gap:2,children:[a.jsxs($,{direction:"row",gap:3,children:[a.jsx(be,{title:a.jsx(dae,{}),children:a.jsx(re,{sx:{maxHeight:40,maxWidth:130,minWidth:130,padding:2},onClick:()=>t?.current?.click(),variant:"outlined",children:p?"Replace Logo":"Upload Logo"})}),p?a.jsx(be,{title:"Remove Icon",children:a.jsx(Ie,{onClick:()=>{l(""),r(null),o(!1)},children:a.jsx(Xr,{})})}):null]}),a.jsx(I,{sx:{color:i?"error.main":"inherit"},children:h||d?.message||lae})]}),a.jsx("input",{id:"upload-logo-input-component",onChange:f=>{const[g]=f.target.files||[],x=document.getElementById("upload-logo-input-component");x&&(CY(x).value=""),g&&Jie(g)?(l(g.name),r(g),o(!1)):(l(""),r(null),o(!0))},type:"file",accept:".jpg, .png, .jpeg",hidden:!0,ref:t})]})}})},Wy=({fieldName:e,label:t,control:n,disabled:r})=>a.jsx(Et,{name:e,control:n,render:({field:s,fieldState:{error:i}})=>a.jsxs(Qe,{sx:{width:"100%"},children:[a.jsxs(T,{display:"flex",justifyContent:"space-between",alignItems:"center",sx:{border:"1px solid",borderColor:"border.default",borderRadius:1,padding:"8px 12px"},children:[t,a.jsx(Dn,{disabled:r,...s,checked:s.value,onChange:o=>{const l=o.target.checked;s.onChange(l)},color:"primary"})]}),a.jsx(Zn,{error:!!i,children:i?.message||" "})]})}),qa=({disabled:e,defaultValue:t="",fieldName:n,InputProps:r,label:s,required:i=!1,testId:o,type:l="text",onValueChange:c})=>{const{control:d}=Hr();return a.jsx(Et,{control:d,defaultValue:t,name:n,render:({field:{onBlur:u,onChange:p,value:h},fieldState:{error:f}})=>a.jsx(De,{disabled:e,error:!!f,fullWidth:!0,helperText:f?.message||" ",inputProps:{"data-testid":o},InputProps:r,label:s,onBlur:u,onChange:g=>{const x=g.target.value;l==="number"?x===""?p(null):Number(x)>=0&&p(Number(x)):p(x),c?.(x)},required:i,type:l,value:h??null})})},U0=()=>{const{watch:e}=Hr(),t=e("objectives"),n=e("kpi_license"),r=m.useMemo(()=>t.reduce((s,i)=>i?.active?s+1:s,0),[t]);return{availableLicenses:n,activeKpiCount:r}},IE={mb:2,display:"flex",alignItems:"center"},pae=()=>{const{editing:e}=yo(),{activeKpiCount:t,availableLicenses:n}=U0();return a.jsxs(a.Fragment,{children:[e&&a.jsx(vn,{severity:"info",sx:({palette:r})=>{const s=r.mode==="dark"?r.info.dark:r.info.light,i=r.getContrastText(s);return{bgcolor:s,color:i,"& .MuiAlert-icon":{color:i},...IE}},children:"KPIs can be edited in Machine Learning under the Data Utilities menu"}),t>=n&&a.jsx(vn,{severity:"warning",sx:({palette:r})=>{const s=r.mode==="dark"?r.warning.dark:r.warning.light,i=r.getContrastText(s);return{bgcolor:s,color:i,"& .MuiAlert-icon":{color:i},...IE}},children:"KPI limit reached. Edit existing KPIs in Machine Learning under the Data Utilities menu or contact support to increase your limit."})]})},hae=({handleClick:e})=>{const{activeKpiCount:t,availableLicenses:n}=U0(),r=t>=n;return a.jsx(be,{title:r?`You have reached your current KPI licenses of ${n}, please increase your licenses to add more KPIs`:"",placement:"top-start",children:a.jsx(T,{children:a.jsxs(re,{color:"secondary",disabled:r,onClick:e,variant:"text",children:[a.jsx(ca,{size:14})," Add KPI"]})})})},fae=()=>{const{control:e,getValues:t,setError:n,trigger:r}=Hr(),{editing:s}=yo(),{fields:i,remove:o,append:l}=KM({control:e,name:"objectives"}),c=m.useCallback(async()=>
182{if(!await r("objectives"))return;const f=t("objectives"),g=f.map(({name:b})=>b),x=g.filter((b,y)=>g.indexOf(b)!==y);f.forEach(({name:b},y)=>{b&&x.includes(b)&&n(`objectives.${y}.name`,{message:`Duplicated KPI name: ${b}`,type:"validate"})})},[t,n,r]),d=fs(()=>{c()},300),u=h=>{o(h),d()},p=()=>{l({name:"",value_per_conversion:0,kpi_scalar:null,newObjective:!0,active:!0})};return a.jsxs(Zt,{title:ga.kpis,children:[a.jsx(pae,{}),a.jsx($,{children:i.map(({id:h,newObjective:f=!1},g)=>a.jsxs(T,{sx:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx(qa,{fieldName:`objectives.${g}.name`,label:"KPI",required:!0,onValueChange:d,disabled:s&&!f}),a.jsx(T,{sx:{minWidth:"260px",marginLeft:"10px"},children:a.jsx(qa,{fieldName:`objectives.${g}.value_per_conversion`,label:"Revenue per Conversion",type:"number",disabled:s&&!f})}),a.jsx(T,{sx:{minWidth:"260px",marginLeft:"10px"},children:a.jsx(qa,{fieldName:`objectives.${g}.kpi_scalar`,label:"KPI Scalar",type:"number",disabled:s&&!f})}),a.jsx(LP,{editing:s,fieldName:`objectives.${g}.active`,hideButton:!f,idPath:`objectives.${g}.id`,onDelete:()=>u(g)})]},h))}),a.jsx(hae,{handleClick:p})]})},mae=()=>{const{control:e,setError:t,watch:n,trigger:r}=Hr(),{editing:s}=yo(),{activeKpiCount:i}=U0(),o=n("kpi_license");return m.useEffect(()=>{(async()=>await r("kpi_license")&&i>o&&t("kpi_license",{message:"Active KPIs are greater than the current available licenses",type:"validate"}))()},[o,i,r,t]),a.jsx(Zt,{title:ga.settings,children:a.jsxs($,{rowGap:"14px",children:[a.jsx(qa,{fieldName:"ds_license",label:"Data Source Licenses",required:!0,testId:"engagement-form:field:ds-license",type:"number"}),a.jsx(qa,{fieldName:"kpi_license",label:"KPI Licenses",required:!0,testId:"engagement-form:field:kpi-license",type:"number"}),a.jsx(Wy,{disabled:!s,fieldName:"active",label:"Active",control:e}),a.jsx(Wy,{fieldName:"dataplatform_flag",label:"Data Platform",control:e})]})})},gae=()=>{const{dispatch:e,state:t}=yo(),{nextLogoFile:n}=t,r=m.createRef();return a.jsx(Zt,{title:ga.branding,children:a.jsxs($,{rowGap:3,children:[a.jsx(uae,{fileInputRef:r,fieldName:"logo",nextLogoFile:n,onUpload:s=>{e({type:"nextLogoFile",value:s})}}),a.jsx(St,{}),a.jsx(oae,{})]})})},xae=()=>{const{setError:e,clearErrors:t}=Hr(),{setIsValidating:n,clients:r,editing:s}=yo(),{debouncedNameValidation:i}=AP({onInvalidInput:l=>e("engagement_name",{message:l,type:"validate"}),onValidInput:()=>t("engagement_name"),setPendingValidationStatus:n}),o=l=>{n(!0),i(l)};return a.jsx(Zt,{title:ga.details,children:a.jsxs($,{rowGap:1,children:[a.jsx(ld,{disabled:s,fieldName:"client_nice_id",label:"Client Name",required:!0,testId:"engagement-form:field:client-name",items:r.map(l=>({value:l.niceId,label:l.name}))}),a.jsx(qa,{fieldName:"engagement_name",label:"Engagement Name",required:!0,testId:"engagement-form:field:engagement-name",onValueChange:o})]})})},bae=()=>{const{control:e}=Hr();return a.jsx(Et,{control:e,name:"notes",defaultValue:"",render:({field:{onChange:t,value:n}})=>a.jsx(cu,{height:400,value:n??"",onChange:t,placeholder:"Add notes about this engagement..."})})},yae=()=>a.jsx(Zt,{title:ga.notes,children:a.jsx(bae,{})}),vae=()=>{const{control:e}=Hr();return a.jsx(Zt,{title:ga.security,children:a.jsx(Wy,{fieldName:"mfa_flag",label:"Multi-Factor Authentication",control:e})})},Cae=()=>a.jsxs(Zt,{title:ga.engagementSettings,children:[a.jsxs(T,{display:"flex",justifyContent:"space-between",mb:2,children:[a.jsx(T,{sx:{mr:1,flex:1},children:a.jsx(ld,{fieldName:"country",label:"Country",testId:"engagement-form:field:country",items:[{value:"US",label:"United States"},{value:"CA",label:"Canada"},{value:"FR",label:"France"},{value:"UK",label:"United Kingdom"},{value:"EU",label:"European Union"}],defaultValue:""})}),a.jsx(T,{sx:{flex:1},children:a.jsx(ld,{fieldName:"currency",label:"Currency",testId:"engagement-form:field:currency",items:[{value:"USD",label:"USD ($)"},{value:"CAD",label:"CAD ($)"},{value:"EUR",label:"EUR (â¬)"},{value:"GBP",label:"GBP (£)"}],defaultValue:""})})]}),a.jsx(St,{sx:{mb:2}}),a.jsx(I,{variant:"h6",gutterBottom:!0,children:"Appearance"}),a.jsx(T,{sx:{mb:2,mt:2},children:a.jsx(ld,{fieldName:"geo_granularity",label:"Geographical Level",testId:"engagement-form:field:geo-granularity",items:[{value:"city",label:"City"},{value:"dma",label:"DMA"},{value:"province",label:"Province"},{value:"region",label:"Region"},{value:"state",label:"State"}],defaultValue:""})}),a.jsx(T,{children:a.jsx(ld,{fieldName:"date_format",label:"Date Format",testId:"engagement-form:field:date-format",items:[{value:"MM/DD/YYYY",label:"MM/DD/YYYY"},{value:"DD/MM/YYYY",label:"DD/MM/YYYY"},{value:"YYYY/MM/DD",label:"YYYY/MM/DD"}],defaultValue:""})})]}),wae=()=>{const{control:e,getValues:t,setError:n,trigger:r}=Hr(),{fields:s,append:i,remove:o}=KM({control:e,name:"targets"}),{editing:l}=yo(),c=()=>{i({name:"",newTarget:!0})},d=async()=>{await r("targets");const u=t("targets"),p=u.map(({name:f})=>f),h=p.filter((f,g)=>p.indexOf(f)!==g);u.forEach(({name:f},g)=>{f&&h.includes(f)&&n(`targets.${g}.name`,{message:`Duplicated name: ${f}`,type:"validate"})})};return a.jsxs(Zt,{title:ga.audiences,children:[a.jsx($,{children:s.map(({id:u},p)=>a.jsxs(T,{sx:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx(qa,{fieldName:`targets.${p}.name`,label:"Audience Name",required:!0,testId:`engagement-form:field:audience-name-${p}`,onValueChange:d,disabled:l}),!!p&&!l&&a.jsx(LP,{editing:!1,fieldName:`targets.${p}.active`,idPath:`targets.${p}.id`,onDelete:()=>o(p)})]},u))}),a.jsxs(re,{variant:"text",onClick:c,color:"secondary",disabled:l,children:[a.jsx(ca,{size:14})," Add Audience"]})]})},Sae=()=>a.jsx(T,{component:"form",children:a.jsxs($,{sx:{py:2,px:{xs:8,lg:20},minWidth:600,flexDirection:{xs:"column",lg:"row"},gap:3,justifyContent:"center"},children:[a.jsxs($,{sx:{width:{xs:"100%",lg:"67%"},maxWidth:{xs:"none",lg:700},gap:3},children:[a.jsx(xae,{}),a.jsx(gae,{}),a.jsx(vae,{}),a.jsx(Cae,{}),a.jsx(fae,{}),a.jsx(wae,{})]}),a.jsxs($,{sx:{width:{xs:"100%",lg:"33%"},maxWidth:{xs:"none",lg:350},gap:3},children:[a.jsx(mae,{}),a.jsx(yae,{})]})]})}),jae=()=>{const{dispatch:e,editing:t,onClose:n,onSubmit:r,open:s,state:i,isValidating:o}=yo(),{exitDialogOpen:l,nextLogoFile:c}=i,{getValues:d,reset:u,handleSubmit:p,formState:{isValid:h,isDirty:f,isSubmitting:g,dirtyFields:x}}=Hr(),b=t?"Edit Engagement":"Create Engagement",y=t?"Cancel Editing?":"Cancel New Engagement?",v=()=>{if(f){e({type:"exitDialogOpen",value:!0});return}n()},C=()=>{e({type:"exitDialogOpen",value:!1})},w=()=>{e({type:"exitDialogOpen",value:!1}),e({type:"nextLogoFile",value:null}),u(),n()},S=p(async()=>{try{await r({...d(),nextLogoFile:c},x),n()}catch(E){alert(E)}});return a.jsxs(yt,{"data-testid":"engagement-form:dialog",fullScreen:!0,open:s,children:[a.jsxs(vt,{variant:"h6",sx:{p:3,pt:4,"&.MuiTypography-h6":{fontSize:18,lineHeight:"22px"}},children:[b,a.jsx(Ie,{"aria-label":"Close engagement form","data-testid":"engagement-form:close:button",onClick:v,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})})]}),a.jsx(Ct,{sx:{pb:6.5,display:"flex",flexDirection:"column"},children:a.jsx(Sae,{})}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(re,{"data-testid":"engagement-form:cancel:button",onClick:v,sx:{maxWidth:200,m:2},variant:"outlined",color:"secondary",children:"Cancel"}),a.jsx(Dt,{"data-testid":"engagement-form:save:button",loading:g,onClick:S,disabled:!h||o,sx:{m:2,pl:2.5},variant:"contained",children:"Save Changes"})]}),a.jsx(mt,{bodyText:"You have unsaved data. If you leave the page, these changes will be lost.",handleClose:C,handleAccept:w,open:l,testId:"engagement-form:exit-confirm:dialog",title:y,acceptLabel:"Yes, Cancel"})]})},DE=U.number().min(1,{message:"Minimum 1"}).max(99,{message:"Maximum 99"}),_p=U.string().min(1,{message:"Required"}),kae=/^#(?:[\da-f]{6}|[\da-f]{8})$/i,Eae="Enter a hex color such as #ED1D24, or leave blank",_ae=U.string().refine(e=>e===""||kae.test(e),{message:Eae}),Tae=U.object({active:U.boolean(),mfa_flag:U.boolean(),brand_color:_ae,client_nice_id:_p,country:U.string(),currency:U.string(),date_format:U.string(),ds_license:DE,engagement_name:_p,geo_granularity:U.string(),kpi_license:DE,logo:U.string(),objectives:U.array(U.object({active:U.boolean().optional(),id:U.number().optional(),name:_p,value_per_conversion:U.number().nullable(),kpi_scalar:U.number().positive().nullable(),newObjective:U.boolean().optional()})),targets:U.array(U.object({active:U.boolean().optional(),id:U.number().optional(),name:_p,newTarget:U.boolean().optional()})),dataplatform_flag:U.boolean().nullable(),notes:U.string().nullable().optional()}),Iae={exitDialogOpen:!1,nextLogoFile:null},Dae=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,FP=({clientNiceId:e,editing:t=!1,engagement:n=null,onClose:r,onSubmit:s,targets:i,objectives:o,open:l})=>{const{userIsInternal:c}=gt(),[d,u]=m.useReducer(Dae,Iae),p=Xs({mode:"onChange",resolver:Zs(Tae),values:Qie({engagement:n,clientNiceId:e,editing:t,targets:i,objectives:o})}),{data:h=[]}=pC(null),[f,g]=m.useState(!1),x=m.useMemo(()=>{let b=h;return(!c||t)&&(b=h.filter(({niceId:y})=>y===e)),{dispatch:u,editing:t,onClose:r,onSubmit:s,open:l,state:d,isValidating:f,setIsValidating:g,clients:b,targets:i}},[h,c,t,r,s,l,d,f,e,i]);return a.jsx(MP.Provider,{value:x,children:a.jsx(Js,{...p,children:a.jsx(jae,{})})})},Aae=()=>{const e=ma(),{state:t,dispatch:n,tableRows:r,userEngagementsIds:s}=bo(),{editedAssigned:i,gridApiRef:o}=t,{username:l}=gt(),c=ct(),[d]=_A(),[u]=uC(),[p,h]=m.useState(!1),f=i.size,g=m.useMemo(()=>f===0,[f]),x=m.useMemo(()=>yM(f),[f]),b=()=>h(!1),y=()=>{o&&(o.current.updateRows(r),n({type:"clearEdits"}))},v=async()=>{const C=i.size?u({username:l,body:{engagements:kE(s,i)}}):null,w=$ie({editedAssigned:i,tableRows:r});i.size&&e("assignEngagement",{assignedEngagements:kE(s,i)}),await C,c()&&(i.size&&d(null),n({type:"clearEdits"}),o&&o.current.updateRows(w),h(!1))};return a.jsxs($,{direction:"row",justifyContent:"end",gap:2,mt:3,children:[a.jsx(be,{title:"Undo edits since last save.",children:a.jsx(T,{children:a.jsx(re,{"data-testid":"configuration:undo-changes:button",disabled:g,id:"configuration-undo-edits-button",onClick:y,variant:"outlined",children:"Undo Current Changes"})})}),a.jsx(re,{"data-testid":"configuration:save-changes:button",disabled:g,id:"configuration-save-edits-button",onClick:()=>h(!0),variant:"contained",children:"Save Changes"}),a.jsx(mt,{bodyText:x,handleClose:b,handleAccept:v,open:p,testId:"configuration:save-confirm:dialog",title:"Save Changes?",acceptLabel:"Save"})]})},Qd="__allClients",Mae={[Qd]:"All Clients"},Rae=[5,10,25,50],$P=800,zP=60,Nae=[{field:"client_name",sort:"asc"}],Oae={sorting:{sortModel:Nae},pagination:{paginationModel:{pageSize:10}}},Ix="You need to be assigned to this engagement before making any changes",Pae
182="You don't have the needed permissions to perform this action",Lae="Only inactive engagements can be deleted",Fae=({row:e})=>{const[t,n]=m.useState(null),{setEngagementToClone:r,setEngagementToDelete:s}=bo(),i=ma(),{userIsSuper:o}=gt(),l=!!t,c=()=>{n(null)},d=en(),u=()=>e.active||!e.assigned||!o,p=()=>o?e.active?Lae:e.assigned?null:Ix:Pae;return a.jsxs(T,{children:[a.jsx(Ie,{"aria-label":`Engagement actions for ${e.nice_id}`,"data-testid":`configuration:actions-menu:${e.nice_id}`,onClick:h=>{n(h.currentTarget)},sx:{p:.5},children:a.jsx(vl,{size:16})}),a.jsxs(dr,{id:"simple-menu",anchorEl:t,open:l,onClose:c,sx:{"> .MuiPaper-root":{width:"120px",borderRadius:"6px"}},children:[a.jsx(be,{title:e.assigned?null:Ix,children:a.jsx(T,{children:a.jsx(Se,{"data-testid":`configuration:actions:edit:${e.nice_id}`,disabled:!e.assigned,onClick:()=>{i("clickEditEngagement"),d("/settings/configuration/:id",{pathParams:{id:e.id},state:{openFormFromTable:!0}})},children:"Edit"})})}),a.jsx(be,{title:e.assigned?null:Ix,children:a.jsx(T,{children:a.jsx(Se,{"data-testid":`configuration:actions:copy:${e.nice_id}`,disabled:!e.assigned,onClick:()=>{i("clickCloneEngagement"),r(e),c()},children:"Copy"})})}),a.jsx(ar,{authorized:"Settings.Configuration.DeleteEngagement",children:a.jsx(be,{title:p(),children:a.jsx(T,{children:a.jsx(Se,{"data-testid":`configuration:actions:delete:${e.nice_id}`,disabled:u(),onClick:()=>{s(e),c()},children:"Delete"})})})})]})]})},$ae=({row:e})=>{const{id:t,assigned:n}=e,{handleUpdateAssigned:r,state:{editedAssigned:s}}=bo(),i=s.get(t)??n,o=i!==n,l=()=>{r({row:e,value:!i})};return a.jsx(Dn,{checked:i,onClick:l,sx:{"& .MuiSwitch-thumb":{backgroundColor:c=>o?c.palette.info.main:"default"}},color:o?"info":"primary"})},zae=({name:e,id:t})=>a.jsxs(T,{children:[a.jsx(I,{children:e}),a.jsxs(I,{color:"text.disabled",fontSize:"12px",fontWeight:"500",children:["ID ",t]})]}),Bae=({content:e,name:t,status:n})=>{const r=n?.name.includes("failed"),s=()=>{switch(n?.name){case"delete_failed":return"An error occurred while deleting the engagement";case"failed":return"An error occurred while copying the engagement";case"running":return"Copying engagement in process";default:return""}},i=a.jsxs(a.Fragment,{children:[a.jsx(I,{variant:"caption",children:`Engagement name: "${t}"`}),r&&a.jsxs(a.Fragment,{children:[a.jsx(St,{}),a.jsx(I,{variant:"caption",children:s()})]})]});return a.jsx(be,{placement:"bottom",title:i,children:a.jsx(T,{sx:{color:r?"error.main":"text.primary"},children:e})})},Uae=({src:e})=>a.jsx(T,{sx:{width:"100%",height:"100%",display:"flex",flexDirection:"column",justifyContent:"center",position:"relative","& > img":{objectFit:"contain",height:"100%",width:"100%"},...e?{}:{"&:after":{content:'""',width:0,height:0,borderStyle:"solid",borderWidth:"0 8px 8px 0",borderColor:"transparent grey transparent transparent",position:"absolute",right:10,top:20}}},children:e&&a.jsx("img",{src:e,alt:"logo",loading:"lazy"})}),Vae=({status:e})=>{const{name:t}=e??{},n=m.useMemo(()=>{switch(t){case"failed":case"delete_failed":return"Failed";case"running":return"Creating";case"deleting":return"Deleting";default:return"Ready"}},[t]),r=m.useMemo(()=>{switch(t){case"failed":case"delete_failed":return"error";case"deleting":case"running":return"warning";default:return"success"}},[t]);return a.jsx(ut,{label:n,color:r})},Ts={sortable:!0,type:"action",resizable:!0,flex:1},Wae=[{...Ts,field:"client_name",headerName:"Client",minWidth:150,renderCell:({row:{engagement:e,client_name:t}})=>a.jsx(Bae,{content:t,name:e.name,status:e.status})},{...Ts,field:"client_nice_id",headerName:"Client Nice Id"},{...Ts,field:"engagement",headerName:"Engagement",minWidth:250,valueGetter:({row:{engagement:e}})=>e.name,renderCell:({row:{engagement:e}})=>a.jsx(zae,{id:e.id,name:e.name})},{...Ts,field:"brand_logo",headerName:"Logo",minWidth:100,sortable:!1,renderCell:({value:e})=>a.jsx(Uae,{src:e})},{...Ts,field:"ds_license",headerName:"Data Source Licenses",minWidth:110},{...Ts,field:"kpi_license",headerName:"KPI Licenses",minWidth:110},{...Ts,field:"status",headerName:"Status",minWidth:130,resizable:!1,renderCell:({value:e})=>a.jsx(Vae,{status:e})},{...Ts,field:"assigned",headerName:"Assigned",minWidth:105,renderCell:({row:e})=>a.jsx($ae,{row:e})},{...Ts,field:"active",headerName:"Active",minWidth:130,resizable:!1,renderCell:({value:e=!1})=>a.jsx(DP,{active:e})},{...Ts,field:"actions",headerName:"Actions",minWidth:90,sortable:!1,renderCell:({row:e})=>a.jsx(Fae,{row:e})}],Hy=bs(Mn)(({theme:e})=>{const{text:t,background:n,border:r}=e.palette,{spacing:s}=e,i={backgroundColor:n.paper,color:t.default,":hover":{backgroundColor:n.brand.subtlest.hovered}};return{border:"none",minHeight:zP*2.5,[`.${xe.main}`]:{maxHeight:$P,height:"100%",borderRadius:"6px",border:"1px solid",borderColor:r.default},[`.${xe.cell}`]:{border:"none",paddingLeft:s(2),paddingRight:s(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1)}},[`.${xe.columnHeader}`]:{paddingLeft:s(2.5),paddingRight:s(1),":focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1.5)}},[`.${xe.columnHeaders}`]:{backgroundColor:n.tableHeader,border:"none"},[`.${xe.columnHeaderTitleContainerContent}`]:{textTransform:"uppercase",fontSize:12},[`.${xe.columnSeparator}`]:{display:"none"},[`.${xe.iconButtonContainer}`]:{paddingLeft:s(1.5)},[`.${xe.row}`]:{...i,cursor:"pointer"},[`.${xe.virtualScroller}`]:{width:"calc(100% + 2px)"}}});Hy.defaultProps={...Hy.defaultProps,columnHeaderHeight:40,disableColumnMenu:!0,disableColumnFilter:!0,disableRowSelectionOnClick:!0,pagination:!0,rowHeight:zP};const Hae=()=>{const{dispatch:e,loadingClients:t,loadingEngagements:n,tableRows:r,state:s,userIsInternal:i}=bo(),o=en(),{gridApiRef:l}=s,c=n||t,d=zn();m.useEffect(()=>{l||e({type:"gridApiRef",value:d})},[d,e,l]);const u=(p,h)=>{["active","assigned","actions"].includes(h)||o("/settings/configuration/:id",{pathParams:{id:p}})};return a.jsx(T,{sx:{width:"100%",maxHeight:$P,maxWidth:"2000px",display:"grid"},children:a.jsx(Hy,{apiRef:d,autoHeight:c,columns:Wae,columnVisibilityModel:{active:i,client_nice_id:!1,ds_license:i,kpi_license:i},initialState:Oae,loading:c,pageSizeOptions:Rae,rows:c?[]:r,slots:{loadingOverlay:Cs},onCellClick:({row:p,field:h})=>u(p.id,h)})})},qae=()=>{const{clientOptions:e,dispatch:t,loadingClients:n,onCloseDialog:r,onCreateClient:s,onOpenDialog:i,putEngagementLogo:o,state:l,updateSearchValue:c,updateSelectedClient:d,userIsSuper:u,engagementToClone:p,clients:h}=bo(),[f]=Q5(),{setRaiseConversationIcon:g}=jt(),x=ma(),{engagementFormOpen:b,selectedClient:y}=l,v=()=>{g(!0),x("clickCreateEngagement"),t({type:"engagementFormOpen",value:!0}),i()},C=()=>{g(!1),t({type:"engagementFormOpen",value:!1}),r()},w=async S=>{const{engagement_name:E}=S,{logo:k,nextLogoFile:j,client_nice_id:_,brand_color:D,...M}=S,{id:N}=h.find(({niceId:R})=>R===_)??{};if(!N)return;x("createEngagement",{engagement:S});const O=await f({...M,brand_color:RP(D),file_name:k,client_id:N});if("error"in O)throw new Error(`${String(O.error)}`);E&&j&&o(TC(E),j)};return a.jsxs(T,{"data-testid":"configuration:page:container",sx:{dis
182play:p?"none":"inline"},children:[a.jsxs($,{direction:"row",justifyContent:"space-between",pb:3,children:[a.jsx(Xt,{title:"Configuration"}),a.jsx(re,{"data-testid":"configuration:create-engagement:button",onClick:v,sx:{minWidth:200},variant:"contained",children:"Create New Engagement"})]}),a.jsx(Yie,{clientOptions:e,onCreateClient:s,loading:n,selectedClient:y,updateSearchValue:c,updateSelectedClient:d,userIsSuper:u}),a.jsx(Hae,{}),a.jsx(Aae,{}),a.jsx(FP,{clientNiceId:y===Qd?null:y,onClose:C,onSubmit:w,open:b,targets:[{newTarget:!0,name:""}]}),a.jsx(Kie,{})]})},BP={gridApiRef:void 0,selectedClient:Qd,editedAssigned:new Map,engagementFormOpen:!1},Gae=(e,t)=>{switch(t.type){case"editedAssigned":case"engagementFormOpen":case"gridApiRef":case"selectedClient":return{...e,[t.type]:t.value};case"clearEdits":return{...e,editedAssigned:BP.editedAssigned};default:return{...e}}},Yae=({clientName:e,clients:t,loadingClients:n,loadingEngagements:r,onCloseDialog:s,onCreateClient:i,onOpenDialog:o,putEngagementLogo:l,tableRows:c,userEngagementsIds:d,userIsInternal:u,userIsSuper:p,onDeleteEngagement:h})=>{const[f,g]=m.useReducer(Gae,BP),{gridApiRef:x,editedAssigned:b,selectedClient:y}=f,v=m.useMemo(()=>[...t].sort((M,N)=>M.name.localeCompare(N.name)).reduce((M,{name:N,niceId:O})=>({...M,[O]:N}),t.length===1?{}:{...Mae}),[t]);m.useEffect(()=>{const[M]=t;t.length===1&&M&&g({type:"selectedClient",value:M.niceId})},[g,t]);const C=m.useCallback(M=>{if(!x)return;const N=y===Qd,O=[{id:1,field:"client_nice_id",operator:N?"contains":"equals",value:N?M:y},{id:2,field:"engagement",operator:"contains",value:M}];x.current.setFilterModel({items:O,quickFilterExcludeHiddenColumns:!1,logicOperator:N?rl.Or:rl.And}),x.current.setPage(0)},[x,y]),w=m.useCallback(({value:M,row:N})=>{const O=new Map(b);O.has(N.id)?O.delete(N.id):O.set(N.id,M),g({type:"editedAssigned",value:O})},[b]),S=m.useCallback(M=>{if(g({type:"selectedClient",value:M}),!x)return;const N=[];M!==Qd&&N.push({id:1,field:"client_nice_id",operator:"equals",value:M}),x.current.setFilterModel({items:N,quickFilterExcludeHiddenColumns:!1}),x.current.setPage(0)},[g,x]),[E,k]=m.useState(null),[j,_]=m.useState(null),D=m.useMemo(()=>({dispatch:g,clientName:e,clients:t,clientOptions:v,handleUpdateAssigned:w,loadingClients:n,loadingEngagements:r,onCloseDialog:s,onCreateClient:i,onOpenDialog:o,putEngagementLogo:l,tableRows:c,updateSearchValue:C,updateSelectedClient:S,userEngagementsIds:d,userIsInternal:u,userIsSuper:p,state:f,engagementToClone:E,setEngagementToClone:k,engagementToDelete:j,setEngagementToDelete:_,onDeleteEngagement:h}),[e,t,v,w,n,r,s,i,o,l,c,C,S,d,u,p,f,E,k,j,_,h]);return a.jsxs(_P.Provider,{value:D,children:[E&&a.jsx(Lie,{}),a.jsx(qae,{})]})},Kae=3e4,Qae=["running","deleting"],Jae=()=>{const{userIsInternal:e,userIsSuper:t}=gt(),{clientName:n,clientId:r,engagementId:s}=pe(),{setRaiseConversationIcon:i}=jt(),[o]=Sm(),[l]=J5(),[c]=X5(),{data:d=[],isLoading:u}=pC(null),{data:p=[],isLoading:h}=Nd({body:e?{}:{client_id:r}}),f=m.useMemo(()=>p?.filter(({status:E})=>Qae.includes(E?.name??"")).map(({id:E})=>E),[p]);Z5({engagements:f,bodyCacheArgs:e?{}:{client_id:r}},{skip:!f.length,pollingInterval:Kae});const{userEngagements:g}=yu(s),x=m.useMemo(()=>g.map(E=>E.engagement_id).reduce((E,k)=>E.set(k,!0),new Map),[g]),b=m.useMemo(()=>Fie({clients:d,engagements:p,userEngagementsIds:x}),[d,p,x]),y=async E=>l(E).unwrap(),v=async E=>c(E).unwrap(),C=()=>{i(!1)},w=()=>{i(!0)},S=(E,k)=>{const j=`${hs.logoAssetsUrl}/${E}/${k.name}`,_={"Content-Type":`${k.type}`,"x-amz-acl":"bucket-owner-full-control"};o({url:j,method:"put",headers:_,data:k})};return a.jsx(Yae,{clientName:n,clients:d,loadingClients:u,loadingEngagements:h,onCloseDialog:C,onCreateClient:y,onOpenDialog:w,putEngagementLogo:S,tableRows:b,userEngagementsIds:x,userIsInternal:e,userIsSuper:t,onDeleteEngagement:v})},ks="calc(100vw - 392px)",UP=m.createContext(null),Xae=()=>m.useContext(UP),Zae=({onClick:e})=>a.jsxs(T,{sx:{display:"flex",mb:"30px",pt:4,alignItems:"center"},children:[a.jsx(I,{id:"reporting-attribution-generating-csv",sx:{mr:"30px",fontWeight:"bold"},children:"Your CSV file is being generated"}),a.jsx(re,{id:"reporting-attribution-link-generate-new-csv",onClick:e,variant:"contained",children:"Generate new CSV"})]}),eoe=e=>e.length?[...new Set(e)].sort((t,n)=>t.kpiName.localeCompare(n.kpiName)):[],toe=(e,t)=>{if(!e.length||!t)return{minDate:void 0,maxDate:void 0};const n=e.filter(i=>i.kpiNiceId===t),r=n.map(i=>i.minDate).reduce((i,o)=>i<o?i:o,"9999-99-99"),s=n.map(i=>i.maxDate).reduce((i,o)=>i>o?i:o,"");return{minDate:Z(r),maxDate:Z(s)}},noe={display:"flex",flexDirection:"column",width:ks,minWidth:700},roe=()=>{const{handleKpiOnChange:e,handleClickDownloadCSV:t,isLoading:n,attributionMeta:r,state:s,dispatch:i}=Xae(),{minDate:o,maxDate:l,selectedDates:c,selectedKpi:d,generatedCsv:u}=s,[p,h]=m.useState(!1),f=ct(),g=d??"",[x,b]=c,y=b??Z(),v=x??Z(),C=O=>{i({type:"selectedDates",value:O})},w=m.useCallback(async()=>{h(!0),await t({endDate:y,startDate:v,selectedKpi:g}),f()&&(i({type:"generatedCsv",value:!0}),h(!1))},[f,i,t,y,v,g]),S=()=>{i({type:"generatedCsv",value:!1})},E=m.useMemo(()=>r.length?eoe(r).map(O=>({name:O.kpiName,niceId:O.kpiNiceId})):[],[r]),k=!!r&&r.length>0,j=!n&&!k,_=n||!j,D=!!k&&!!g,M=!!g&&!!v&&!!y,N=a.jsxs(T,{sx:{display:"flex",flexDirection:"row",mb:"40px",pt:4,width:"100%",alignItems:{md:"center",xs:"normal"}},children:[j&&a.jsx(I,{sx:{mt:1,fontWeight:"bold"},children:"There is no attribution data for this engagement."}),a.jsxs($,{spacing:2,direction:"row",children:[_&&a.jsx(da,{hideTargetAudience:!0,isMetaLoading:n,kpiListOptions:E,dataLastDate:l,dataFirstDate:o,disableDatePicker:!D,selectedDateRange:c,selectedKpi:g,handleKpiOnChange:e,handleDatePickerOnChange:C}),_&&a.jsx(Nt,{animation:"wave",isLoading:n,children:a.jsx(Dt,{sx:{minWidth:135,maxHeight:40},id:"reporting-attribution-create-csv-button",loading:p,disabled:n||!M,onClick:w,variant:"contained",children:"Generate CSV"})})]})]});return a.jsxs(T,{sx:noe,children:[a.jsx(ho,{loading:n}),a.jsx(Xt,{title:"Attribution Export"}),a.jsxs(T,{sx:{pt:4},children:[a.jsx(Nt,{isLoading:n,children:a.jsxs($,{direction:"column",spacing:2,children:[a.jsx(I,{children:"Please note it can take up to 30 minutes to generate this CSV file."}),a.jsx(I,{children:"You will receive an email with a link to a CSV file when your file is completed."})]})}),u?a.jsx(Zae,{onClick:S}):N]})]})},soe={selectedKpi:null,selectedDates:[null,null],maxDate:void 0,minDate:void 0,generatedCsv:!1},ioe=(e,t)=>{switch(t.type){case"selectedDates":case"generatedCsv":return{...e,[t.type]:t.value};case"setNextKpi":return{...e,selectedKpi:t.value.nextKpi,minDate:t.value.minDate,maxDate:t.value.maxDate,selectedDates:[t.value.minDate||null,t.value.maxDate||null]};default:return{...e}}},aoe=({attributionMeta:e,handleClickDownloadCSV:t,isLoading:n})=>{const[r,s]=m.useReducer(ioe,soe),i=m.useCallback(c=>{const{minDate:d,maxDate:u}=toe(e,c);s({type:"setNextKpi",value:{nextKpi:c,minDate:d,maxDate:u}})},[e,s]),o=m.useMemo(()=>{const[c]=e;return c&&i(c.kpiNiceId),e},[i,e]),l=m.useMemo(()=>({state:r,dispatch:s,attributionMeta:o,handleClickDownloadCSV:t,handleKpiOnChange:i,isLoading:n}),[r,o,t,i,n]);return a.jsx(UP.Provider,{value:l,children:a.jsx(roe,{})})},ooe={csv:"Attribution Report CSV"},loe=()=>pr({actionMap:ooe,eventName:"attribution"}),AE=[],coe=()=>{const e=loe(),{userEmail:t}=gt(),{engagementNiceId:n}=pe(),[r]=eV(),{data:{data:s=AE}={},isFetching:i}=tV(n),{activeKpiNiceIds:o,kpisLoading:l}=Ol(),c=m.useMemo(()=>!s.length||!o.size?AE:s.filter(u=>o.has(u.kpiNiceId)),[s,o]),d=m.useCallback(async({selectedKpi:u,endDate:p,startDate:h})=>{const f=p.format("YYYY-MM-DD"),g=h.format("YYYY-MM-DD");
182e("csv",{kpiNiceId:u,emailAddress:t,endDate:f,startDate:g}),await r({end_date:f,engagement_nice_id:n,kpi_nice_id:u,start_date:g,email_address:t})},[e,t,n,r]);return a.jsx(aoe,{handleClickDownloadCSV:d,isLoading:i||l,attributionMeta:c})},doe=["attribution","contribution"],uoe=3500,V0=25,poe=["cost","impressions","clicks","conversions","cost_per_conversion"],hoe=["cost","impressions","clicks","conversions","roas","cost_per_conversion"],Au="gl_type_name",foe=e=>e.find(n=>n.value===Au)??e[0],moe=[{field:Au,sort:"asc"}],goe=["day","week","month","year","quarter"],xoe={">":"Greater than",">=":"Greater than or equal to","<":"Less than","<=":"Less than or equal to"},VP={minWidth:135,maxWidth:135,height:40},Ls={activeControlChanges:!1,createdReport:!1,filterOptions:[],generatedCsv:!1,initialMetaSelection:void 0,limit:V0,maxDate:void 0,minDate:void 0,offset:0,pivotTableRef:null,searchColumns:[],searchText:void 0,selectedColumns:[{column:Au,header:"Media Type"}],selectedBrand:{name:"",niceId:""},selectedKpi:void 0,selectedDates:[null,null],selectedTarget:void 0,valuePerConversion:null,kpiScalar:null},boe={csv:"Download CSV",report:"Create Report"},yoe=()=>pr({actionMap:boe,eventName:"reporting"}),voe=(e=!1,t=[])=>{const r=foe(t)?.value??Au;return{rowsPerPage:V0,selectedNumberFields:[...e?hoe:poe],selectedPivots:[r],sortModel:[{field:r,sort:"asc"}]}},kd=(e,t,n)=>{if(!t)return e;const r={...e},{createdReport:s,generatedCsv:i,offset:o,filterOptions:l,searchColumns:c}=Ls,{createdReport:d,filterOptions:u,generatedCsv:p,offset:h,selectedBrand:f,searchColumns:g,selectedTarget:x}=r,{brandName:b,brandNiceId:y,kpiNiceId:v,targetNiceId:C,earliestEventDate:w,latestEventDate:S}=t,E=Z(w),k=Z(S);d&&(r.createdReport=s),u.length&&(r.filterOptions=l),g.length&&(r.searchColumns=c),p&&(r.generatedCsv=i),h!==o&&(r.offset=o),f.niceId!==y&&(r.selectedBrand={name:b,niceId:y}),x!==C&&(r.selectedTarget=C),r.minDate=E,r.maxDate=k;const j=k.subtract(2,"month").startOf("month");r.selectedDates=[j.isBefore(E)?E:j,k],r.selectedKpi=v;const _=n?.kpis.find(D=>D.kpi_nice_id===v);return r.valuePerConversion=_?.value_per_conversion??null,r.kpiScalar=_?.kpi_scalar??null,r},Coe=(e,t)=>{const n={...e},{filterOptions:r,searchColumns:s,searchText:i,limit:o,offset:l,selectedColumns:c,sortModel:d}=n,{filterOptions:u,searchColumns:p,searchText:h,limit:f,offset:g,selectedColumns:x,sortModel:b}=t;return Kn(r,u)||(n.filterOptions=u),Kn(s,p)||(n.searchColumns=p),i!==h&&(n.searchText=h),o!==f&&(n.limit=f),l!==g&&(n.offset=g),Kn(c,x)||(n.selectedColumns=x),Kn(d,b)||(n.sortModel=b),n},woe=(e,t)=>{const{filterOptions:n,searchColumns:r,searchText:s,limit:i,offset:o,selectedColumns:l,sortModel:c}=e,{filterOptions:d,searchColumns:u,searchText:p,limit:h,offset:f,selectedColumns:g,sortModel:x}=t;return!Kn(n,d)||!Kn(r,u)||s!==p||i!==h||o!==f||!Kn(l,g)||!Kn(c,x)},ME=(e,t,n)=>{const{filterOptions:r,limit:s,offset:i,searchColumns:o,searchText:l="",selectedBrand:c,selectedColumns:d,selectedDates:u,selectedKpi:p="",selectedTarget:h="",sortModel:f=moe,valuePerConversion:g,kpiScalar:x}=n,[b,y]=u,v=y??Z(),C=b??Z(),{name:w,niceId:S}=c;return{report_table:e,brand_name:w,brand_nice_id:S,attribute_columns:d,engagement_nice_id:t,start_date:C.format("YYYY-MM-DD"),end_date:v.format("YYYY-MM-DD"),kpi_nice_id:p,target_nice_id:h,filter_options:r,current_page:i/s,rows_per_page:s,search_columns:o,search_text:l,sort_model:f,value_per_conversion:g,kpi_scalar:x}},RE=e=>({kpiNiceId:e.kpi_nice_id,targetNiceId:e.target_nice_id,endDate:e.end_date,startDate:e.start_date,reportTable:e.report_table}),NE=(e,t)=>e?.niceId.localeCompare(t?.niceId),OE=(e,t,n)=>e[n].localeCompare(t[n]),PE=(e,t)=>{const n=[...e],[r]=n.sort((o,l)=>OE(o,l,"targetNiceId")),s=t||r?.targetNiceId,[i]=n.filter(o=>o.targetNiceId===s).sort((o,l)=>OE(o,l,"kpiNiceId"));return i},Soe=(e,t)=>t.reduce((r,s)=>{const i=e.find(o=>o.field===s);return i?(r.push({column:i.field,header:i.headerName||""}),r):(We(`${s} :: column not found, skipping`),r)},[]),joe=(e,t)=>{const{filterModelItems:n,limit:r,offset:s,search:i,selectedPivots:o,sortModel:l}=e,c=o?.length?o:[Au],d=[],u=[];
182n.forEach(f=>{const{field:g,value:x,operator:b}=f;b&&Tn(XD,b)?d.push({column:g,number:x,type:xoe[b]}):b&&Tn(Za,b)&&u.push({column:g,value:x,type:b})});const p=Soe(t,c);return{filterOptions:d,limit:r,offset:s,searchColumns:u,searchText:i,selectedColumns:p,sortModel:l}},koe=(e,t)=>{switch(t.type){case"activeControlChanges":case"createdReport":case"generatedCsv":case"pivotTableRef":case"searchText":case"selectedDates":return{...e,[t.type]:t.value};case"initialMetaSelection":return{...e,[t.type]:t.value,activeControlChanges:!1};case"setNextState":return{...e,...t.value,activeControlChanges:!0};case"setArguments":return{...e,...Coe(e,t.value)};case"selectedColumns":return{...e,[t.type]:t.value,createdReport:Ls.createdReport,generatedCsv:Ls.generatedCsv};case"resetDefaults":return{...e,...Ls,...kd(e,e.initialMetaSelection,t.value)};case"resetTableState":return{...e,createdReport:Ls.createdReport,generatedCsv:Ls.generatedCsv,offset:Ls.offset,filterOptions:Ls.filterOptions,searchColumns:Ls.searchColumns};default:return{...e}}},WP=m.createContext(null),tg=()=>m.useContext(WP),Eoe=()=>{const{debounceFetchCallback:e,dispatch:t,handleDatePickerOnChange:n,handleFetchReportingData:r,handleKpiOnChange:s,handleTargetAudienceOnChange:i,handleChangeTableType:o,isLoadingData:l,isLoadingMeta:c,mlConfig:d,reportingMeta:u,resetFirstRun:p,state:h,tableTypeSelected:f}=tg(),{activeControlChanges:g,initialMetaSelection:x,pivotTableRef:b,maxDate:y,minDate:v,selectedDates:C,selectedKpi:w,selectedTarget:S}=h,E=w??"",k=S??"",[j,_]=m.useState(!1),D=H=>{if(o(H),!b?.current)return;const{dispatch:V,state:G}=b.current;V({type:"currentPage",value:0}),G.filterModel.items.length&&V({type:"filterModel",value:{items:[]}})},M=()=>{if(p(),t({type:"resetDefaults",value:d}),r(kd(h,x,d)),!b?.current)return;const{dispatch:H}=b.current;H({type:"resetDefaults"})},N=H=>{n(H),g||t({type:"activeControlChanges",value:!g})},O=m.useCallback(()=>{g&&(r(h),t({type:"activeControlChanges",value:!g}))},[g,t,r,h]);m.useEffect(()=>{j&&(O(),_(!1))},[j,O]);const R=()=>{_(!0)},L=()=>{g&&e.cancel()},P=m.useCallback(H=>{s(k,H)},[k,s]),F=m.useMemo(()=>u.length?u.filter(V=>V.targetNiceId===k).map(V=>({name:V.kpiName,niceId:V.kpiNiceId})).sort(NE):[],[u,k]),z=m.useMemo(()=>u.length?u.map(H=>({name:H.targetName,niceId:H.targetNiceId})).sort(NE):[],[u]),B=!!u&&u.length>0,W=c||l;return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",my:4,width:"100%",alignItems:{md:"left",xs:"normal"}},children:[a.jsxs($,{mb:4,direction:{md:"row",xs:"column"},spacing:2,justifyContent:"space-between",children:[a.jsx(Mm,{disabled:W,isLoading:c,onChange:D,testId:"reporting:table-type:toggle",value:f}),!c&&!B?a.jsx(I,{sx:{mt:1,fontWeight:"bold",alignSelf:"center"},children:"There is no reporting data for this engagement."}):null,a.jsx(Nt,{isLoading:c,children:a.jsx(re,{"aria-label":"Reset all filters",color:"secondary",size:"small","data-testid":"reporting:reset-filters:button",disabled:W,onClick:M,sx:{...VP,padding:0,margin:0},variant:"text",children:"Reset All Filters"})})]}),a.jsx(da,{dataFirstDate:v,dataLastDate:y,disableDatePicker:!B,handleDatePickerOnChange:N,handleDatePickerOnClose:R,handleDatePickerOnOpen:L,handleKpiOnChange:P,handleTargetAudienceOnChange:i,isMetaLoading:c,isDataLoading:l,kpiListOptions:F,selectedDateRange:C,selectedKpi:E,selectedTargetAudience:k,targetAudienceListOptions:z,testId:"reporting:filters"})]})},_oe=()=>{const{dispatch:e,handleClickDownloadCSV:t,isLoadingData:n,isLoadingMeta:r,reportingData:s,state:i}=tg(),{generatedCsv:o}=i,l=ct(),[c,d]=m.useState(!1),u=async()=>{e({type:"generatedCsv",value:!0}),await t(i),l()&&d(!1)};m.useEffect(()=>{o&&setTimeout(()=>{l()&&e({type:"generatedCsv",value:!1})},3e4)},[o,e,l]);const p=!n&&!!s&&s.length>0,h=r||n;return a.jsxs($,{direction:"row",spacing:2,children:[a.jsx(Nt,{isLoading:r,children:a.jsx(be,{title:o?"File creation in progress...":"",children:a.jsx(T,{children:a.jsx(re,{"aria-label":"Download CSV",sx:VP,color:"secondary",variant:"outlined","data-testid":"reporting:download-csv:button",disabled:h||!p||o,onClick:()=>d(!0),startIcon:a.jsx(bl,{size:16}),size:"small",children:"Download"})})})}),a.jsx(mt,{acceptLabel:"Ok",bodyText:"You will receive an email with a link to a CSV file when your file is completed.",handleClose:()=>d(!1),handleAccept:()=>u(),open:c,testId:"reporting:csv-dialog",title:"Request a CSV"})]})},W0=()=>m.useRef(),HP=m.createContext(null),xa=()=>m.useContext(HP),Toe=({columns:e,selectedNumberFields:t,selectedPivots:n,sortModel:r})=>{const s=e.filter(({alwaysVisible:o})=>!!o).map(({field:o})=>o);return r.filter(({field:o})=>n.includes(o)||t.includes(o)||s.includes(o))},Ioe=({column:e,selectedNumberFields:t,selectedPivots:n})=>{const{alwaysVisible:r=!1,field:s,filterable:i=!0,disableColumnMenu:o=!1}=e;let l=!0;return(!i||o||!r&&!t.includes(s)&&!n.includes(s))&&(l=!1),l},Doe=({column:e,loading:t})=>
182t?!1:e.sortable??!0,Aoe=(e,t)=>{const n=[];return t.forEach(r=>{const s=e.find(i=>i.field===r);s&&n.push(s)}),n},Moe=(e,t)=>e.sort((n,r)=>t.indexOf(n.field)-t.indexOf(r.field)),qP=({columns:e,columnOrder:t=[],loading:n,selectedNumberFields:r,selectedPivots:s})=>{const i=e.map(o=>({...o,filterable:Ioe({column:o,selectedNumberFields:r,selectedPivots:s}),sortable:Doe({column:o,loading:n})}));return Moe(i,t)};function Roe({columns:e,selectedNumberFields:t,selectedPivots:n}){const r=e.reduce((s,{alwaysVisible:i,field:o})=>({...s,[o]:i}),{});return t.forEach(s=>{s in r&&(r[s]=!0)}),n.forEach(s=>{s in r&&(r[s]=!0)}),r}const Noe=(e,t)=>t?.selectedPivots??[e[0]?.value??""],Ooe=({columns:e,currentGetDataArgs:t,prevGetDataArgs:n,selectedNumberFields:r,selectedPivots:s})=>{let i=t.offset,o=!1;(t.search!==n.search||!Kn(t.filterModelItems,n.filterModelItems))&&(i=0,o=!0);const l=Toe({columns:e,sortModel:t.sortModel,selectedNumberFields:r,selectedPivots:s}),c=l.length!==t.sortModel.length,d={filterModelItems:t.filterModelItems,limit:t.limit,offset:i,search:t.search,selectedPivots:t.selectedPivots,sortModel:l};return{argsChanged:o||c||!Kn(d,n),nextOnGetDataArgs:d,offsetReset:o,sortModelChanged:c}},Poe=()=>{const{columns:e,columnVisibilityModel:t,dispatch:n,loading:r,onCloseColumnSelector:s,state:i}=xa(),{initialState:o,selectedPivots:l,selectedNumberFields:c}=i,d=m.useMemo(()=>qP({columns:e,loading:r,selectedNumberFields:c,selectedPivots:l}),[r,e,c,l]),u=m.useMemo(()=>d.filter(({customType:g})=>g==="pivot").map(({field:g,headerName:x})=>({label:x||g,value:g})),[d]),p=m.useMemo(()=>d.filter(({alwaysVisible:g,customType:x})=>!g&&x==="number").map(({field:g,headerName:x})=>({label:x||g,value:g})),[d]),h=g=>{const{value:x}=g.target,b=typeof x=="string"?x.split(","):x,y=Aoe(d,b),v=y.filter(({customType:w})=>w==="pivot").map(({field:w})=>w).sort(),C=y.filter(({customType:w})=>w==="number").map(({field:w})=>w);n({type:"selectedPivots",value:v}),n({type:"selectedNumberFields",value:C})},f=()=>{let g=l;l.length||(g=Noe(u,o),n({type:"selectedPivots",value:g})),s(g)};return a.jsx(Nt,{isLoading:r,children:a.jsx(Qe,{children:a.jsxs(tt,{"data-testid":"columnSelect",disabled:r,multiple:!0,onChange:h,onClose:f,renderValue:()=>a.jsxs($,{direction:"row",gap:1,sx:{color:r?"text.disabled":"text.secondary",alignItems:"center"},children:[a.jsx(po,{size:19}),a.jsx(I,{component:"span",sx:{lineHeight:"24px",height:24},children:"Columns"})]}),sx:{height:38,width:142},value:d.filter(({field:g})=>!!(t[g]??t[`${g}_name`])).map(({field:g})=>g),children:[!!p.length&&a.jsx(Nh,{children:"Dimensions"}),u.map(({label:g,value:x})=>a.jsxs(Se,{value:x,"data-testid":x,children:[a.jsx(et,{checked:!!(t[x]??t[`${x}_name`])}),a.jsx(Kt,{primary:g})]},x)),!!p.length&&a.jsx(Nh,{children:"Totals"}),!!p.length&&p.map(({label:g,value:x})=>a.jsxs(Se,{value:x,"data-testid":x,children:[a.jsx(et,{checked:!!t[x]}),a.jsx(Kt,{primary:g})]},x))]})})})},Gi={editableCellCursor:"editable-cell-cursor",rowExcluded:"row-excluded",rowLocked:"row-locked",rowPinned:"row-pinned"},H0=10,GP=[10,25,50,100],YP=15,q0=40,Mu=58,Loe=q0+Mu*H0+YP,Foe=q0+Mu*(H0+1)+YP,Tp={fontSize:12,fontWeight:500,letterSpacing:.5,lineHeight:"20px"},$oe=()=>{const{dispatch:e,getData:t,loading:n,state:r,totalRows:s}=xa(),{currentPage:i,rowsPerPage:o}=r,l=n||i===0,c=n||s>-1&&(i+1)*o>=s,d=async(p,h)=>{const f=h*o;t({offset:f}),e({type:"currentPage",value:h})},u=async p=>{const h=Number(p.target.value);if(h!==o){const f=i*o,g=Math.floor(f/h),x=g*h;t({limit:h,offset:x}),e({type:"rowsPerPage",value:h}),e({type:"currentPage",value:g})}};return a.jsx(Nt,{isLoading:n,sx:{float:"inline-end"},children:a.jsx(iB,{"data-testid":"pivot-table:pagination",backIconButtonProps:{disabled:l},component:"div",count:s,nextIconButtonProps:{disabled:c},onPageChange:d,onRowsPerPageChange:u,page:i,rowsPerPage:o,rowsPerPageOptions:GP,SelectProps:{disabled:n,sx:{mr:3,...Tp,".MuiSelect-select":{py:.5}},MenuProps:{sx:{".MuiTablePagination-menuItem":{...Tp}}}},sx:{".MuiTablePagination-selectLabel":{color:"text.secondary",...Tp},".MuiTablePagination-displayedRows":{color:"text.secondary",...Tp},".MuiTablePagination-actions":{ml:2}}})})},zoe=()=>{const e=ZD(),{dispatch:t,getData:n,loading:r,state:s}=xa(),{search:i}=s,o=eA(i,1e3),l=c=>{t({type:"search",value:c.target.value})};return m.useEffect(()=>{let c=!0;return c&&!e&&n(),()=>{c=!1}},[o]),a.jsx(Nt,{isLoading:r,children:a.jsx(Qe,{children:a.jsx(ys,{disabled:r,onChange:l,placeholder:"Search",inputProps:{"data-testid":"searchInput"},startAdornment:a.jsx(Bn,{position:"start",sx:{color:"text.disabled"},children:a.jsx(er,{})}),sx:{height:42},value:i})})})},Boe=e=>a.jsx(re,{...e,variant:"contained"}),Uoe=[rl.And],Voe=e=>{const{getData:t}=xa(),n=()=>{t()};return a.jsx(Bv,{onClickAway:n,children:a.jsx(Br,{sx:{p:2},children:a.jsx(rM,{logicOperators:Uoe,sx:{".MuiDataGrid-filterForm":{columnGap:2}
182,".MuiDataGrid-panelContent":{pb:1}},...e})})})},Woe=Mu-8,Hoe=()=>{const{totalsRow:e}=xa();return a.jsx($,{gap:1,sx:{pt:1},children:Array(e?11:10).fill(null).map((t,n)=>a.jsx(fe,{height:Woe,variant:"rounded"},n))})},ng=()=>a.jsx(T,{sx:{display:"flex",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"},children:a.jsx(I,{children:"No data available."})}),qy=rt(Mn)(({theme:e,pinnedRows:t})=>{const{background:n,grey:r,primary:s,text:i}=e.palette,{spacing:o}=e,l=t&&t.bottom?t.bottom.length>0:!1,c={backgroundColor:n.paper,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.paper}};return{border:"none",".MuiDataGrid-cell":{border:"none",paddingLeft:o(2),paddingRight:o(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&.MuiDataGrid-cell--editing":{paddingLeft:o(2),paddingRight:o(1),boxShadow:"none",":focus-within":{outline:"none"}},[`&.${Gi.editableCellCursor}:hover`]:{cursor:"pointer"}},".MuiDataGrid-cellCheckbox":{paddingLeft:o(1)},".MuiDataGrid-columnHeader":{":focus-within":{outline:"none"}},".MuiDataGrid-columnHeadersInner":{".MuiDataGrid-columnHeader:not(:first-of-type)":{paddingLeft:o(2),paddingRight:o(2)}},".MuiDataGrid-columnHeaders":{backgroundColor:n.tableHeader,border:"none",borderRadius:o(1)},".MuiDataGrid-columnHeaderTitleContainerContent":{fontSize:12,height:18,textTransform:"uppercase"},".MuiDataGrid-columnSeparator":{color:r[400],":hover":{color:r[400]}},".MuiDataGrid-row":{...c,[`&.${Gi.rowExcluded}`]:{background:e.palette.mode==="dark"?`repeating-linear-gradient(-60deg, ${n.paper}, ${n.disabled} 16px)`:`repeating-linear-gradient(-60deg, ${n.paper}, ${s.lightest} 16px)`,color:i.disabled},[`&.${Gi.rowLocked}`]:{color:i.disabled},[`&.${Gi.rowPinned}`]:{borderBottomLeftRadius:o(1),borderBottomRightRadius:o(1)}},".MuiDataGrid-virtualScrollerContent":{minHeight:"auto !important"},".MuiDataGrid-pinnedRows":{boxShadow:"none",borderBottomLeftRadius:o(1),borderBottomRightRadius:o(1)},".MuiDataGrid-row--lastVisible":{borderBottomLeftRadius:l?"":o(1),borderBottomRightRadius:l?"":o(1)},".MuiDataGrid-row:nth-of-type(even)":{...c}}});qy.defaultProps={...qy.defaultProps,columnHeaderHeight:q0,disableColumnPinning:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,hideFooter:!0,rowHeight:Mu};const KP=e=>!e.row.exclude&&!e.row.locked&&dU.includes(e.field),qoe=e=>KP(e)?Gi.editableCellCursor:"",Goe=e=>e.row.exclude?Gi.rowExcluded:e.row.locked?Gi.rowLocked:e.row.pinned?Gi.rowPinned:"",Yoe=()=>{const[e,t]=m.useState({}),{BatchEdit:n,columns:r,columnVisibilityModel:s,data:i,dispatch:o,getData:l,gridApiRef:c,loading:d,onEditRows:u,state:p,totalsRow:h}=xa(),{selectedRows:f,sortModel:g,filterModel:x,columnOrder:b,selectedPivots:y,selectedNumberFields:v}=p,C=m.useMemo(()=>qP({columns:r,columnOrder:b,loading:d,selectedNumberFields:v,selectedPivots:y}),[b,d,r,v,y]),w=m.useMemo(()=>f.map(({id:R})=>R),[f]),S={bottom:h?[h]:[]},E=!!n;m.useEffect(()=>{const R=()=>{c.current&&c.current.resize()};return window.addEventListener("resize",R),()=>{window.removeEventListener("resize",R)}},[c]);const k=R=>{o({type:"sortModel",value:R})},j=m.useCallback((R,L)=>Kn(R,L)?L:(u([{...R}]),R),[u]),_=R=>{const L=R.map(P=>c.current.getRow(P));o({type:"selectedRows",value:L})},D=m.useCallback(R=>{o({type:"filterModel",value:R})},[o]),M=({oldIndex:R,targetIndex:L})=>{const P=[...b];if(P.length){const F=P.splice(R-(E?1:0),1)[0]||"";P.splice(L-(E?1:0),0,F),o({type:"columnOrder",value:P})}},N=(R,L)=>{R.isEditable&&(L.target instanceof Node&&L.target.nodeType===1&&!L.currentTarget.contains(L.target)||t(P=>({...Object.keys(P).reduce((F,z)=>({...F,[z]:Object.keys(P[z]||{}).reduce((B,W)=>({...B,[W]:{mode:Dg.View}}),{})}),{}),[R.id]:{...Object.keys(P[R.id]||{}).reduce((F,z)=>({...F,[z]:{mode:Dg.View}}),{}),[R.field]:{mode:Dg.Edit}}})))},O=R=>{t(R)};return m.useEffect(()=>{!x.items.length&&!d&&l()},[x.items.length]),a.jsx(T,{sx:{height:h?Foe:Loe,overflow:"hidden",width:"100%"},children:a.jsx(qy,{apiRef:c,checkboxSelection:E,cellModesModel:e,columns:C,columnVisibilityModel:s,disableColumnFilter:d,disableColumnMenu:d,filterMode:"server",filterModel:x,getCellClassName:qoe,getRowClassName:Goe,isCellEditable:n?KP:void 0,loading:d,onCellClick:N,onCellModesModelChange:O,onColumnOrderChange:M,onFilterModelChange:D,onRowSelectionModelChange:_,onSortModelChange:k,processRowUpdate:j,rows:d?[]:i,pinnedRows:d||i.length===0?{}:S,rowSelectionModel:w,slots:{baseButton:Boe,filterPanel:Voe,loadingOverlay:Hoe,noRowsOverlay:ng},sortingMode:"server",sortModel:g})})},Dx={flexDirection:"row",alignItems:"center"},Koe=()=>{const{BatchEdit:e,controlsChildren:t,loading:n,state:r}=xa(),{selectedRows:s}=r,i=!!e&&s.length>1;
182return a.jsxs(T,{sx:{overflow:"hidden",width:"100%"},children:[a.jsx($,{sx:{...Dx,justifyContent:"space-between",mb:3,height:40},children:i?a.jsx(e,{disabled:n}):a.jsxs($,{sx:{...Dx,justifyContent:"space-between",width:"100%"},children:[a.jsxs($,{sx:{...Dx,gap:1},children:[a.jsx(Poe,{}),a.jsx(zoe,{})]}),t]})}),a.jsxs(T,{sx:{overflow:"hidden",width:"100%"},children:[a.jsx(Yoe,{}),a.jsx($oe,{})]})]})},QP=(e={})=>{const{rowsPerPage:t=10,selectedNumberFields:n=[],selectedPivots:r=[],sortModel:s=[]}=e;return{columnOrder:[],currentPage:0,filterModel:{items:[]},initialState:e,rowsPerPage:t,search:"",selectedNumberFields:[...n],selectedPivots:[...r],selectedRows:[],sortModel:[...s]}},Qoe=(e,t)=>{switch(t.type){case"columnOrder":case"currentPage":case"filterModel":case"rowsPerPage":case"search":case"selectedNumberFields":case"selectedPivots":case"selectedRows":case"sortModel":return{...e,[t.type]:t.value};case"resetDefaults":return{...e,...QP(e.initialState)};default:return e}},Joe=({columns:e,dispatch:t,onChangePivots:n,onGetData:r,state:s})=>{const i=ct(),{currentPage:o,filterModel:l,rowsPerPage:c,search:d,selectedNumberFields:u,selectedPivots:p,sortModel:h}=s,[f,g]=m.useState(p),[x,b]=m.useState({filterModelItems:l.items.filter(({value:S})=>!!S),limit:c,offset:o*c,search:d,selectedPivots:p,sortModel:h}),y=eA(h,1e3),v=o*c,C=m.useCallback(async({force:S=!1,limit:E=c,nextSortModel:k=h,offset:j=v}={})=>{if(!i())return;const _={filterModelItems:l.items.filter(({value:R})=>!!R),limit:E,offset:j,search:d,selectedPivots:p,sortModel:k},{argsChanged:D,nextOnGetDataArgs:M,offsetReset:N,sortModelChanged:O}=Ooe({columns:e,currentGetDataArgs:_,prevGetDataArgs:x,selectedNumberFields:u,selectedPivots:p});if(S||D){N&&t({type:"currentPage",value:0}),O&&t({type:"sortModel",value:M.sortModel}),b(M);const{error:R}=await r(M);i()&&R&&b(x)}},[e,v,t,l.items,i,r,x,c,d,u,p,h]),w=m.useCallback(async S=>{if(S.length&&!Kn(f,S)){t({type:"currentPage",value:0});const{error:E}=await n(S);i()&&(E||(g(S),C({force:!0,offset:0})))}},[t,C,i,n,f]);return m.useEffect(()=>{const S=x.sortModel;Kn(S,y)||C({nextSortModel:y})},[y]),{getData:C,onCloseColumnSelector:w}},G0=({BatchEdit:e,columns:t,controlsChildren:n,data:r,initialState:s,loading:i,onChangePivots:o,onEditRows:l=()=>{},onGetData:c,pivotOptions:d,pivotTableRef:u,totalRows:p,totalsRow:h})=>{const f=zn(),[g,x]=m.useReducer(Qoe,QP(s)),{columnOrder:b,selectedNumberFields:y,selectedPivots:v}=g,C=m.useMemo(()=>Roe({columns:t,selectedNumberFields:y,selectedPivots:v}),[t,y,v]);m.useEffect(()=>{b.length!==t.length&&x({type:"columnOrder",value:t.map(k=>k.field)})},[b.length,t,d]),m.useEffect(()=>{if(!d.length)return;const k=new Set(d.map(_=>_.value));if(v.some(_=>!k.has(_))){const _=d[0]?.value??"",D=v.map(N=>k.has(N)?N:_).filter(Boolean),M=[...new Set(D)];x({type:"selectedPivots",value:M.length?M:[_]})}},[d,v]);const{getData:w,onCloseColumnSelector:S}=Joe({columns:t,dispatch:x,onChangePivots:o,onGetData:c,state:g});m.useImperativeHandle(u,()=>({dispatch:x,state:g}),[g]);const E=m.useMemo(()=>({BatchEdit:e,columns:t,columnVisibilityModel:C,controlsChildren:n,data:r,dispatch:x,getData:w,gridApiRef:f,loading:i,onCloseColumnSelector:S,onEditRows:l,pivotOptions:d,state:g,totalRows:p,totalsRow:h}),[e,t,C,n,r,x,w,f,i,S,l,d,g,p,h]);return a.jsx(HP.Provider,{value:E,children:a.jsx(Koe,{})})},Xoe=({columns:e,dispatch:t,handleFetchReportingData:n,state:r})=>{const s=ct(),i=m.useCallback(async()=>({error:!1}),[]),o=m.useCallback(async l=>{const c=joe(l,e);return t({type:"setArguments",value:c}),woe(r,c)?(t({type:"generatedCsv",value:!1}),await n({...r,...c}),s()?{error:!1}:{error:!0}):{error:!1}},[e,t,n,s,r]);return{handleChangePivots:i,handleGetTableData:o}},Y0={alwaysVisible:!1,customType:"pivot",flex:1,minWidth:140,filterOperators:Em().filter(e=>Za.includes(e.value))},Ao={...Y0,customType:"number",minWidth:150,type:"number",filterOperators:_m().filter(e=>XD.includes(e.value))},Zoe={...Y0,minWidth:120,filterable:!1,filterOperators:void 0},LE=[{...Ao,field:"cost",headerName:"Spend",renderCell:e=>a.jsx(ft,{isCurrency:!0,value:e.value,TypographyProps:{sx:{fontWeight:e.rowNode.type==="pinnedRow"?"bold":"normal "}}})},{...Ao,field:"impressions",headerName:"Impressions",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e.value,TypographyProps:{sx:{fontWeight:e.rowNode.type==="pinnedRow"?"bold":"normal "}}})},{...Ao,field:"clicks",headerName:"Clicks",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e.value,TypographyProps:{sx:{fontWeight:e.rowNode.type==="pinnedRow"?"bold":"normal "}}})},{...Ao,field:"conversions",headerName:"Conversions",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e.value,TypographyProps:{sx:{fontWeight:e.rowNode.type==="pinnedRow"?"bold":"normal "}}})},{...Ao,field:"roas",headerName:"ROAS",renderCell:e=>a.jsx(ft,{isPercent:!0,value:e.value,TypographyProps:{sx:{fontWeight:e.rowNode.type==="pinnedRow"?"bold":"normal "}}})},{...Ao,field:"cost_per_conversion",headerName:"Spend Per Conversion",renderCell:e=>a.jsx(ft,{isCurrency:!0,value:e.value,TypographyProps:{sx:{fontWeight:e.rowNode.type==="pinnedRow"?"bold":"normal "}}})}],ele=e=>({...Tn(goe,e.value)?Zoe:Y0,field:e.value,headerName:e.label,renderCell:n=>{const r=n.api.getColumnIndex(n.field);return n.rowNode.type==="pinnedRow"&&r===0?a.jsx(I,{sx:{fontWeight:"bold"},children:"Report Total"}):a.jsx(I,{children:n.value})}}),tle=({hideROAS:e,pivotOptions:t})=>{const n=t.map(s=>
182ele(s)),r=e?LE.filter(s=>s.headerName!=="ROAS"):LE;return[...n,...r]},nle=[{label:"Account ID",value:"account_id"},{label:"Account Name",value:"account_name"},{label:"Ad Group ID",value:"adgroup_id"},{label:"Ad Group Name",value:"adgroup_name"},{label:"Campaign ID",value:"campaign_id"},{label:"Campaign Name",value:"campaign_name"},{label:"Country",value:"gl_country_name"},{label:"Creative Message",value:"creative_message"},{label:"Creative Name",value:"creative_name"},{label:"Data Source",value:"datasource_name"},{label:"KPI Market",value:"kpi_market"},{label:"Media Market",value:"gl_market_name"},{label:"Media Type",value:"gl_type_name"},{label:"Placement ID",value:"placement_id"},{label:"Placement Name",value:"placement_name"},{label:"Platform",value:"gl_platform_name"},{label:"Program",value:"gl_program_name"},{label:"Tactic",value:"gl_tactic_name"},{label:"Vehicle",value:"gl_vehicle_name"},{label:"Vendor",value:"vendor_nice_id"},{label:"Day",value:"day"},{label:"Week",value:"week"},{label:"Month",value:"month"},{label:"Year",value:"year"},{label:"Quarter",value:"quarter"}],rle=()=>{const e=yn({authorized:"ROAS"}),{dispatch:t,handleFetchReportingData:n,state:r,totalRowCount:s,isLoadingData:i,isLoadingMeta:o,reportingData:l,reportingTotals:c}=tg(),{offset:d,pivotTableRef:u}=r,{pivotsLoading:p,pivotOptions:h}=O0(nle,{filterFn:({active:w})=>w}),f=W0(),g=m.useMemo(()=>tle({hideROAS:!e,pivotOptions:h}),[e,h]),x=m.useMemo(()=>l.map((w,S)=>({...w,id:S+d})),[l,d]),b=m.useMemo(()=>c?{...c,id:s+1,pinned:!0}:void 0,[c,s]),{handleChangePivots:y,handleGetTableData:v}=Xoe({columns:g,dispatch:t,handleFetchReportingData:n,state:r});m.useEffect(()=>{u||t({type:"pivotTableRef",value:f})},[u]);const C=m.useMemo(()=>voe(e,h),[e,h]);return a.jsx(G0,{columns:g,controlsChildren:a.jsx(_oe,{}),data:x,initialState:C,loading:i||o||p,onChangePivots:y,onGetData:v,pivotOptions:h,pivotTableRef:f,totalRows:s,totalsRow:b})},sle={display:"flex",flexDirection:"column",minWidth:700,width:"100%"},ile=()=>{const{isLoadingData:e,isLoadingMeta:t}=tg(),n=t||e;return a.jsxs(T,{"data-testid":"reporting:page:container",sx:sle,children:[a.jsx(ho,{loading:n,testId:"reporting:loading:bar"}),a.jsx(Xt,{testId:"reporting:page:header",title:"Media Reporting"}),a.jsx(Eoe,{}),a.jsx(rle,{})]})},ale=({handleChangeTableType:e,handleClickDownloadCSV:t,handleFetchReportingData:n,isLoadingData:r,isLoadingMeta:s,mlConfig:i,reportingData:o,reportingTotals:l,reportingMeta:c,resetFirstRun:d,tableTypeSelected:u,totalRowCount:p})=>{const[h,f]=m.useReducer(koe,Ls),{pivotTableRef:g}=h,x=m.useCallback(async D=>{await n(D),f({type:"activeControlChanges",value:!1})},[]),b=fs(x,uoe),y=m.useCallback(()=>{if(d(),f({type:"resetTableState"}),!g?.current)return;const{dispatch:D,state:M}=g.current;M.filterModel.items.length&&D({type:"filterModel",value:{items:[]}})},[d,f,g]),v=m.useCallback(D=>{y(),e(D)},[y,e]),C=m.useCallback(D=>{f({type:"searchText",value:D})},[f]),w=m.useCallback(D=>{f({type:"selectedDates",value:D}),y()},[y]),S=m.useCallback(D=>{f({type:"setNextState",value:D})},[]),E=m.useCallback((D,M)=>{const[N]=c.filter(O=>O.targetNiceId===D&&O.kpiNiceId===M);if(N){const O=kd(h,N,i);S(O),y(),b(O)}},[c,i,h,S,y,b]),k=m.useCallback(D=>{const M=PE(c,D);if(M){const N=kd(h,M,i);S(N),y(),b(N)}},[c,i,y,b,S,h]),j=m.useMemo(()=>{const D=PE(c);if(D){const M=kd(h,D,i);S(M),f({type:"initialMetaSelection",value:D}),setTimeout(()=>n(M),V0)}return c},[c,i]),_=m.useMemo(()=>({debounceFetchCallback:b,dispatch:f,handleChangeSearch:C,handleChangeTableType:v,handleClickDownloadCSV:t,handleDatePickerOnChange:w,handleFetchReportingData:n,handleKpiOnChange:E,handleTargetAudienceOnChange:k,isLoadingData:r,isLoadingMeta:s,mlConfig:i,reportingData:o,reportingTotals:l,reportingMeta:j,resetFirstRun:d,state:h,tableTypeSelected:u,totalRowCount:p}),[b,C,v,t,w,n,E,k,r,s,i,o,l,j,d,h,u,p]);return a.jsx(WP.Provider,{value:_,children:a.jsx(ile,{})})},ole={data:[],count:-1},lle={totals:null},FE={data:[]},cle=()=>{const e=yoe(),t=ct(),{engagementId:n,engagementNiceId:r}=pe(),s=yn({authorized:"ROAS"}),[i,o]=m.useState(!0),[l,c]=m.useState([]),[d,u]=m.useState([]),[p,h]=m.useState(""),{data:f=null,isFetching:g}=SA(n,{skip:!s}),[x,{data:{data:b,count:y}=ole,isFetching:v}]=nV(),[C,{data:{totals:w}=lle,isError:S,isFetching:E}]=rV(),[k]=sV(),[,j]=doe,[_,D]=m.useState(j),{data:{data:M}=FE,isFetching:N}=iV({engagement_nice_id:r,report_table:_}),{activeKpiNiceIds:O,kpisLoading:R}=Ol(),L=m.useMemo(()=>!M.length||!O.size?FE.data:M.filter(W=>O.has(W.kpiNiceId)),[M,O]),P=()=>{b.length&&o(!0)},F=async W=>{const H=JSON.stringify(W.filterOptions)!==JSON.stringify(l)||JSON.stringify(W.searchColumns)!==JSON.stringify(d),V=W.searchText!==p,G=ME(_,r,W);e("report",RE(G)),await x(G,!0),(i||H||V)&&t()&&(await C(G,!0),o(!1),c(W.filterOptions),u(W.
182searchColumns),h(W.searchText||""))},z=W=>{_!==W&&(D(W),P())},B=m.useCallback(async W=>{const H=ME(_,r,W);e("csv",RE(H)),await k(H)},[r,k,e,_]);return a.jsx(ale,{handleChangeTableType:z,handleClickDownloadCSV:B,handleFetchReportingData:F,isLoadingData:v||E,isLoadingMeta:N||g||R,mlConfig:f,reportingMeta:L,reportingData:b,reportingTotals:S?null:w,resetFirstRun:P,tableTypeSelected:_,totalRowCount:y})};m.createContext(null);m.createContext(null);const dle=U.object({deliveryMethod:U.literal("snowflake"),accountNumber:U.string(),name:U.string(),region:U.string(),dataFeeds:U.array(U.string())}),ule=U.object({deliveryMethod:U.literal("s3")}),ple=U.object({deliveryMethod:U.literal("api-key")}),hle=U.object({deliveryMethod:U.literal("sftp")});U.discriminatedUnion("deliveryMethod",[dle,ule,ple,hle]);const fle={create:"Create",delete:"Delete",view:"View"},mle=()=>pr({actionMap:fle,eventName:"dashboards"});var yc={},$E;function gle(){if($E)return yc;$E=1;var e=Pt();Object.defineProperty(yc,"__esModule",{value:!0}),yc.default=void 0;var t=e(Lt()),n=Ot();return yc.default=(0,t.default)((0,n.jsx)("path",{d:"M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8"}),"InfoOutlined"),yc}var xle=gle();const aa=dt(xle),ble=({open:e,handleCancel:t,handleCreate:n,setOpen:r,userIsInternal:s})=>{const i=ct(),[o,l]=m.useState(""),[c,d]=m.useState(""),[u,p]=m.useState(!1),[h,f]=m.useState(null),g=m.useCallback(async()=>{p(!0);const b=await n({analysisId:o,dashboardName:c});if(i()){if(p(!1),"error"in b){const{type:y,message:v}=b.error;switch(y){case"NOT_FOUND":f({type:"analysis",message:"Analysis ID not found"});break;case"ALREADY_EXISTS":f({type:"name",message:"Dashboard name already exists"});break;case"NETWORK_ERROR":f({type:"network",message:v});break;default:f({type:"generic",message:v});break}}else r(!1);p(!1)}},[o,c,n,i,r]);m.useEffect(()=>{l(""),d(""),f(null)},[e]);const x=a.jsxs($,{gap:2,p:2,pb:0,children:[a.jsx(De,{disabled:u||h?.type==="network",fullWidth:!0,InputProps:{startAdornment:a.jsx(Bn,{position:"start",children:a.jsx(be,{title:"Found in the url after 'analyses/'",children:a.jsx(aa,{color:"secondary"})})})},error:!!h&&h.type==="analysis",helperText:h?.type==="analysis"?h.message:" ",label:"Analysis Id",onChange:b=>{l(b.target.value),f(null)},required:!0,value:o}),a.jsx(De,{disabled:u||h?.type==="network",fullWidth:!0,InputProps:{startAdornment:a.jsx(Bn,{position:"start",children:a.jsx(be,{title:`Name must be unique${s?" per engagement":""}`,children:a.jsx(aa,{color:"secondary"})})})},error:!!h&&h.type==="name",helperText:h?.type==="name"?h.message:" ",label:"Dashboard Name",onChange:b=>{d(b.target.value),f(null)},required:!0,value:c}),h?.type==="network"||h?.type==="generic"?a.jsx(I,{color:"error",children:h.message}):a.jsx(T,{height:21})]});return a.jsx(mt,{acceptButtonProps:{disabled:!o||!c||u||!!h},acceptLabel:"Create",body:x,handleAccept:g,handleClose:t,open:e,resetLoadingAfterAccept:!0,title:"Create New Dashboard"})},JP=140,XP=400,yle=({dashboard:e,editEnabled:t,onClickDelete:n,onClickView:r})=>{const{palette:s}=Re();return a.jsx(Ve,{children:a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:"1fr auto",width:XP,height:JP},children:[a.jsx(be,{arrow:!0,enterDelay:500,enterNextDelay:500,title:`View ${e.name}`,children:a.jsxs(Mb,{onClick:()=>{r(e)},sx:{p:4,width:"100%",display:"grid",gridTemplateRows:"1fr 1fr",rowGap:3,justifyContent:"flex-start"},children:[a.jsx(I,{sx:{overflow:"hidden",textOverflow:"ellipsis",fontWeight:500,fontSize:"16px",whiteSpace:"nowrap"},children:e.name}),a.jsxs(I,{variant:"body2",color:"text.secondary",sx:{alignSelf:"center"},children:["Created at:"," ",a.jsx(I,{component:"span",variant:"subtitle1",children:Z(e.createdTime).format("ll")})]})]})}),t&&a.jsx(be,{arrow:!0,enterDelay:500,enterNextDelay:500,title:`Delete ${e.name}`,children:a.jsx(Mb,{onClick:()=>n(e),sx:{p:4},children:a.jsx(Xr,{color:s.icon.secondary})})})]})},e.dashboardId)},vle=({dashboards:e,editEnabled:t,handleCreateDashboard:n,handleDeleteDashboard:r,handleViewDashboard:s,loading:i,userIsInternal:o})=>{const[l,c]=m.useState(null),[d,u]=m.useState(!1),p=m.useCallback(async()=>{l&&(r(l),c(null))},[r,l]);let h;return i?h=Array.from({length:6},(f,g)=>a.jsx(fe,{variant:"rounded",height:JP,width:XP},g)):e.length===0?h=a.jsx(I,{variant:"subtitle1",color:"text.secondary",children:"No dashboards foun
182d"}):h=e.map(f=>a.jsx(yle,{dashboard:f,editEnabled:t,onClickDelete:c,onClickView:()=>s(f)},f.dashboardId)),a.jsxs($,{sx:{width:ks,minWidth:600,rowGap:4},children:[a.jsxs($,{sx:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",height:36},children:[a.jsx(Xt,{title:"Dashboards"}),t&&a.jsx(re,{variant:"contained",onClick:()=>{u(!0)},children:"Create New Dashboard"})]}),a.jsx(T,{sx:{display:"flex",gap:3,flexWrap:"wrap"},children:h}),a.jsx(Cl,{open:!!l,handleClose:()=>c(null),handleDelete:p,title:"Delete Dashboard",bodyText:`Are you sure you want to delete '${l?.name}'?`}),a.jsx(ble,{open:d,handleCancel:()=>u(!1),handleCreate:n,setOpen:u,userIsInternal:o})]})},Cle=()=>{const{userIsInternal:e}=gt(),{engagementNiceId:t}=pe(),n=mle(),r=en(),s=yn({authorized:"Visualize.Dashboards.Edit"}),{data:i=[],isFetching:o}=TA(t),[l]=aV(),[c]=oV(),d=m.useCallback(({analysisId:h,dashboardName:f})=>(n("create",{featurePath:"Visualize.Dashboards",analysisId:h,name:f}),l({analysisId:h,dashboardName:f,engagementNiceId:t})),[l,t,n]),u=m.useCallback(({dashboardId:h,name:f})=>(n("delete",{featurePath:"Visualize.Dashboards",dashboardId:h,name:f}),c({engagementNiceId:t,dashboardId:h})),[c,t,n]),p=m.useCallback(({dashboardId:h,name:f})=>{n("view",{featurePath:"Visualize.Dashboards",dashboardId:h,name:f}),r("/visualize/dashboards/:id",{pathParams:{id:h}})},[n,r]);return a.jsx(vle,{dashboards:i,editEnabled:s,handleCreateDashboard:d,handleDeleteDashboard:u,handleViewDashboard:p,loading:o,userIsInternal:e})};function zE(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function BE(e,t,n,r,s,i,o){try{var l=e[i](o),c=l.value}catch(d){return void n(d)}l.done?t(c):Promise.resolve(c).then(r,s)}function qe(e){return function(){var t=this,n=arguments;return new Promise((function(r,s){var i=e.apply(t,n);function o(c){BE(i,r,s,o,l,"next",c)}function l(c){BE(i,r,s,o,l,"throw",c)}o(void 0)}))}}function fr(e,t,n){return t=Kf(t),(function(r,s){if(s&&(typeof s=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return(function(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i})(r)})(e,ZP()?Reflect.construct(t,n||[],Kf(e).constructor):t.apply(e,n))}function Ft(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $t(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function ue(e,t,n){return(t=(function(r){var s=(function(i,o){if(typeof i!="object"||!i)return i;var l=i[Symbol.toPrimitive];if(l!==void 0){var c=l.call(i,o);if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return(o==="string"?String:Number)(i)})(r,"string");return typeof s=="symbol"?s:s+""})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Kf(e){return Kf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Kf(e)}function mr(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Gy(e,t)}function ZP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(ZP=function(){return!!e})()}function UE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable}))),n.push.apply(n,r)}return n}function it(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?UE(Object(n),!0).forEach((function(r){ue(e,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):UE(Object(n)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))}))}return e}function bi(e,t){if(e==null)return{};var n,r,s=(function(o,l){if(o==null)return{};var c={};for(var d in o)if({}.hasOwnProperty.call(o,d)){if(l.includes(d))continue;c[d]=o[d]}return c})(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function ye(){ye=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,s=Object.defineProperty||function(P,F,z){P[F]=z.value},i=typeof Symbol=="function"?Symbol:{},o=i.iterator||"@@iterator",l=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function d(P,F,z){return Object.defineProperty(P,F,{value:z,enumerable:!0,configurable:!0,writable:!0}),P[F]}try{d({},"")}catch{d=function(F,z,B){return F[z]=B}}function u(P,F,z,B){var W=F&&F.prototype instanceof y?F:y,H=Object.create(W.prototype),V=new R(B||[]);return s(H,"_invoke",{value:D(P,z,V)}),H}function p(P,F,z){try{return{type:"normal",arg:P.call(F,z)}}catch(B){return{type:"throw",arg:B}}}t.wrap=u;var h="suspendedStart",f="suspendedYield",g="executing",x="completed",b={};function y(){}function v(){}function C(){}var w={};d(w,o,(function(){return this}));var S=Object.getPrototypeOf,E=S&&S(S(L([])));E&&E!==n&&r.call(E,o)&&(w=E);var k=C.prototype=y.prototype=Object.create(w);function j(P){["next","throw","return"].forEach((function(F){d(P,F,(function(z){return this._invoke(F,z)}))}))}function _(P,F){function z(W,H,V,G){var X=p(P[W],P,H);if(X.type!=="throw"){var K=X.arg,ie=K.value;return ie&&typeof ie=="object"&&r.call(ie,"__await")?F.resolve(ie.__await).then((function(le){z("next",le,V,G)}),(function(le){z("throw",le,V,G)})):F.resolve(ie).then((function(le){K.value=le,V(K)}),(function(le){return z("throw",le,V,G)}))}G(X.arg)}var B;s(this,"_invoke",{value:function(W,H){function V(){return new F((function(G,X){z(W,H,G,X)}))}return B=B?B.then(V,V):V()}})}function D(P,F,z){var B=h;return function(W,H){if(B===g)throw Error("Generator is already running");if(B===x){if(W==="throw")throw H;return{value:e,done:!0}}for(z.method=W,z.arg=H;;){var V=z.delegate;if(V){var G=M(V,z);if(G){if(G===b)continue;return G}}if(z.method==="next")z.sent=z._sent=z.arg;else if(z.method==="throw"){if(B===h)throw B=x,z.arg;
182z.dispatchException(z.arg)}else z.method==="return"&&z.abrupt("return",z.arg);B=g;var X=p(P,F,z);if(X.type==="normal"){if(B=z.done?x:f,X.arg===b)continue;return{value:X.arg,done:z.done}}X.type==="throw"&&(B=x,z.method="throw",z.arg=X.arg)}}}function M(P,F){var z=F.method,B=P.iterator[z];if(B===e)return F.delegate=null,z==="throw"&&P.iterator.return&&(F.method="return",F.arg=e,M(P,F),F.method==="throw")||z!=="return"&&(F.method="throw",F.arg=new TypeError("The iterator does not provide a '"+z+"' method")),b;var W=p(B,P.iterator,F.arg);if(W.type==="throw")return F.method="throw",F.arg=W.arg,F.delegate=null,b;var H=W.arg;return H?H.done?(F[P.resultName]=H.value,F.next=P.nextLoc,F.method!=="return"&&(F.method="next",F.arg=e),F.delegate=null,b):H:(F.method="throw",F.arg=new TypeError("iterator result is not an object"),F.delegate=null,b)}function N(P){var F={tryLoc:P[0]};1 in P&&(F.catchLoc=P[1]),2 in P&&(F.finallyLoc=P[2],F.afterLoc=P[3]),this.tryEntries.push(F)}function O(P){var F=P.completion||{};F.type="normal",delete F.arg,P.completion=F}function R(P){this.tryEntries=[{tryLoc:"root"}],P.forEach(N,this),this.reset(!0)}function L(P){if(P||P===""){var F=P[o];if(F)return F.call(P);if(typeof P.next=="function")return P;if(!isNaN(P.length)){var z=-1,B=function W(){for(;++z<P.length;)if(r.call(P,z))return W.value=P[z],W.done=!1,W;return W.value=e,W.done=!0,W};return B.next=B}}throw new TypeError(typeof P+" is not iterable")}return v.prototype=C,s(k,"constructor",{value:C,configurable:!0}),s(C,"constructor",{value:v,configurable:!0}),v.displayName=d(C,c,"GeneratorFunction"),t.isGeneratorFunction=function(P){var F=typeof P=="function"&&P.constructor;return!!F&&(F===v||(F.displayName||F.name)==="GeneratorFunction")},t.mark=function(P){return Object.setPrototypeOf?Object.setPrototypeOf(P,C):(P.__proto__=C,d(P,c,"GeneratorFunction")),P.prototype=Object.create(k),P},t.awrap=function(P){return{__await:P}},j(_.prototype),d(_.prototype,l,(function(){return this})),t.AsyncIterator=_,t.async=function(P,F,z,B,W){W===void 0&&(W=Promise);var H=new _(u(P,F,z,B),W);return t.isGeneratorFunction(F)?H:H.next().then((function(V){return V.done?V.value:H.next()}))},j(k),d(k,c,"Generator"),d(k,o,(function(){return this})),d(k,"toString",(function(){return"[object Generator]"})),t.keys=function(P){var F=Object(P),z=[];for(var B in F)z.push(B);return z.reverse(),function W(){for(;z.length;){var H=z.pop();if(H in F)return W.value=H,W.done=!1,W}return W.done=!0,W}},t.values=L,R.prototype={constructor:R,reset:function(P){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(O),!P)for(var F in this)F.charAt(0)==="t"&&r.call(this,F)&&!isNaN(+F.slice(1))&&(this[F]=e)},stop:function(){this.done=!0;var P=this.tryEntries[0].completion;if(P.type==="throw")throw P.arg;return this.rval},dispatchException:function(P){if(this.done)throw P;var F=this;function z(X,K){return H.type="throw",H.arg=P,F.next=X,K&&(F.method="next",F.arg=e),!!K}for(var B=this.tryEntries.length-1;B>=0;--B){var W=this.tryEntries[B],H=W.completion;if(W.tryLoc==="root")return z("end");if(W.tryLoc<=this.prev){var V=r.call(W,"catchLoc"),G=r.call(W,"finallyLoc");if(V&&G){if(this.prev<W.catchLoc)return z(W.catchLoc,!0);if(this.prev<W.finallyLoc)return z(W.finallyLoc)}else if(V){if(this.prev<W.catchLoc)return z(W.catchLoc,!0)}else{if(!G)throw Error("try statement without catch or finally");if(this.prev<W.finallyLoc)return z(W.finallyLoc)}}}},abrupt:function(P,F){for(var z=this.tryEntries.length-1;z>=0;--z){var B=this.tryEntries[z];if(B.tryLoc<=this.prev&&r.call(B,"finallyLoc")&&this.prev<B.finallyLoc){var W=B;break}}W&&(P==="break"||P==="continue")&&W.tryLoc<=F&&F<=W.finallyLoc&&(W=null);var H=W?W.completion:{};return H.type=P,H.arg=F,W?(this.method="next",this.next=W.finallyLoc,b):this.complete(H)},complete:function(P,F){if(P.type==="throw")throw P.arg;return P.type==="break"||P.type==="continue"?this.next=P.arg:P.type==="return"?(this.rval=this.arg=P.arg,this.method="return",this.next="end"):P.type==="normal"&&F&&(this.next=F),b},finish:function(P){for(var F=this.tryEntries.length-1;F>=0;--F){var z=this.tryEntries[F];if(z.finallyLoc===P)return this.complete(z.completion,z.afterLoc),O(z),b}},catch:function(P){for(var F=this.tryEntries.length-1;F>=0;--F){var z=this.tryEntries[F];if(z.tryLoc===P){var B=z.completion;if(B.type==="throw"){var W=B.arg;O(z)}
182return W}}throw Error("illegal catch attempt")},delegateYield:function(P,F,z){return this.delegate={iterator:L(P),resultName:F,nextLoc:z},this.method==="next"&&(this.arg=e),b}},t}function Gy(e,t){return Gy=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Gy(e,t)}function Qf(e,t){return(function(n){if(Array.isArray(n))return n})(e)||(function(n,r){var s=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(s!=null){var i,o,l,c,d=[],u=!0,p=!1;try{if(l=(s=s.call(n)).next,r!==0)for(;!(u=(i=l.call(s)).done)&&(d.push(i.value),d.length!==r);u=!0);}catch(h){p=!0,o=h}finally{try{if(!u&&s.return!=null&&(c=s.return(),Object(c)!==c))return}finally{if(p)throw o}}return d}})(e,t)||(function(n,r){if(n){if(typeof n=="string")return zE(n,r);var s={}.toString.call(n).slice(8,-1);return s==="Object"&&n.constructor&&(s=n.constructor.name),s==="Map"||s==="Set"?Array.from(n):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?zE(n,r):void 0}})(e,t)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 183In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function oa(e){return oa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},oa(e)}var eL={CALLBACK_OPERATION_INVOKED:"CALLBACK_OPERATION_INVOKED",CONTENT_LOADED:"CONTENT_LOADED",EXPERIENCE_INITIALIZED:"EXPERIENCE_INITIALIZED",ERROR_OCCURRED:"ERROR_OCCURRED",SIZE_CHANGED:"SIZE_CHANGED",PARAMETERS_CHANGED:"PARAMETERS_CHANGED",SELECTED_SHEET_CHANGED:"SELECTED_SHEET_CHANGED",MODAL_OPENED:"MODAL_OPENED",Q_SEARCH_CLOSED:"Q_SEARCH_CLOSED",Q_SEARCH_OPENED:"Q_SEARCH_OPENED",Q_SEARCH_FOCUSED:"Q_SEARCH_FOCUSED",Q_SEARCH_SIZE_CHANGED:"Q_SEARCH_SIZE_CHANGED",Q_SEARCH_ENTERED_FULLSCREEN:"Q_SEARCH_ENTERED_FULLSCREEN",Q_SEARCH_EXITED_FULLSCREEN:"Q_SEARCH_EXITED_FULLSCREEN",Q_PANEL_ENTERED_FULLSCREEN:"Q_PANEL_ENTERED_FULLSCREEN",Q_PANEL_EXITED_FULLSCREEN:"Q_PANEL_EXITED_FULLSCREEN",PAGE_NAVIGATION:"PAGE_NAVIGATION"},tL={FRAME_STARTED:"FRAME_STARTED",FRAME_MOUNTED:"FRAME_MOUNTED",FRAME_LOADED:"FRAME_LOADED",FRAME_REMOVED:"FRAME_REMOVED"},nL={FRAME_NOT_CREATED:"FRAME_NOT_CREATED",NO_BODY:"NO_BODY",NO_CONTAINER:"NO_CONTAINER",INVALID_CONTAINER:"INVALID_CONTAINER",NO_URL:"NO_URL",INVALID_URL:"INVALID_URL",NO_FRAME_OPTIONS:"NO_FRAME_OPTIONS",INVALID_FRAME_OPTIONS:"INVALID_FRAME_OPTIONS"},rL={UNRECOGNIZED_CONTENT_OPTIONS:"UNRECOGNIZED_CONTENT_OPTIONS",UNRECOGNIZED_FRAME_OPTIONS:"UNRECOGNIZED_FRAME_OPTIONS",UNRECOGNIZED_EVENT_TARGET:"UNRECOGNIZED_EVENT_TARGET"},sL={SET_PARAMETERS:"SET_PARAMETERS",SET_SELECTED_SHEET_ID:"SET_SELECTED_SHEET_ID",SET_Q_SEARCH_QUESTION:"SET_Q_SEARCH_QUESTION",SET_VISUAL_ACTIONS:"SET_VISUAL_ACTIONS",SET_THEME:"SET_THEME",ADD_FILTER_GROUPS:"ADD_FILTER_GROUPS",UPDATE_FILTER_GROUPS:"UPDATE_FILTER_GROUPS",REMOVE_FILTER_GROUPS:"REMOVE_FILTER_GROUPS",ADD_VISUAL_ACTIONS:"ADD_VISUAL_ACTIONS",REMOVE_VISUAL_ACTIONS:"REMOVE_VISUAL_ACTIONS",SET_THEME_OVERRIDE:"SET_THEME_OVERRIDE",PRELOAD_THEMES:"PRELOAD_THEMES",CREATE_SHARED_VIEW:"CREATE_SHARED_VIEW"},iL={GET_PARAMETERS:"GET_PARAMETERS",GET_SHEETS:"GET_SHEETS",GET_SHEET_VISUALS:"GET_SHEET_VISUALS",GET_VISUAL_ACTIONS:"GET_VISUAL_ACTIONS",GET_SELECTED_SHEET_ID:"GET_SELECTED_SHEET_ID",GET_FILTER_GROUPS_FOR_SHEET:"GET_FILTER_GROUPS_FOR_SHEET",GET_FILTER_GROUPS_FOR_VISUAL:"GET_FILTER_GROUPS_FOR_VISUAL"},aL={ACKNOWLEDGE:"ACKNOWLEDGE",INITIATE_PRINT:"INITIATE_PRINT",NAVIGATE_TO_DASHBOARD:"NAVIGATE_TO_DASHBOARD",CLOSE_Q_SEARCH:"CLOSE_Q_SEARCH",UNDO:"UNDO",REDO:"REDO",RESET:"RESET",TOGGLE_EXECUTIVE_SUMMARY_PANE:"TOGGLE_EXECUTIVE_SUMMARY_PANE",OPEN_BUILD_VISUAL_PANE:"OPEN_BUILD_VISUAL_PANE",OPEN_DATA_QNA_PANE:"OPEN_DATA_QNA_PANE",TOGGLE_BOOKMARKS_PANE:"TOGGLE_BOOKMARKS_PANE",TOGGLE_THRESHOLD_ALERTS_PANE:"TOGGLE_THRESHOLD_ALERTS_PANE",TOGGLE_SCHEDULING_PANE:"TOGGLE_SCHEDULING_PANE",TOGGLE_RECENT_SNAPSHOTS_PANE:"TOGGLE_RECENT_SNAPSHOTS_PANE",OPEN_BUILD_STORY_PANE:"OPEN_BUILD_STORY_PANE"},wle=Object.freeze({__proto__:null,ErrorChangeEventName:nL,GetterMessageEventName:iL,InfoChangeEventName:tL,InfoMessageEventName:eL,InvokerMessageEventName:aL,SetterMessageEventName:sL,WarnC
183hangeEventName:rL}),mn=it(it(it({},tL),nL),rL),ze=it(it(it(it({},eL),sL),iL),aL),gn={ERROR:"ERROR",INFO:"INFO",WARN:"WARN"},Sle=Object.freeze({__proto__:null,ChangeEventLevel:gn,ChangeEventName:mn,MessageEventName:ze}),jle=Object.freeze({__proto__:null}),kle=Object.freeze({__proto__:null}),Ele=Object.freeze({__proto__:null}),_le=Object.freeze({__proto__:null}),Er={CONSOLE:"CONSOLE",CONTEXT:"CONTEXT",CONTROL:"CONTROL",VISUAL:"VISUAL",DASHBOARD:"DASHBOARD",QSEARCH:"QSEARCH",GENERATIVEQNA:"QSEARCH"},Tle=Object.freeze({__proto__:null,ExperienceType:Er}),Ile=Object.freeze({__proto__:null}),Dle={NULL:null,OTHER_BUCKET:null},Ale={INTEGER:null,STRING:null,DECIMAL:null,DATETIME:null},Mle=Object.freeze({__proto__:null,CALCULATED_METRIC_COLUMN_TYPE:Ale,SPECIAL_DATAPOINT_VALUE_TYPES:Dle}),Rle=Object.freeze({__proto__:null}),Nle=Object.freeze({__proto__:null}),Ole=Object.freeze({__proto__:null}),jh={FULL:"FULL",SEARCH_BAR:"SEARCH_BAR"},Ple=Object.freeze({__proto__:null,GenerativeQnAPanelType:jh}),Lle=Object.freeze({__proto__:null}),oL=$t((function e(t,n,r){Ft(this,e),this.eventName=t,this.message=n,this.data=r})),jn=(function(){function e(t,n,r,s){var i;return Ft(this,e),(i=fr(this,e,[t,r,s])).eventLevel=n,i}return mr(e,oL),$t(e)})(),Xe=(function(){function e(t,n,r){var s;return Ft(this,e),(s=fr(this,e,[t,n,r])).eventName=t,s}return mr(e,oL),$t(e)})(),K0=(function(){function e(t,n,r,s){var i;return Ft(this,e),(i=fr(this,e,[t,r,s])).eventTarget=n,i}return mr(e,Xe),$t(e)})(),Fle=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),(c=fr(this,e,[t,n,o,l])).timestamp=s,c.version=i,c.eventId=r,c}return mr(e,K0),$t(e)})();$t((function e(){Ft(this,e)}));var VE=$t((function e(){Ft(this,e),ue(this,"success",!0)})),$le=$t((function e(t){Ft(this,e),ue(this,"success",!1),this.errorCode=t.errorCode,this.error=t.error,this.message=t.message})),zle=$t((function e(t){Ft(this,e),ue(this,"success",!0),this.message=t}));let Ip;const Ble=new Uint8Array(16);function Ule(){if(!Ip&&(Ip=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ip))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ip(Ble)}const nr=[];for(let e=0;e<256;++e)nr.push((e+256).toString(16).slice(1));var WE={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function lL(e,t,n){if(WE.randomUUID&&!e)return WE.randomUUID();const r=(e=e||{}).random||(e.rng||Ule)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,(function(s,i=0){return nr[s[i+0]]+nr[s[i+1]]+nr[s[i+2]]+nr[s[i+3]]+"-"+nr[s[i+4]]+nr[s[i+5]]+"-"+nr[s[i+6]]+nr[s[i+7]]+"-"+nr[s[i+8]]+nr[s[i+9]]+"-"+nr[s[i+10]]+nr[s[i+11]]+nr[s[i+12]]+nr[s[i+13]]+nr[s[i+14]]+nr[s[i+15]]})(r)}var Pl=$t((function e(t,n,r,s){var i=this;Ft(this,e),ue(this,"send",(function(){var o=qe(ye().mark((function l(c){var d;return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:if(i.experienceFrame&&i.internalExperience){u.next=2;break}throw new Error("Experience has not been initialized");case 2:return d=new K0(c.eventName,i.internalExperience,c.message,c.data),u.abrupt("return",i.experienceFrame.send(d));case 4:case"end":return u.stop()}}),l)})));return function(l){return o.apply(this,arguments)}})()),ue(this,"addEventListener",(function(o,l){return i.experienceFrame.addInternalEventListener(o,l)})),ue(this,"setLogProvider",(function(o){return i.logger=o,i})),ue(this,"getInternalExperienceInfo",(function(o){var l,c,d=-1;do d++,l=it(it({},o),{},{contextId:i.controlOptions.contextId,discriminator:d}),c=e.getExperienceIdentifier(l);while(i.experienceIdentifiers.has(c));return i.experienceIdentifiers.add(c),{experienceIdentifier:c,internalExperience:l}})),ue(this,"transformContentOptions",(function(o,l){return i.warnUnrecognizedContentOptions(Object.keys(l)),o})),ue(this,"warnUnrecognizedContentOptions",(function(o){var l,c,d;o.length>0&&((l=(c=i.frameOptions).onChange)===null||l===void 0||l.call(c,new jn(mn.UNRECOGNIZED_CONTENT_OPTIONS,gn.WARN,"Experience content options contain unrecognized properties",{unrecognizedContentOptions:o}),{frame:null}),(d=i.logger)===null||d===void 0||d.warn("Experience content options contain unrecognized properties"))})),ue(this,"validateFrameOptions",(function(){if(!i.frameOptions.url){var o,l,c="Url is required for the experience";throw(o=(l=i.frameOptions).onChange)===null||o===void 0||o.call(l,new jn(mn.NO_URL,gn.ERROR,c),{frame:null}),new Error(c)}})),this.frameOptions=t,this.contentOptions=n,this.controlOptions=r,this.experienceIdentifiers=s,this.validateFrameOptions()}));ue(Pl,"getExperienceIdentifier",(function(e){if(e.experienceType===Er.DASHBOARD)return[e.contextId,e.experienceType,e.dashboardId,e.discriminator].filter(
183Boolean).join("-");if(e.experienceType===Er.VISUAL)return[e.contextId,e.experienceType,e.dashboardId,e.sheetId,e.visualId,e.discriminator].filter(Boolean).join("-");if([Er.CONSOLE,Er.CONTROL,Er.CONTEXT,Er.QSEARCH,Er.GENERATIVEQNA].includes(e.experienceType))return[e.contextId,e.experienceType,e.discriminator].filter(Boolean).join("-");throw new Error("Invalid experience unable to build experience identifier")}));const Ax=2147483647,Vle={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},Wo=Math.floor,Mx=String.fromCharCode;function HE(e){throw new RangeError(Vle[e])}const qE=function(e,t){return e+22+75*(e<26)-((t!=0)<<5)},Wle=function(e,t,n){let r=0;for(e=n?Wo(e/700):e>>1,e+=Wo(e/t);e>455;r+=36)e=Wo(e/35);return Wo(r+36*e/(e+38))},Hle=function(e){const t=[];e=(function(c){const d=[];let u=0;const p=c.length;for(;u<p;){const h=c.charCodeAt(u++);if(h>=55296&&h<=56319&&u<p){const f=c.charCodeAt(u++);(64512&f)==56320?d.push(((1023&h)<<10)+(1023&f)+65536):(d.push(h),u--)}else d.push(h)}return d})(e);const n=e.length;let r=128,s=0,i=72;for(const c of e)c<128&&t.push(Mx(c));const o=t.length;let l=o;for(o&&t.push("-");l<n;){let c=Ax;for(const u of e)u>=r&&u<c&&(c=u);const d=l+1;c-r>Wo((Ax-s)/d)&&HE("overflow"),s+=(c-r)*d,r=c;for(const u of e)if(u<r&&++s>Ax&&HE("overflow"),u===r){let p=s;for(let h=36;;h+=36){const f=h<=i?1:h>=i+26?26:h-i;if(p<f)break;const g=p-f,x=36-f;t.push(Mx(qE(f+g%x,0))),p=Wo(g/x)}t.push(Mx(qE(p,0))),i=Wle(s,d,l===o),s=0,++l}++s,++r}return t.join("")};var cL=$t((function e(t){var n=this;Ft(this,e),ue(this,"classNames",[e.IFRAME_CLASS_NAME]),ue(this,"getIframe",(function(){return n.iframe})),ue(this,"createIframePlaceholder",(function(x){if(n.iframePlaceholder=document.createElement("div"),n.iframePlaceholder.id="".concat(n.iframeName,"-placeholder"),n.iframePlaceholder.style.width=n.width,n.iframePlaceholder.style.backgroundColor="rgba(0,0,0,.01)",n.iframePlaceholder.style.display="flex",n.iframePlaceholder.style.justifyContent="center",n.iframePlaceholder.style.alignItems="center",n.iframePlaceholder.className="".concat(e.IFRAME_CLASS_NAME,"-placeholder"),n.height.endsWith("px")&&(n.iframePlaceholder.style.height=n.height),x&&typeof x!="boolean")n.iframePlaceholder.appendChild(x);else{var b=n.createLoaderSVG();n.iframePlaceholder.appendChild(b)}n.container.appendChild(n.iframePlaceholder)})),ue(this,"createIframe",(function(){var x=document.createElement("iframe");return x.className=n.classNames.join(" ").trim(),x.id=n.iframeName,x.name=n.iframeName,x.width=n.width,x.height=n.height,n.loading&&(x.loading=n.loading),x.style.border="0px",x.style.padding="0px",n.iframePlaceholder&&(x.style.opacity="0",x.style.position="absolute"),n.width==="0px"&&n.height==="0px"&&(x.style.position="absolute"),n.container.appendChild(x),n.payload?n.postRequest=n.createPostRequest({src:n.src,target:x.name,container:n.container,payload:n.payload}):x.src=n.src,x})),ue(this,"onLoadLocal",(function(x){var b,y;n.iframePlaceholder&&(n.iframePlaceholder.remove(),n.iframe.style.position="",n.iframe.style.opacity="1",n.iframe.style.transition="opacity .5s ease-in-out"),(b=n.onLoad)===null||b===void 0||b.call(n,x),(y=n.postRequest)===null||y===void 0||y.remove()})),ue(this,"createPostRequest",(function(x){var b=x.src,y=x.container,v=x.target,C=x.payload;if(!b)throw new Error("No source has been provided.");var w=document.createElement("form");return w.style.visibility="hidden",w.method="POST",w.action=b,w.target=v,w.name="".concat(v,"-form"),Object.keys(C).forEach((function(S){var E=document.createElement("input");E.type="hidden",E.name=S,E.value=C[S],w.appendChild(E)})),y.appendChild(w),w?.submit(),{remove:function(){w.remove()}}})),ue(this,"createSvgElement",(function(x,b){var y=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},v=arguments.length>3&&arguments[3]!==void 0?arguments[3]:[],C=document.createElementNS("http://www.w3.org/2000/svg",x);return Object.entries(b).forEach((function(w){var S=Qf(w,2),E=S[0],k=S[1];return C.setAttribute(E,k)}
183)),Object.entries(y).forEach((function(w){var S=Qf(w,2),E=S[0],k=S[1];return C.style.setProperty(E,k)})),v.forEach((function(w){return C.appendChild(w)})),C})),ue(this,"createLoaderSVG",(function(){var x=[1,2,3].map((function(b){var y=n.createSvgElement("animate",{attributeName:"opacity",dur:"1s",values:"0;1;0",repeatCount:"indefinite",begin:"".concat(b/10)});return n.createSvgElement("circle",{fill:"#ccc",stroke:"none",cx:"".concat(20*b-14),cy:"50",r:"6"},void 0,[y])}));return n.createSvgElement("svg",{version:"1.1",x:"0px",y:"0px",viewBox:"0 0 100 100","enable-background":"new 0 0 0 0"},{width:"100px",height:"100px"},x)}));var r=t.id,s=t.src,i=t.width,o=i===void 0?"100%":i,l=t.height,c=l===void 0?"100%":l,d=t.container,u=t.onLoad,p=t.loading,h=t.withIframePlaceholder,f=t.payload,g=t.className;this.width=o,this.height=c,this.onLoad=u,this.iframeName=r,this.loading=p,g&&this.classNames.push(g),this.container=d,this.payload=f,this.src=s,h&&this.createIframePlaceholder(h),this.iframe=this.createIframe(),this.iframe.addEventListener("load",this.onLoadLocal)}));ue(cL,"IFRAME_CLASS_NAME","quicksight-embedding-iframe");var GE="2.10.1",Ll=$t((function e(t,n,r,s,i,o,l){var c=this;Ft(this,e),ue(this,"MESSAGE_RESPONSE_TIMEOUT",5e3),ue(this,"iframe",null),ue(this,"send",(function(){var d=qe(ye().mark((function u(p){var h,f,g;return ye().wrap((function(x){for(;;)switch(x.prev=x.next){case 0:if(!c.controlOptions.sendToControlFrame){x.next=2;break}return x.abrupt("return",c.controlOptions.sendToControlFrame(p));case 2:if(c.iframe){x.next=4;break}throw new Error("Cannot send ".concat(p.eventName,": No experience frame found"));case 4:if(f=lL(),g=new Fle(p.eventName,p.eventTarget,f,Date.now(),GE,p.message,p.data),(h=c.iframe)===null||h===void 0||(h=h.contentWindow)===null||h===void 0||h.postMessage(g,c.url),p.eventName!==ze.ACKNOWLEDGE){x.next=9;break}return x.abrupt("return",Promise.resolve(new VE));case 9:return x.abrupt("return",new Promise((function(b,y){var v=function(C){var w,S,E=C.data;E?.eventId===f&&(window.removeEventListener("message",v),((w=E.message)===null||w===void 0?void 0:w.success)===!0?b(new VE):((S=E.message)===null||S===void 0?void 0:S.success)===!1?b(new $le(E.message)):b(new zle(E.message)))};window.addEventListener("message",v),setTimeout((function(){window.removeEventListener("message",v),y("".concat(p.eventName," timed out"))}),c.MESSAGE_RESPONSE_TIMEOUT)})));case 10:case"end":return x.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(this,"buildParameterString",(function(d){return d&&oa(d)==="object"?Object.entries(d).map((function(u){var p=Qf(u,2),h=p[0],f=p[1],g=Array.isArray(f)?f:[f],x=encodeURIComponent(h);return g.map(encodeURIComponent).map((function(b){return"p.".concat(x,"=").concat(b)})).join("&")})).join("&"):""})),ue(this,"buildQueryString",(function(d){var u=Object.entries(d).reduce((function(p,h){var f=Qf(h,2),g=f[0],x=f[1];return x!=null?it(it({},p),{},ue({},g,"".concat(x))):p}),{punyCodeEmbedOrigin:Hle("".concat(window.location.origin,"/")),sdkVersion:GE});return new URLSearchParams(u).toString()})),ue(this,"createExperienceIframe",(function(){c.onChange(new jn(mn.FRAME_STARTED,gn.INFO,"Creating the frame",{experience:c.internalExperience}));try{c.setTimeoutInstance(),c.iframe=new cL({id:c.experienceId,src:c.url,width:c.frameOptions.width,height:c.frameOptions.height,container:c.container,onLoad:c.onLoadHandler,withIframePlaceholder:c.frameOptions.withIframePlaceholder,className:c.frameOptions.className}).getIframe()}catch(d){throw c.onChange(new jn(mn.FRAME_NOT_CREATED,gn.ERROR,"Failed to create the frame",{experience:c.internalExperience})),d}c.onChange(new jn(mn.FRAME_MOUNTED,gn.INFO,"The frame mounted",{experience:c.internalExperience,frame:c.iframe}))})),ue(this,"addInternalEventListener",(function(d,u){var p=function(h,f){h.eventName===d&&u(h,f)};return c.controlOptions.eventManager.addEventListener(c.experienceId,p,!0),{remove:function(){return c.controlOptions.eventManager.removeEventListener(c.experienceId,p)}}})),ue(this,"validateBaseUrl",(function(d){if(!d)throw c.onChange(new jn(m
183n.NO_URL,gn.ERROR,"Url is required for the experience",{experience:c.internalExperience})),new Error("Url is required for the experience");return d})),ue(this,"setTimeoutInstance",(function(){c.timeoutInstance=setTimeout((function(){throw c.onChange(new jn(mn.FRAME_NOT_CREATED,gn.ERROR,"Creating the frame timed out",{experience:c.internalExperience})),new Error("Creating the frame timed out")}),c.controlOptions.timeout)})),ue(this,"onLoadHandler",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:c.timeoutInstance&&clearTimeout(c.timeoutInstance),c.onChange(new jn(mn.FRAME_LOADED,gn.INFO,"The experience iframe loaded",{experience:c.internalExperience}));case 2:case"end":return u.stop()}}),d)})))),ue(this,"getContainer",(function(d){if(!d){var u="Container is required for the experience";throw c.onChange(new jn(mn.NO_CONTAINER,gn.ERROR,u,{experience:c.internalExperience})),new Error(u)}var p=null;if(typeof d=="string")try{p=document.querySelector(d)}catch(f){throw f instanceof Error&&c.onChange(new jn(mn.INVALID_CONTAINER,gn.ERROR,f.message,{experience:c.internalExperience})),f}else oa(d)==="object"&&d.nodeName&&(p=d);if(!p){var h="Invalid container '".concat(d,"' for the experience");throw c.onChange(new jn(mn.INVALID_CONTAINER,gn.ERROR,h,{experience:c.internalExperience})),new Error(h)}return p})),ue(this,"decorateOnChange",(function(d){return function(u){if(d){var p={frame:c.iframe};d(u,p)}}})),ue(this,"decorateOnMessage",(function(d,u){return function(p){u&&c.iframe&&u(p,{frame:c.iframe}),d&&d(p,{frame:c.iframe})}})),ue(this,"initializeMutationObserver",(function(){var d=new MutationObserver((function(u){u.some((function(p){return Array.from(p.removedNodes).some((function(h){return h===c.iframe||h===c.container}))}))&&(c.controlOptions.eventManager.cleanUpCallbacksForExperience(c.experienceId),d.disconnect(),c.iframe=null,c.onChange(new jn(mn.FRAME_REMOVED,gn.INFO,"Frame removed from the DOM",{experience:c.internalExperience})))}));d.observe(document.body,{childList:!0,subtree:!0})})),this.frameOptions=t,this.contentOptions=r,this.onChange=this.decorateOnChange(t.onChange),this.onMessage=this.decorateOnMessage(r.onMessage,l),this.container=this.getContainer(t.container),this.internalExperience=i,this.controlOptions=n,this.transformedContentOptions=s,this.experienceId=o,this.url=this.validateBaseUrl(t.url),this.controlOptions.eventManager.addEventListener(this.experienceId,this.onMessage,!0),this.initializeMutationObserver()})),qle=["parameters"],Gle=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),ue(c=fr(this,e,[t,n,r,s,i,o,l]),"buildExperienceUrl",(function(d){var u=c.transformedContentOptions,p=u.parameters,h=bi(u,qle),f=c.internalExperience,g=f.contextId,x=f.discriminator;return[d,[c.buildQueryString(it(it({},h),{},{contextId:g,discriminator:x})),c.buildParameterString(p)].join("#")].join(d.includes("?")?"&":"?")})),c.url=c.buildExperienceUrl(t.url),c.createExperienceIframe(),c}return mr(e,Ll),$t(e)})(),Yle=["fitToIframeWidth","locale","parameters","themeOptions","onMessage"],Kle=(function(){function e(t,n,r,s){var i;Ft(this,e),ue(i=fr(this,e,[t,n,r,s]),"setParameters",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_PARAMETERS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"reset",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.RESET)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"addFilterGroups",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.ADD_FILTER_GROUPS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"updateFilterGroups",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.UPDATE_FILTER_GROUPS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"removeFilterGroups",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.REMOVE_FILTER_GROUPS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"getFilterGroups",qe(ye().mark((function d(){var u;return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,i.send(new Xe(ze.GET_FILTER_GROUPS_FOR_VISUAL));case 2:if(u=p.sent,Array.isArray(u?.message)){p.next=5;break}throw new Error("Failed to retrieve filter groups for the visual");case 5:return p.abrupt("return",u.message);case 6:case"end":return p.stop()}}),d)})))),ue(i,"getActions",qe(ye().mark((function d(){var u;return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,i.send(new Xe(ze.GET_VISUAL_ACTIONS));case 2:if(u=p.sent,Array.isArray(u?.message)){p.next=5;break}throw new Error("Failed to retrieve the actions");case 5:return p.abrupt("return",u.message);case 6:case"end":return p.stop()}}),d)})))),ue(i,"addActions",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.ADD_VISUAL_ACTIONS,{Actions:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setActions",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_
183VISUAL_ACTIONS,{Actions:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"removeActions",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.REMOVE_VISUAL_ACTIONS,{Actions:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setTheme",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_THEME,{ThemeArn:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setThemeOverride",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_THEME_OVERRIDE,{ThemeOverride:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setPreloadThemes",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.PRELOAD_THEMES,{PreloadThemes:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"extractExperienceFromUrl",(function(d){var u,p,h=/^https:\/\/[^/]+\/embed\/[^/]+\/dashboards\/([\w-]+)\/sheets\/([\w-]+)\/visuals\/([\w-]+)(\?|$)/i.exec(d)||[];if(h.length<5)throw(u=(p=i.frameOptions).onChange)===null||u===void 0||u.call(p,new jn(mn.INVALID_URL,gn.ERROR,"Invalid visual experience url",{url:d}),{frame:i.experienceFrame.iframe}),new Error("Invalid visual experience URL");return{experienceType:Er.VISUAL,dashboardId:h[1],sheetId:h[2],visualId:h[3]}})),ue(i,"interceptMessage",(function(d,u){var p,h,f,g,x;d.eventName==="SIZE_CHANGED"&&i.frameOptions.resizeHeightOnSizeChangedEvent&&(u==null||(f=u.frame)===null||f===void 0||(g=f.setAttribute)===null||g===void 0||g.call(f,"height","".concat((x=d.message)===null||x===void 0?void 0:x.height,"px"))),d.eventName==="EXPERIENCE_INITIALIZED"&&(p=i.contentOptions)!==null&&p!==void 0&&(p=p.themeOptions)!==null&&p!==void 0&&p.themeOverride&&i.setThemeOverride(i.contentOptions.themeOptions.themeOverride),d.eventName==="EXPERIENCE_INITIALIZED"&&(h=i.contentOptions)!==null&&h!==void 0&&(h=h.themeOptions)!==null&&h!==void 0&&h.preloadThemes&&i.setPreloadThemes(i.contentOptions.themeOptions.preloadThemes)})),ue(i,"transformVisualContentOptions",(function(d){var u=d.fitToIframeWidth,p=d.locale,h=d.parameters,f=d.themeOptions;d.onMessage;var g=bi(d,Yle),x=i.transformContentOptions({fitToIframeWidth:u==null||u,locale:p},g);return Array.isArray(h)&&(x.parameters=h.reduce((function(b,y){return it(it({},b),{},ue({},y.Name,y.Values))}),{})),f!=null&&f.themeArn&&(x.themeArn=f.themeArn),x})),i.experience=i.extractExperienceFromUrl(t.url);var o=i.getInternalExperienceInfo(i.experience),l=o.experienceIdentifier,c=o.internalExperience;return i.internalExperience=c,i.experienceId=l,i.experienceFrame=new Gle(t,r,n,i.transformVisualContentOptions(n),c,l,i.interceptMessage),i}return mr(e,Pl),$t(e)})(),Qle=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),ue(c=fr(this,e,[t,n,r,s,i,o,l]),"buildExperienceUrl",(function(d){var u=c.internalExperience,p=u.contextId,h=u.discriminator;return[d,c.buildQueryString(it(it({},c.transformedContentOptions),{},{contextId:p,discriminator:h}))].join(d.includes("?")?"&":"?")})),c.url=c.buildExperienceUrl(t.url),c.createExperienceIframe(),c}return mr(e,Ll),$t(e)})(),Jle=["locale","toolbarOptions","onMessage"],Xle=(function(){function e(t,n,r,s){var i;Ft(this,e),ue(i=fr(this,e,[t,n,r,s]),"createSharedView",qe(ye().mark((function u(){var p;return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:if(i.currentPage==="DASHBOARD"||i.currentPage==="DASHBOARD_SHEET"||i.currentPage==="DASHBOARD_VIEW"){h.next=2;break}throw new Error("Cannot call createSharedView from this page");case 2:return h.next=4,i.send(new Xe(ze.CREATE_SHARED_VIEW));case 4:if((p=h.sent)!=null&&p.message){h.next=7;break}throw new Error("Failed to create shared view");case 7:return h.abrupt("return",p);case 8:case"end":return h.stop()}}),u)})))),ue(i,"toggleExecutiveSummaryPane",qe(ye().mark((function u(){return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:if(i.currentPage==="DASHBOARD"){p.next=2;break}throw new Error("Cannot call toggleExecutiveSummaryPane from this page");case 2:return p.abrupt("return",i.send(new Xe(ze.TOGGLE_EXECUTIVE_SUMMARY_PANE)));case 3:case"end":return p.stop()}}),u)})))),ue(i,"openDataQnAPane",qe(ye().mark((function u(){return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.abrupt("return",i.send(new Xe(ze.OPEN_DATA_QNA_PANE)));case 1:case"end":return p.stop()}}),u)})))),ue(i,"openBuildVisualPane",qe(ye().mark((function u(){return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.abrupt("return",i.send(new Xe(ze.OPEN_BUILD_VISUAL_PANE)));case 1:case"end":return p.stop()}}),u)})))),ue(i,"buildStoryFromDashboard",qe(ye().mark((function u(){return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:if(i.currentPage==="DASHBOARD"){p.next=2;break}throw new Error('Cannot call buildStoryFromDashboard from "'.concat(i.currentPage,'" page'));case 2:return p.abrupt("return",i.send(new Xe(ze.OPEN_BUILD_STORY_PANE)));case 3:case"end":return p.stop()}}),u)})))),ue(i,"interceptMessage",(function(u,p){var h;u.eventName===ze.PAGE_NAVIGATION&&(i.currentPage=u==null||(h=u.message)===null||h===void 0?void 0:h.pageType)})),ue(i,"extractExperienceFromUrl",(function(u){var p,h;if((/^https:\/\/[^/]+\/embedding\/[^/]+\/(start(\/(favorites|dashboards|analyses))?|dashboards\/[\w-]+(\/views\/[\w-]+)?|analyses\/[\w-]+)(\?|$)/i.exec(u)||[]).length<5)throw(p=(h=i.frameOptions).onChange)===null||p===void 0||p.call(h,new jn(mn.INVALID_URL,gn.ERROR,"Invalid console experience url",{url:u}),{frame:i.experienceFrame.iframe}),new Error("Invalid console experience URL");return{experienceType:Er.CONSOLE}})),ue(i,"transformConsoleContentOptions",(function(u){var p=u.locale,h=u.toolbarOptions;u.onMessage;var f=bi(u,Jle),g=i.transformContentOptions({locale:p},f);return h?.executiveSummary===!0&&(g.showExecutiveSummaryIcon=!0),h?.dataQnA===!0&&(g.showDataQnAIcon=!0),h?.buildVisual===!0&&(g.showBuildVisualIcon=!0),h?.buildStory===!0&&(g.showBuildStoryIcon=!0),g}
183)),i.experience=i.extractExperienceFromUrl(t.url);var o=i.getInternalExperienceInfo(i.experience),l=o.experienceIdentifier,c=o.internalExperience;i.internalExperience=c,i.experienceId=l,n.locale,n.onMessage;var d=i.transformConsoleContentOptions(n);return i.experienceFrame=new Qle(t,r,n,d,c,l,i.interceptMessage),i.currentPage="START",i}return mr(e,Pl),$t(e)})(),Zle=["parameters"],ece=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),ue(c=fr(this,e,[t,n,r,s,i,o,l]),"buildExperienceUrl",(function(d){var u=c.transformedContentOptions,p=u.parameters,h=bi(u,Zle),f=c.internalExperience,g=f.contextId,x=f.discriminator,b=c.contentOptions.viewId;if(b){var y=new URL(d);y.pathname=y.pathname.concat("/views/"+b),d=y.href}return[d,[c.buildQueryString(it(it({},h),{},{contextId:g,discriminator:x})),c.buildParameterString(p)].join("#")].join(d.includes("?")?"&":"?")})),c.url=c.buildExperienceUrl(t.url),c.createExperienceIframe(),c}return mr(e,Ll),$t(e)})(),tce=["parameters","locale","attributionOptions","sheetOptions","toolbarOptions","themeOptions","onMessage"],nce=(function(){function e(t,n,r,s){var i;Ft(this,e),ue(i=fr(this,e,[t,n,r,s]),"initiatePrint",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.INITIATE_PRINT)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"undo",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.UNDO)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"redo",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.REDO)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"toggleExecutiveSummaryPane",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.TOGGLE_EXECUTIVE_SUMMARY_PANE)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"toggleBookmarksPane",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.TOGGLE_BOOKMARKS_PANE)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"toggleThresholdAlertsPane",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.TOGGLE_THRESHOLD_ALERTS_PANE)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"toggleSchedulingPane",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.TOGGLE_SCHEDULING_PANE)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"toggleRecentSnapshotsPane",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.TOGGLE_RECENT_SNAPSHOTS_PANE)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"getParameters",qe(ye().mark((function d(){var u;return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,i.send(new Xe(ze.GET_PARAMETERS));case 2:if(u=p.sent,Array.isArray(u?.message)){p.next=5;break}throw new Error("Failed to retrieve the parameters");case 5:return p.abrupt("return",u.message);case 6:case"end":return p.stop()}}),d)})))),ue(i,"getSheets",qe(ye().mark((function d(){var u;return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,i.send(new Xe(ze.GET_SHEETS));case 2:if(u=p.sent,Array.isArray(u?.message)){p.next=5;break}throw new Error("Failed to retrieve the sheets");case 5:return p.abrupt("return",u.message);case 6:case"end":return p.stop()}}),d)})))),ue(i,"addFilterGroups",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.ADD_FILTER_GROUPS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"updateFilterGroups",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.UPDATE_FILTER_GROUPS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"removeFilterGroups",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.REMOVE_FILTER_GROUPS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"getFilterGroupsForSheet",(function(){var d=qe(ye().mark((function u(p){var h;return ye().wrap((function(f){for(;;)switch(f.prev=f.next){case 0:return f.next=2,i.send(new Xe(ze.GET_FILTER_GROUPS_FOR_SHEET,{SheetId:p}));case 2:if(h=f.sent,Array.isArray(h?.message)){f.next=5;break}throw new Error("Failed to retrieve filter groups for the sheet");case 5:return f.abrupt("return",h.message);case 6:case"end":return f.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"getFilterGroupsForVisual",(function(){var d=qe(ye().mark((function u(p,h){var f;return ye().wrap((function(g){for(;;)switch(g.prev=g.next){case 0:return g.next=2,i.send(new Xe(ze.GET_FILTER_GROUPS_FOR_VISUAL,{SheetId:p,VisualId:h}));case 2:if(f=g.sent,Array.isArray(f?.message)){g.next=5;break}throw new Error("Failed to retrieve filter groups for the visual");case 5:return g.abrupt("return",f.message);case 6:case"end":return g.stop()}}),u)})));return function(u,p){return d.apply(this,arguments)}})()),ue(i,"getVisualActions",(function(){var d=qe(ye().mark((function u(p,h){var f;return ye().wrap((function(g){for(;;)switch(g.prev=g.next){case 0:return g.next=2,i.send(new Xe(ze.GET_VISUAL_ACTIONS,{SheetId:p,VisualId:h}));case 2:if(f=g.sent,Array.isArray(f?.message)){g.next=5;break}throw new Error("Failed to retrieve the visual actions");case 5:return g.abrupt("return",f.message);case 6:case"end":return g.stop()}}),u)})));return function(u,p){return d.apply(this,arguments)}})()),ue(i,"addVisualActions",(function(){var d=qe(ye().mark((function u(p,h,f){return ye().wrap((function(g){for(;;)switch(g.prev=g.next){case 0:return g.abrupt("return",i.send(new Xe(ze.ADD_VISUAL_ACTIONS,{SheetId:p,VisualId:h,Actions:f})));case 1:case"end":return g.stop()}}),u)})));return function(u,p,h){return d.apply(this,arguments)}})()),ue(i,"setVisualActions",(function(){var d=qe(ye().mark((function u(p,h,f){return ye().wrap((function(g){for(;;)switch(g.prev=g.next){case 0:return g.abrupt("return",i.send(new Xe(ze.SET_
183VISUAL_ACTIONS,{SheetId:p,VisualId:h,Actions:f})));case 1:case"end":return g.stop()}}),u)})));return function(u,p,h){return d.apply(this,arguments)}})()),ue(i,"getSelectedSheetId",qe(ye().mark((function d(){var u;return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,i.send(new Xe(ze.GET_SELECTED_SHEET_ID));case 2:if((u=p.sent)!=null&&u.message){p.next=5;break}throw new Error("Failed to retrieve the selected sheet id");case 5:return p.abrupt("return",u.message);case 6:case"end":return p.stop()}}),d)})))),ue(i,"setSelectedSheetId",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_SELECTED_SHEET_ID,{SheetId:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setTheme",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_THEME,{ThemeArn:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"navigateToDashboard",(function(){var d=qe(ye().mark((function u(p,h){return ye().wrap((function(f){for(;;)switch(f.prev=f.next){case 0:return f.abrupt("return",i.send(new Xe(ze.NAVIGATE_TO_DASHBOARD,{DashboardId:p,Parameters:h?.parameters})));case 1:case"end":return f.stop()}}),u)})));return function(u,p){return d.apply(this,arguments)}})()),ue(i,"removeVisualActions",(function(){var d=qe(ye().mark((function u(p,h,f){return ye().wrap((function(g){for(;;)switch(g.prev=g.next){case 0:return g.abrupt("return",i.send(new Xe(ze.REMOVE_VISUAL_ACTIONS,{SheetId:p,VisualId:h,Actions:f})));case 1:case"end":return g.stop()}}),u)})));return function(u,p,h){return d.apply(this,arguments)}})()),ue(i,"getSheetVisuals",(function(){var d=qe(ye().mark((function u(p){var h;return ye().wrap((function(f){for(;;)switch(f.prev=f.next){case 0:return f.next=2,i.send(new Xe(ze.GET_SHEET_VISUALS,{SheetId:p}));case 2:if(h=f.sent,Array.isArray(h?.message)){f.next=5;break}throw new Error("Failed to retrieve the sheet visuals");case 5:return f.abrupt("return",h.message);case 6:case"end":return f.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setParameters",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_PARAMETERS,p)));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"reset",qe(ye().mark((function d(){return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",i.send(new Xe(ze.RESET)));case 1:case"end":return u.stop()}}),d)})))),ue(i,"setThemeOverride",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.SET_THEME_OVERRIDE,{ThemeOverride:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"setPreloadThemes",(function(){var d=qe(ye().mark((function u(p){return ye().wrap((function(h){for(;;)switch(h.prev=h.next){case 0:return h.abrupt("return",i.send(new Xe(ze.PRELOAD_THEMES,{PreloadThemes:p})));case 1:case"end":return h.stop()}}),u)})));return function(u){return d.apply(this,arguments)}})()),ue(i,"createSharedView",qe(ye().mark((function d(){var u;return ye().wrap((function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,i.send(new Xe(ze.CREATE_SHARED_VIEW));case 2:if((u=p.sent)!=null&&u.message){p.next=5;break}throw new Error("Failed to create shared view");case 5:return p.abrupt("return",u);case 6:case"end":return p.stop()}}),d)})))),ue(i,"extractExperienceFromUrl",(function(d){var u,p,h=/^https:\/\/[^/]+\/embed\/[^/]+\/dashboards\/([\w-]+)(\?|$)/i.exec(d)||[];if(h.length<3)throw(u=(p=i.frameOptions).onChange)===null||u===void 0||u.call(p,new jn(mn.INVALID_URL,gn.ERROR,"Invalid dashboard experience url",{url:d}),{frame:null}),new Error("Invalid dashboard experience URL");return{experienceType:Er.DASHBOARD,dashboardId:h[1]}})),ue(i,"interceptMessage",(function(d,u){var p,h,f,g,x;d.eventName==="SIZE_CHANGED"&&i.frameOptions.resizeHeightOnSizeChangedEvent&&(u==null||(f=u.frame)===null||f===void 0||(g=f.setAttribute)===null||g===void 0||g.call(f,"height","".concat(d==null||(x=d.message)===null||x===void 0?void 0:x.height,"px"))),d.eventName==="EXPERIENCE_INITIALIZED"&&(p=i.contentOptions)!==null&&p!==void 0&&(p=p.themeOptions)!==null&&p!==void 0&&p.themeOverride&&i.setThemeOverride(i.contentOptions.themeOptions.themeOverride),d.eventName==="EXPERIENCE_INITIALIZED"&&(h=i.contentOptions)!==null&&h!==void 0&&(h=h.themeOptions)!==null&&h!==void 0&&h.preloadThemes&&i.setPreloadThemes(i.contentOptions.themeOptions.preloadThemes)})),ue(i,"transformDashboardContentOptions",(function(d){var u,p=d.parameters,h=d.locale,f=d.attributionOptions,g=d.sheetOptions,x=d.toolbarOptions,b=d.themeOptions;d.onMessage;var y=bi(d,tce),v=i.transformContentOptions({locale:h},y);return Array.isArray(p)&&(v.parameters=p.reduce((function(C,w){return it(it({},C),{},ue({},w.Name,w.Values))}),{})),f?.overlayContent!==!0&&(v.footerPaddingEnabled=!0),(x!=null&&x.export||x!=null&&(u=x.export)!==null&&u!==void 0&&u.print)&&(v.printEnabled=!0),x?.undoRedo!==!0&&(v.undoRedoDisabled=!0),x?.reset!==!0&&(v.resetDisabled=!0),x?.bookmarks===!0&&(v.showBookmarksIcon=!0),x?.thresholdAlerts===!0&&(v.showThresholdAlertsIcon=!0),x?.scheduling===!0&&(v.showSchedulingIcon=!0),x?.executiveSummary===!0&&(v.showExecutiveSummaryIcon=!0),x?.recentSnapshots===!0&&(v.showRecentSnapshotsIcon=!0),g!=null&&g.initialSheetId&&(v.sheetId=g.initialSheetId),typeof g?.singleSheet=="boolean"&&(v.sheetTabsDisabled=g.singleSheet),g!=null&&g.emitSizeChangedEventOnSheetChange&&(v.resizeOnSheetChange=!0),b!=null&&b.themeArn&&(v.themeArn=b.themeArn),v}
183)),i.experience=i.extractExperienceFromUrl(t.url);var o=i.getInternalExperienceInfo(i.experience),l=o.experienceIdentifier,c=o.internalExperience;return i.internalExperience=c,i.experienceId=l,i.experienceFrame=new ece(t,r,n,i.transformDashboardContentOptions(n),c,l,i.interceptMessage),i}return mr(e,Pl),$t(e)})(),rce=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),ue(c=fr(this,e,[t,n,r,s,i,o,l]),"buildExperienceUrl",(function(d){var u=c.internalExperience,p=u.contextId,h=u.discriminator;return[d,c.buildQueryString(it(it({},c.transformedContentOptions),{},{contextId:p,discriminator:h}))].join(d.includes("?")?"&":"?")})),c.url=c.buildExperienceUrl(t.url),c.createExperienceIframe(),c}return mr(e,Ll),$t(e)})(),Q0=(function(){function e(){var t;Ft(this,e);for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return ue(t=fr(this,e,[].concat(r)),"close",(function(){return t.send(new Xe(ze.CLOSE_Q_SEARCH))})),ue(t,"setQuestion",(function(i){return t.send(new Xe(ze.SET_Q_SEARCH_QUESTION,{question:i}))})),ue(t,"trackOutsideClicks",(function(){var i=(function(){var o=qe(ye().mark((function l(c){var d;return ye().wrap((function(u){for(;;)switch(u.prev=u.next){case 0:if((d=t.experienceFrame.iframe)!==null&&d!==void 0&&d.contains(c.target)){u.next=11;break}return u.prev=1,u.next=4,t.close();case 4:u.next=11;break;case 6:if(u.prev=6,u.t0=u.catch(1),t.experienceFrame.iframe){u.next=10;break}return u.abrupt("return");case 10:throw u.t0;case 11:case"end":return u.stop()}}),l,null,[[1,6]])})));return function(l){return o.apply(this,arguments)}})();window.addEventListener("click",i),t.controlOptions.eventManager.addEventListenerForCleanup(t.experienceId,(function(){return window.removeEventListener("click",i)}))})),ue(t,"enterFullScreen",(function(i){var o,l;!t.frameStyles&&i!=null&&i.frame&&(t.frameStyles={position:(o=i.frame)===null||o===void 0?void 0:o.style.position,top:(l=i.frame)===null||l===void 0?void 0:l.style.top,left:i.frame.style.left,zIndex:i.frame.style.zIndex,width:i.frame.style.width,height:i.frame.style.height},i.frame.style.position="fixed",i.frame.style.top="0px",i.frame.style.left="0px",i.frame.style.zIndex=e.MAX_Z_INDEX,i.frame.style.width="100vw",i.frame.style.height="100vh")})),ue(t,"exitFullScreen",(function(i){t.frameStyles&&i!=null&&i.frame&&(i.frame.style.position=t.frameStyles.position,i.frame.style.top=t.frameStyles.top,i.frame.style.left=t.frameStyles.left,i.frame.style.zIndex=t.frameStyles.zIndex,i.frame.style.width=t.frameStyles.width,i.frame.style.height=t.frameStyles.height,t.frameStyles=void 0)})),t}return mr(e,Pl),$t(e)})();ue(Q0,"MAX_Z_INDEX","2147483647");var sce=["hideIcon","hideTopicName","theme","allowTopicSelection","onMessage"],ice=(function(){function e(t,n,r,s){var i;Ft(this,e),ue(i=fr(this,e,[t,n,r,s]),"extractExperienceFromUrl",(function(d){var u,p;if((/^https:\/\/[^/]+\/embedding\/[^/]+\/q\/search(\/|\?|$)/i.exec(d)||[]).length<2)throw(u=(p=i.frameOptions).onChange)===null||u===void 0||u.call(p,new jn(mn.INVALID_URL,gn.ERROR,"Invalid q-search experience URL",{url:d}),{frame:i.experienceFrame.iframe}),new Error("Invalid q-search experience URL");return{experienceType:Er.QSEARCH}})),ue(i,"interceptMessage",(function(d,u){switch(d.eventName){case ze.Q_SEARCH_OPENED:case ze.Q_SEARCH_CLOSED:var p,h;oa(d.message)==="object"&&(u==null||(p=u.frame)===null||p===void 0||p.style.setProperty("height","".concat(d==null||(h=d.message)===null||h===void 0?void 0:h.height,"px")));break;case ze.CONTENT_LOADED:i.trackOutsideClicks();break;case ze.Q_SEARCH_ENTERED_FULLSCREEN:i.enterFullScreen(u);break;case ze.Q_SEARCH_EXITED_FULLSCREEN:i.exitFullScreen(u)}})),ue(i,"transformQSearchContentOptions",(function(d){var u=d.hideIcon,p=d.hideTopicName,h=d.theme,f=d.allowTopicSelection;d.onMessage;var g=bi(d,sce),x=i.transformContentOptions({allowTopicSelection:f},g);return u!==void 0&&(x.qBarIconDisabled=u),p!==void 0&&(x.qBarTopicNameDisabled=p),h!==void 0&&(x.themeId=h),x})),i.experience=i.extractExperienceFromUrl(t.url);var o=i.getInternalExperienceInfo(i.experience),l=o.experienceIdentifier,c=o.internalExperience;
183return i.internalExperience=c,i.experienceId=l,i.experienceFrame=new rce(t,r,n,i.transformQSearchContentOptions(n),c,l,i.interceptMessage),i}return mr(e,Q0),$t(e)})(),ace=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),ue(c=fr(this,e,[t,n,r,s,i,o,l]),"buildExperienceUrl",(function(d){var u=c.internalExperience,p=u.contextId,h=u.discriminator;return[d,c.buildQueryString(it(it({},c.transformedContentOptions),{},{contextId:p,discriminator:h}))].join(d.includes("?")?"&":"?")})),c.url=c.buildExperienceUrl(t.url),c.createExperienceIframe(),c}return mr(e,Ll),$t(e)})(),oce=["onMessage","showTopicName","showPinboard","showSearchBar","showInterpretedAs","showFeedback","showGeneratedNarrative","showDidYouMean","showComplementaryVisuals","showQBusinessInsights","showSeeWhy","allowTopicSelection","allowFullscreen","allowReturn","searchPlaceholderText","panelOptions","themeOptions","initialQuestionId","initialAnswerId"],lce=["panelType","title","showQIcon"],cce=["panelType","focusedHeight","expandedHeight"],dL=(function(){function e(t,n,r,s){var i;Ft(this,e),ue(i=fr(this,e,[t,n,r,s]),"extractExperienceFromUrl",(function(d){var u,p;if((/^https:\/\/[^/]+\/embedding\/[^/]+\/q\/search(\/|\?|$)/i.exec(d)||[]).length<2)throw(u=(p=i.frameOptions).onChange)===null||u===void 0||u.call(p,new jn(mn.INVALID_URL,gn.ERROR,"Invalid generative-qna experience URL",{url:d}),{frame:i.experienceFrame.iframe}),new Error("Invalid generative-qna experience URL");return{experienceType:Er.GENERATIVEQNA}})),ue(i,"interceptMessage",(function(d,u){switch(d.eventName){case ze.Q_SEARCH_OPENED:case ze.Q_SEARCH_CLOSED:case ze.Q_SEARCH_FOCUSED:var p,h;oa(d.message)==="object"&&(u==null||(p=u.frame)===null||p===void 0||p.style.setProperty("height","".concat(d==null||(h=d.message)===null||h===void 0?void 0:h.height)));break;case ze.CONTENT_LOADED:var f;((f=i.contentOptions)===null||f===void 0||(f=f.panelOptions)===null||f===void 0?void 0:f.panelType)===jh.SEARCH_BAR&&i.trackOutsideClicks();break;case ze.Q_PANEL_ENTERED_FULLSCREEN:i.enterFullScreen(u);break;case ze.Q_PANEL_EXITED_FULLSCREEN:i.exitFullScreen(u)}})),ue(i,"transformGenerativeQnAContentOptions",(function(d){var u=[],p=function(V){var G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";Object.keys(V).forEach((function(X){u.push(G+X)}))};d.onMessage;var h=d.showTopicName,f=d.showPinboard,g=d.showSearchBar,x=d.showInterpretedAs,b=d.showFeedback,y=d.showGeneratedNarrative,v=d.showDidYouMean,C=d.showComplementaryVisuals,w=d.showQBusinessInsights,S=d.showSeeWhy,E=d.allowTopicSelection,k=d.allowFullscreen,j=d.allowReturn,_=d.searchPlaceholderText,D=d.panelOptions,M=d.themeOptions,N=d.initialQuestionId,O=d.initialAnswerId;p(bi(d,oce));var R={qShowTopicName:h,qShowPinboard:f,qShowSearchBar:g,qShowInterpretedAs:x,qShowFeedback:b,qShowGeneratedNarrative:y,qShowDidYouMean:v,qShowComplementaryVisuals:C,qShowQBusinessInsights:w,qShowSeeWhy:S,qAllowTopicSelection:E,qAllowFullscreen:k,qAllowReturn:j,questionId:N,answerId:O};if(typeof _=="string"&&(i.checkMaxLength(_,"searchPlaceholderText"),R.qSearchPlaceholderText=encodeURIComponent(_)),D){var L=D.panelType;if(R.qPanelType=L,L===jh.FULL){D.panelType;var P=D.title,F=D.showQIcon,z=bi(D,lce);typeof P=="string"&&(i.checkMaxLength(P,"panelOptions.title"),R.qPanelTitle=encodeURIComponent(P)),R.qShowPanelIcon=F,p(z,"panelOptions.")}else{if(L!==jh.SEARCH_BAR)throw new Error("panelOptions.panelType should be one of following: [FULL, SEARCH_BAR]");D.panelType;var B=D.focusedHeight,W=D.expandedHeight,H=bi(D,cce);R.qPanelFocusedHeight=B,R.qPanelExpandedHeight=W,p(H,"panelOptions.")}}return M!=null&&M.themeArn&&(R.themeArn=M.themeArn),i.warnUnrecognizedContentOptions(u),R})),ue(i,"checkMaxLength",(function(d,u){var p=e.TEXT_PROPERTY_MAX_LENGTH;if(d.length>p)throw new Error("".concat(u," should be less than ").concat(p," characters"))})),i.experience=i.extractExperienceFromUrl(t.url);var o=i.getInternalExperienceInfo(i.experience),l=o.experienceIdentifier,c=o.internalExperience;return i.internalExperience=c,i.experienceId=l,i.experienceFrame=new ace(t,r,n,i.transformGenerativeQnAContentOptions(n),c,l,i.interceptMessage),i}return mr(e,Q0),$t(e)})();ue(dL,"TEXT_PROPERTY_MAX_LENGTH",200);var dce=(function(){function e(t,n,r,s,i,o,l){var c;return Ft(this,e),ue(c=fr(this,e,[t,n,r,s,i,o,l]),"buildExperienceUrl",(function(d){var u=c.internalExperience,p=u.contextId,h=u.discriminator;return[d,c.buildQueryString(it(it({},c.transformedContentOptions),{},{contextId:p,discriminator:h}))].join("?")})),c.url=c.buildExperienceUrl(t.url),c.createExperienceIframe(),c}return mr(e,Ll),$t(e)})(),Yy=$t((function e(t,n,r,s){var i=this;Ft(this,e),ue(this,"experience",{experienceType:Er.CONTROL}),ue(this,"send",(function(l){return i.controlExperienceFrame.send(l)})),ue(this,"controlFrameMessageListener",(function(l){if(i.isMessageEvent(l.data)){var c=l.data;try{if(c.eventTarget){var d=Pl.getExperienceIdentifier(c.eventTarget);i.eventManager.invokeEventListener(d,c)}i.sendAcknowledgment(c)}catch{var u,p;(u=i.onChange)===null||u===void 0||u.call(i,new jn(mn.UNRECOGNIZED_EVENT_TARGET,gn.WARN,"Message with unrecognized event target received",{eventTarget:c.eventTarget}),{frame:i.controlExperienceFrame.iframe}),(p=i.logger)===null||p===void 0||p.warn("Message with unrecognized event target received")}}})),ue(this,"sendAcknowledgment",(function(l){var c,d,u=new K0(ze.ACKNOWLEDGE,i.internalExperience,{eventName:l.eventName,eventTarget:l.eventTarget});!((c=(d=window).requestIdleCallback)===null||c===void 0)&&c.call(d,(function(){return i.send(u)}))||i.send(u)})),ue(this,"getControlExperienceId",(function(){return[i.internalExperience.contextId,i.internalExperience.experienceType,i.internalExperience.discriminator].filter(
183Boolean).join("-")})),ue(this,"getControlExperienceBaseUrl",(function(){var l=i.urlInfo,c=l.host,d=l.sessionId,u="".concat(c,"/embed/").concat(d,"/embedControl");return new URL(u).href})),ue(this,"isMessageEvent",(function(l){return!!l&&!!l.eventTarget&&!!l.eventName})),this.container=t,this.eventManager=n.eventManager,this.urlInfo=n.urlInfo,this.onChange=r,this.logger=s,this.internalExperience=it(it({},this.experience),{},{contextId:n.contextId,discriminator:0});var o=this.getControlExperienceId();this.controlExperienceFrame=new dce({url:this.getControlExperienceBaseUrl(),container:this.container,width:"0px",height:"0px",onChange:this.onChange},{eventManager:this.eventManager,contextId:this.internalExperience.contextId,timeout:e.FRAME_TIMEOUT,urlInfo:this.urlInfo},{},{},this.internalExperience,o),window.addEventListener("message",this.controlFrameMessageListener),this.eventManager.addEventListenerForCleanup(o,(function(){return window.removeEventListener("message",i.controlFrameMessageListener)}))}));ue(Yy,"FRAME_TIMEOUT",6e4);var uce=$t((function e(){var t=this;Ft(this,e),ue(this,"addEventListener",(function(n,r,s){if(!n)throw new Error("Experience identifier is required when calling addEventListener");if(typeof r!="function")throw new Error("Invalid type provided for event listener");var i=t.eventListeners.get(n);return s&&t.addEventListenerForCleanup(n,(function(){return t.removeEventListener(n,r)})),i?(i.push(r),t):(t.eventListeners.set(n,[r]),t)})),ue(this,"invokeEventListener",(function(n,r){var s=t.eventListeners.get(n);if(!s)throw new Error("Unable to find experience specific event listeners: ".concat(n));return s.forEach((function(i){i(r)})),t})),ue(this,"removeEventListener",(function(n,r){var s=t.eventListeners.get(n);if(!s)throw new Error("Unable to find experience specific event listeners: ".concat(n));var i=s.filter((function(o){return o!==r}));return t.eventListeners.set(n,i),t})),ue(this,"addEventListenerForCleanup",(function(n,r){var s,i=(s=t.cleanUpCallbacks.get(n))!==null&&s!==void 0?s:[];i.push(r),t.cleanUpCallbacks.set(n,i)})),ue(this,"cleanUpCallbacksForExperience",(function(n){var r=t.cleanUpCallbacks.get(n);r&&(r.forEach((function(s){return s()})),t.cleanUpCallbacks.delete(n),t.eventListeners.set(n,[]))})),this.eventListeners=new Map,this.cleanUpCallbacks=new Map})),pce=$t((function e(){Ft(this,e),ue(this,"log",console.log),ue(this,"warn",console.warn),ue(this,"error",console.error),ue(this,"debug",console.debug),ue(this,"info",console.info)})),hce=$t((function e(t){var n=this;Ft(this,e),ue(this,"embedVisual",(function(){var r=qe(ye().mark((function s(i){var o,l,c=arguments;return ye().wrap((function(d){for(;;)switch(d.prev=d.next){case 0:return o=c.length>1&&c[1]!==void 0?c[1]:{},n.validateFrameOptions(i,"embedVisual"),l=n.buildControlOptions(i),d.abrupt("return",new Kle(i,o,l,n.experienceIdentifiers).setLogProvider(n.logger));case 4:case"end":return d.stop()}}),s)})));return function(s){return r.apply(this,arguments)}})()),ue(this,"embedDashboard",(function(){var r=qe(ye().mark((function s(i){var o,l,c=arguments;return ye().wrap((function(d){for(;;)switch(d.prev=d.next){case 0:return o=c.length>1&&c[1]!==void 0?c[1]:{},n.validateFrameOptions(i,"embedDashboard"),l=n.buildControlOptions(i),d.abrupt("return",new nce(i,o,l,n.experienceIdentifiers).setLogProvider(n.logger));case 4:case"end":return d.stop()}}),s)})));return function(s){return r.apply(this,arguments)}})()),ue(this,"embedConsole",(function(){var r=qe(ye().mark((function s(i){var o,l,c=arguments;return ye().wrap((function(d){for(;;)switch(d.prev=d.next){case 0:return o=c.length>1&&c[1]!==void 0?c[1]:{},n.validateFrameOptions(i,"embedConsole"),l=n.buildControlOptions(i),d.abrupt("return",new Xle(i,o,l,n.experienceIdentifiers).setLogProvider(n.logger));case 4:case"end":return d.stop()}}),s)})));return function(s){return r.apply(this,arguments)}})()),ue(this,"embedQSearchBar",(function(){var r=qe(ye().mark((function s(i){var o,l,c=arguments;return ye().wrap((function(d){for(;;)switch(d.prev=d.next){case 0:return o=c.length>1&&c[1]!==void 0?c[1]:{},n.validateFrameOptions(i,"embedQSearchBar"),l=n.buildControlOptions(i),d.abrupt("return",new ice(i,o,l,n.experienceIdentifiers).setLogProvider(n.logger));case 4:case"end":return d.stop()}}),s)})));return function(s){return r.apply(this,arguments)}})()),ue(this,"embedGenerativeQnA",(function(){var r=qe(ye().mark((function s(i){var o,l,c=arguments;return ye().wrap((function(d){for(;;)switch(d.prev=d.next){case 0:return o=c.length>1&&c[1]!==void 0?c[1]:{},n.validateFrameOptions(i,"embedGenerativeQnA"),l=n.buildControlOptions(i),d.abrupt("return",new dL(i,o,l,n.experienceIdentifiers).setLogProvider(n.logger));case 4:case"end":return d.stop()}}),s)})));return function(s){return r.apply(this,arguments)}})()),ue(this,"validateFrameOptions",(function(r,s){if(!r){var i="".concat(s," is called without frameOptions");
183throw n.onChange(new jn(mn.NO_FRAME_OPTIONS,gn.ERROR,"".concat(s," is called without frameOptions"),{methodName:s}),{frame:null}),new Error(i)}if(oa(r)!=="object"||Array.isArray(r)){var o="".concat(s," is called with non-object frameOptions");throw n.onChange(new jn(mn.INVALID_FRAME_OPTIONS,gn.ERROR,o,{methodName:s,frameOptionsType:Array.isArray(r)?"array":oa(r)}),{frame:null}),new Error(o)}var l=["url","container","width","height","resizeHeightOnSizeChangedEvent","withIframePlaceholder","onChange","className"],c=Object.keys(r).filter((function(h){return!l.includes(h)}));if(c.length>0){var d,u,p="".concat(s," is called with unrecognized properties");(d=r.onChange)===null||d===void 0||d.call(r,new jn(mn.UNRECOGNIZED_FRAME_OPTIONS,gn.WARN,p,{unrecognizedFrameOptions:c}),{frame:null}),(u=n.logger)===null||u===void 0||u.warn(p)}})),ue(this,"buildControlOptions",(function(r){if(!n.controlOptions){if(!r.url)throw new Error("URL is missing in frame options, but is a required field");var s=n.getControlUrlInfo(r.url),i=new Yy(n.getBodyElement(),{eventManager:n.eventManager,urlInfo:s,contextId:n.contextId},n.onChange,n.logger);n.controlOptions={eventManager:n.eventManager,sendToControlFrame:i.send,contextId:n.contextId,timeout:Yy.FRAME_TIMEOUT,urlInfo:s}}return n.controlOptions})),ue(this,"onChange",(function(r,s){n.contextOnChange&&n.contextOnChange(r,s)})),ue(this,"getControlUrlInfo",(function(r){var s=/^(https:\/\/[^/]+)\/(embedding|embed)\/([^/]+)\/[^?]+\?(.*)/i.exec(r)||[];if(s?.length<4)throw new Error('Invalid embedding url: "'.concat(r,'"'));return{sessionId:s[3],host:s[1],urlSearchParams:new URLSearchParams(s[4])}})),ue(this,"getBodyElement",(function(){var r,s=(r=document.getElementsByTagName("body"))===null||r===void 0?void 0:r[0];if(!s){var i="could not locate <body> element in the page";throw n.onChange(new jn(mn.NO_BODY,gn.ERROR,i),{frame:null}),new Error(i)}return s})),this.contextId=lL(),this.experienceIdentifiers=new Set,this.eventManager=new uce,this.contextOnChange=t.onChange,this.logger=new pce})),fce=(function(){var e=qe(ye().mark((function t(){var n,r=arguments;return ye().wrap((function(s){for(;;)switch(s.prev=s.next){case 0:return n=r.length>0&&r[0]!==void 0?r[0]:{},s.abrupt("return",new hce(n));case 2:case"end":return s.stop()}}),t)})));return function(){return e.apply(this,arguments)}})();it(it(it(it(it(it(it(it(it(it(it(it(it(it({},_le),wle),Sle),jle),kle),Ele),Tle),Ile),Mle),Nle),Rle),Ole),Ple),Lle);const YE="qs-dashboard",mce=()=>{const{engagementNiceId:e}=pe(),{id:t}=Cm(),n=en(),{data:r=[],isError:s,isFetching:i}=TA(e),o=m.useMemo(()=>r.find(u=>u.dashboardId===t),[r,t]),{data:l,isFetching:c}=lV({engagementNiceId:e,dashboardId:o?.dashboardId??""},{skip:!o?.dashboardId}),d=m.useCallback(()=>{n("/visualize/dashboards")},[n]);return m.useEffect(()=>{!i&&!o&&d()},[o,i,d]),m.useEffect(()=>{l&&(async p=>{const h=await fce(),{embedDashboard:f}=h,g=document.getElementById(YE);g&&f({container:g,resizeHeightOnSizeChangedEvent:!0,url:p,withIframePlaceholder:!0})})(l)},[l]),a.jsxs($,{gap:4,pb:4,children:[a.jsx(vu,{handleNavigateHome:d,pageName:o?.name||"Dashboard",parentConfig:{handleNavigateToParent:d,parentName:"Dashboards"}}),a.jsx(T,{id:YE,width:"100%",children:i||c?"Loading...":s?"Error loading dashboard":null})]})},gce=()=>{const{palette:e}=Re(),t=`/data-dictionary.html?theme=${e.mode}`;return a.jsx(T,{component:"iframe",src:t,sx:{border:"none",height:"100%",minHeight:"calc(100vh - 120px)",width:"100%"},title:"Data Dictionary"},e.mode)},xce=()=>{const{engagementNiceId:e}=pe(),{data:t=[],isFetching:n,isLoading:r,refetch:s}=cV(e),[i,{isLoading:o}]=dV();return{handleUpdatePartition:m.useCallback(async({partitionId:c,notes:d,techopsStatus:u,dataSourceId:p})=>{const h=await i({dataSourceId:p,engagementNiceId:e,notes:d,partitionId:c,techopsStatus:u});return"data"in h&&h.data.success?{error:!1}:{error:!0}},[e,i]),partitionsLoading:n||r,partitions:t,refetchPartitions:s,updatingPartition:o}},Dp={failedUserCreation:{error:!0,message:"Failed to create user. Please try again later, or contact support",eventType:"FailedUserCreation"},failedAssignment:{error:!0,message:"The user was created, but could not be assigned as a contact",eventType:"FailedAssignment"},success:{error:!1,message:"User created and assigned successfully",eventType:"Success"}},KE={failedAssignment:{error:!0,message:"Error updating contacts",eventType:"FailedAssignment"},success:{error:!1,message:"Contacts updated successfully",eventType:"Success"}},bce=()=>{const[e]=IA(),[t]=DA(),{engagementId:n}=pe(),[r]=AA(),[s]=hC(),[i,o]=m.useState(!1),{data:l=[],isLoading:c}=MA(n),d=m.useCallback(async({id:f,contacts:g},x)=>{o(!0);const b={email:x.email,engagements:[Number(n)],first_name:x.firstName,groups:["CustomerRoles-BasicUser"],is_employee:!1,last_name:x.lastName,phone_number:x.phoneNumber||null,username:x.username},y=await e(b);if("error"in y)return o(!1),Dp.failedUserCreation;r({engagementId:Number(n)});const{data:v}=y;
183if(!("userId"in v))return o(!1),Dp.failedUserCreation;const C=[...g||[],{id:v.userId,is_primary:!1,is_private:!1,name:`${x.firstName} ${x.lastName}`,is_internal:!1}],w=await t({dataSourceId:f,engagementId:n,key:"contacts",value:C});return o(!1),"error"in w?(o(!1),Dp.failedAssignment):Dp.success},[e,n,r,t]),u=m.useCallback(async(f,g)=>{o(!0);const x=await t({dataSourceId:f,engagementId:n,key:"contacts",value:g});return o(!1),"error"in x?KE.failedAssignment:KE.success},[n,t]),p=m.useCallback(async f=>{if(!f.length)return{isValid:!1};const g=await s({parameter:"email",value:f});return"data"in g?{isValid:!g.data?.error}:{isValid:!1}},[s]),h=m.useCallback(async f=>{if(!f.length)return{isValid:!1};const g=await s({parameter:"username",value:f});return"data"in g?{isValid:!g.data?.error}:{isValid:!1}},[s]);return{allContacts:l,contactsLoading:c,handleCreateContact:d,handleUpdateContacts:u,updating:i,validateEmail:p,validateUsername:h}},ul=[{label:"Media",contentType:"agg",measurementCategory:["Media"],niceId:"media",feedLabel:"Media Type"},{label:"KPI",contentType:"agg",measurementCategory:["KPI"],niceId:"kpi",feedLabel:"KPI Name"},{label:"Media + KPI",contentType:"agg",measurementCategory:["KPI","Media"],niceId:"mediakpi",feedLabel:"Media Type"},{label:"External Factor",contentType:"extfactor",measurementCategory:["External Factor"],niceId:"extfactors",feedLabel:"External Factors Name"}];ul.map(({label:e})=>e);const rg=e=>ul.find(t=>t.label===e),uL={extfactor:"External Factor",log:"Log",match:"Match",microagg:"Micro Aggregate (Legacy)",spendadjustment:"Spend Adjustment"},yce="Aggregate",pL=e=>JSON.stringify(e.map(t=>t.trim().toLowerCase()).toSorted()),vce=new Map(ul.map(e=>[pL(e.measurementCategory),e.label])),Cce=uL,J0=({contentType:e,measurementCategory:t})=>{if(!e)return"";if(e==="microagg")return uL.microagg;if(t?.length){const n=vce.get(pL(t));if(n)return n}return Cce[e]??yce},hL=m.createContext(null),Je=()=>m.useContext(hL),fL=m.createContext(null),tn=()=>m.useContext(fL),An=()=>on(),wce=()=>{const{engagementNiceId:e}=pe(),[t]=uV();return m.useCallback(({data:r,validationField:s})=>t({data:r,engagementNiceId:e,validationField:s}).then(i=>{if(i.data){if(i.data.is_valid)return{apiErrors:null,otherError:null};if(i.data.errors?.length)return{apiErrors:i.data.errors,otherError:null}}return{apiErrors:null,otherError:"An unknown error occurred"}}),[e,t])},Sce=e=>iY(e)&&!Yb(e)?e:null,Ed=e=>Go(e)&&!Yb(e)&&e.some(t=>!Yb(t))?e:null,is=e=>typeof e=="string"?e:null,QE=e=>e?.query?{type:"query",query:is(e.query)||""}:{type:"table",table:is(e?.table)||""},jce=({source:e})=>{const t=e?.api_config?.[0];switch(e?.delivery_method){case"api":return{type:e.delivery_method,apiConfig:t||{},apiSecret:e.api_secret||""};case"bigquery":return{type:e.delivery_method,connectionId:e.connection_id??null,dataset:is(t?.dataset)||"",dateFieldName:is(t?.date_field)||"",filterClause:is(t?.filter)||"",project:is(t?.project)||"",queryOrTable:QE(t)};case"snowflake":return{type:e.delivery_method,connectionId:e.connection_id??null,database:is(t?.database)||"",dateFieldName:is(t?.date_field)||"",filterClause:is(t?.filter)||"",queryOrTable:QE(t),schema:is(t?.schema)||"",warehouse:is(t?.warehouse)||""};case"amazonads":case"cm360":case"dv360":case"ga4":case"googleads":case"sftp":case"sa360":case"fbinsights":case"pinterestads":case"redditads":case"linkedinads":case"tiktokmarketing":case"tiktokorganic":case"gsc":return{type:e.delivery_method,connectionId:e.connection_id??null,apiConfig:t??{}};default:return{type:"s3",bucket:e?.s3_bucket||"",fileFilter:e?.file_filter||"",path:e?.path||""}}},mL=({queryOrTable:e})=>e.type==="query"?{query:e.query}:{table:e.table},gL=({connectorValues:e})=>{const t={dataset:e.dataset,project:e.project,...mL(e)};return e.dateFieldName&&(t.date_field=e.dateFieldName),e.filterClause&&(t.filter=e.filterClause),t},xL=({connectorValues:e})=>{const t={database:e.database,schema:e.schema,warehouse:e.warehouse,...mL(e)};return e.dateFieldName&&(t.date_field=e.dateFieldName),e.filterClause&&(t.filter=e.filterClause),t},kce=({connectorValues:e,engagementNiceId:t,environment:n})=>{const r={api_config:null,api_secret:null,delivery_method:e.type,file_filter:null,path:null,s3_bucket:null};switch(e.type){case"api":return{...r,api_config:Ed([e.apiConfig]),api_secret:e.apiSecret};case"bigquery":return{...r,api_config:[gL({connectorValues:e})],connection_id:e.connectionId};case"snowflake":return{...r,api_config:[xL({connectorValues:e})],connection_id:e.connectionId};
183case"s3":return{...r,file_filter:e.fileFilter,path:e.path,s3_bucket:e.bucket};case"cm360":case"amazonads":case"dv360":case"ga4":case"googleads":case"sftp":case"sa360":case"fbinsights":case"pinterestads":case"redditads":case"linkedinads":case"tiktokmarketing":case"tiktokorganic":case"gsc":return{...r,api_config:Ed([e.apiConfig]),connection_id:e.connectionId};default:return{...r}}},bL=e=>{const t={attributes:[],placements:!1,creatives:!1,brand:!1};if(!e)return{type:"none",...t};const{name_cleaning:n}=e;if(!n)return{type:"full",...t};if(n.length===0)return{type:"none",...t};const r=n.filter(l=>![Tr.brand,Tr.creative,Tr.placement].includes(l)),s=n.some(l=>l===Tr.placement),i=n.some(l=>l===Tr.creative),o=n.some(l=>l===Tr.brand);return{type:"custom",attributes:r,placements:s,creatives:i,brand:o}},Ece=e=>{switch(e?.frequency){case"hourly":case"daily":return{type:"daily",offset:0};case"weekly":return{type:"weekly",offset:e?.freq_offset??0};default:return{type:"monthly",offset:e?.freq_offset??1}}},_ce=e=>{if(!e)return{deviceResolution:null,personResolution:null};const t=e?.events_json?.length&&e.events_json?.[0]||{};return{deviceResolution:"idr"in t&&t.idr?JSON.stringify(t.idr):null,personResolution:"pr"in t&&t.pr?JSON.stringify(t.pr):null}},Rx=({source:e})=>({active:e?.active??!1,connector:jce({source:e}),contacts:e?.contacts?.map(t=>!t.is_internal&&t.is_private?{...t,is_private:!1}:t)??[],diConfig:e?.di_config?.[0]??{},eventsJson:_ce(e),executionSteps:e?.execution_steps??[],fileCompression:Yf(e?.file_compression),fileConfig:e?.file_config??{},fileDelimiter:e?.file_delimiter??"",fileExtension:Yf(e?.file_extension)||"",frequency:Ece(e),headers:e?.header_json??[],name:e?.name||null,nameCleaning:bL(e),notes:e?.notes||null,schedule:e?.supervisor_scheduling??!1,verify:e?.validation_active??!1}),Tce=e=>{const{type:t,attributes:n=[],placements:r,creatives:s,brand:i}=e.nameCleaning;if(t==="none")return[];if(t==="full")return null;if(t==="custom"){const o=[];return r&&o.push(Tr.placement),s&&o.push(Tr.creative),i&&o.push(Tr.brand),o.concat(n)}return null},Ice=e=>{if(!e.eventsJson)return null;const{deviceResolution:t,personResolution:n}=e.eventsJson,r={};return t&&(r.idr=t),n&&(r.pr=n),Object.keys(r).length?[r]:null},Dce=({engagementNiceId:e,environment:t,formValues:n})=>{const r=kce({connectorValues:n.connector,engagementNiceId:e,environment:t}),s=Tce(n),i=Ice(n);return{id:null,active:n.active,api_config:r.api_config,api_secret:r.api_secret,contacts:n.contacts||null,connection_id:r.connection_id,delivery_method:n.connector.type,di_config:Ed([n.diConfig]),events_json:i,execution_steps:Ed(n.executionSteps),file_compression:n.fileCompression||null,file_config:Sce(n.fileConfig),file_delimiter:n.fileDelimiter,file_extension:n.fileExtension,file_filter:r.file_filter,frequency:n.frequency.type,freq_offset:n.frequency.offset,header_json:Ed(n.headers),name:n.name||null,name_cleaning:s,notes:n.notes||null,path:r.path,s3_bucket:r.s3_bucket,supervisor_scheduling:n.schedule,validation_active:n.verify}},Ace=()=>{const[e,{isFetching:t}]=pV(),[n,{isFetching:r}]=hV(),s=m.useCallback(async i=>{const{bucket:o,fileFilter:l,path:c}=i;if(!o||!c)return!1;try{return l?await e({bucket:o,keyword:l,path:c}).unwrap():await n({bucket:o,path:c}).unwrap()}catch{return!1}},[e,n]);return{isValidating:t||r,validateS3Connection:s}},Mce=({engagementNiceId:e,environment:t})=>{const[n,{isFetching:r}]=fV(),s=m.useCallback(async i=>{const{type:o,connectionId:l}=i,c=[o==="bigquery"?gL({connectorValues:i}):xL({connectorValues:i})];try{return(await n({apiConfig:c,type:o,connectionId:l}).unwrap()).is_valid}catch{return!1}},[e,t,n]);return{isValidating:r,testApiConnection:s}},Rce=({engagementNiceId:e,environment:t})=>{const n=ct(),{isValidating:r,validateS3Connection:s}=Ace(),{isValidating:i,testApiConnection:o}=Mce({engagementNiceId:e,environment:t}),[l,c]=m.useState(null),d=m.useCallback(async p=>{c(null);let h=!1;switch(p.type){case"bigquery":case"snowflake":h=await o(p);break;case"s3":h=await s(p);break;default:h=!1}return n()&&c(h?"success":"error"),h},[n,o,s]),u=m.useCallback(()=>c(null),[]);return{isValidating:r||i,resetStatus:u,status:l,validate:d}},sg=({nextView:e,saveText:t="Save Changes"})=>{const{dispatch:n}=Je(),{dispatch:r,resetChanges:s,state:i}=tn(),{isSubmitting:o}=i,{formState:l}=An(),{isDirty:c,errors:d,isValid:u}=l,p=!u&&d.root&&Object.keys(d).length===1?d.root.message:null,h=!u||!c,f=()=>{n({type:"nextView",value:e}),r({type:"saveChangesDialogOpen",value:!0})};return a.jsxs($,{sx:{rowGap:1},children:[p&&a.jsx(I,{color:"error",fontSize:"12px",fontWeight:500,children:p}),a.jsxs($,{sx:{flexDirection:"row",columnGap:2,justifyContent:"flex-end"},children:[a.jsx(re,{color:"secondary",disabled:!c,variant:"outlined",onClick:s,children:"Reset Changes"}),a.jsx(Dt,{disabled:h,loading:o,onClick:f,variant:"contained",children:t})]})]})},JE=e=>{try{return eR.parse(e),!0}catch{return!1}},Nce=e=>typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):e===null,XE=e=>e?typeof e=="string"?e:e.value:null,Oce=e=>Array.isArray(e)?e.map(t=>XE(t)).filter(t=>t!==null):XE(e),ZE=(e,t)=>{const n=t.find(r=>r.value===e);return n||{value:e,label:e}},e_=({defaultValue:e,fieldName:t,freeSolo:n,label:r,multiple:s,options:i=[],required:o})=>{const{control:l}=An(),{isSubmitting:c}=tn().state,[d,u]=m.useState(""),p=m.useCallback((x,b,y)=>{(i.find(C=>C.label===b)||y!=="reset")&&u(b)},[i]),h=m.useCallback(({onChange:x,nextValue:b,reason:y})=>{switch(y){case"selectOption":case"removeOption":case"createOption":x(Oce(b));break;case"clear":x(s?[]:o?"":null);break}u("")},[s,o]),f=m.useCallback(({rawInput:x,value:b})=>Nce(b)?!n||!x?b:Array.isArray(b)?b.some(v=>v===x)?b:(u(""),[...b,x]):i.find(v=>v.label===x)?.value??x:null,[n,i]),g=m.useCallback(x=>
183JE(x)?x:typeof x=="string"?ZE(x,i):Array.isArray(x)?x.map(b=>JE(b)?b:typeof b=="string"?ZE(b,i):null).filter(b=>b!==null):s?[]:null,[s,i]);return a.jsx(Et,{control:l,name:t,defaultValue:e,render:({field:{value:x,onBlur:b,onChange:y,ref:v},fieldState:{error:C}})=>a.jsx(gl,{multiple:s,disabled:c,freeSolo:n,inputValue:d,onInputChange:p,getOptionLabel:w=>typeof w=="string"?w:w.label,isOptionEqualToValue:(w,S)=>(typeof w=="string"?w:w.value)===(typeof S=="string"?S:S.value),onChange:(w,S,E)=>h({onChange:y,nextValue:S,reason:E}),options:i,renderInput:w=>a.jsx(De,{...w,error:!!C,helperText:C?.message??" ",inputRef:v,label:r,required:o,onBlur:S=>{b();const E=S.target.value.trim();y(f({rawInput:E,value:x}))}}),value:g(x)})})},ig=({isValid:e,type:t})=>{const{error:n,success:r}=Re().palette;if(e===null)return null;const s=(e?r:n).main,i=e?qv:Gv,o=`${t} ${e?"Successful":"Failed"}`;return a.jsxs(T,{sx:{alignItems:"center",columnGap:1,display:"flex"},children:[a.jsx(i,{sx:{color:s}}),a.jsx(I,{fontSize:"12px",fontWeight:500,children:o})]})},Pce=e=>{let t="",n="",r=null;try{r=JSON.parse(e),n=JSON.stringify(r,null,4)}catch(s){s instanceof Error&&s.message.toLowerCase().includes("json")?t=s.message:t="Unknown error"}return{errorMessage:t,formattedValue:n,parsedValue:r}},Lce=e=>{switch(e.type){case"syntax":return"JSON Syntax Error(s)";case"validation":return"Validation Error(s)";default:return""}},Fce=e=>{const t=[];let n=null;return e.forEach(r=>{typeof r=="string"?n=n?`${n}.${r}`:r:(n&&(t.push(`Key: ${JSON.stringify(n)}`),n=null),t.push(`Item ${r+1}`))}),n&&t.push(`Key: ${JSON.stringify(n)}`),t},Nx=rt(T)(({theme:e})=>({display:"grid",gridTemplateColumns:"80px 1fr",paddingLeft:e.spacing(2)})),$ce=({error:e})=>typeof e=="string"?a.jsx(I,{children:e}):a.jsx($,{sx:{rowGap:4,overflow:"auto",maxWidth:"100%"},children:e.map((t,n)=>a.jsxs($,{sx:{rowGap:1},children:[a.jsxs(I,{children:["Error ",n+1,":"]}),a.jsxs(Nx,{children:[a.jsx(I,{children:"Location:"}),a.jsx(T,{children:Fce(t.loc).map((r,s)=>s===0?a.jsx(I,{sx:{display:"inline-grid"},children:r},r):a.jsxs(I,{sx:{display:"inline-grid"},children:["Â â ",r]},r))})]}),a.jsxs(Nx,{children:[a.jsx(I,{children:"Input:"}),a.jsx(I,{sx:{whiteSpace:"pre-wrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:JSON.stringify(t.input,null,2)})]}),a.jsxs(Nx,{children:[a.jsx(I,{children:"Message:"}),a.jsx(I,{children:t.msg})]})]},JSON.stringify(t.loc)))}),zce=({checkFormatting:e,checkValidity:t,error:n,isValid:r,loading:s,onChange:i,onValidate:o,value:l})=>{const c=d=>{if(d.key==="Tab"){d.preventDefault();const u=d.target,{selectionEnd:p,selectionStart:h,value:f}=u,g=h??0,x=p??0,y=`${f.substring(0,g)} ${f.substring(g)}`;u.value=y,u.selectionStart=g+1,u.selectionEnd=x+1}};return a.jsxs(Ct,{sx:{display:"grid",gridTemplateRows:"auto 1fr",rowGap:2,mt:2},children:[a.jsxs(T,{sx:{display:"flex",columnGap:2},children:[a.jsx(re,{color:"secondary",disabled:s,onClick:e,children:"Format JSON"}),o?a.jsxs(a.Fragment,{children:[a.jsx(Dt,{color:"secondary",loading:s,onClick:t,variant:"outlined",size:"small",children:"Validate"}),a.jsx(ig,{isValid:r,type:"Validation"})]}):null]}),a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:"3fr 2fr",columnGap:2,minHeight:0},children:[a.jsx(T,{sx:{overflow:"auto",minWidth:0},children:a.jsx(De,{disabled:s,error:n.type!==null,fullWidth:!0,minRows:10,multiline:!0,onChange:i,onKeyDown:c,value:l})}),a.jsxs(T,{sx:{display:"flex",flexDirection:"column",minHeight:0,minWidth:0},children:[a.jsx(I,{color:"error",variant:"subtitle2",sx:{pb:1},children:Lce(n)}),n.type!==null?a.jsx($ce,{error:n.message}):null]})]})]})},Bce=({initialValue:e,onClose:t,onConfirm:n,onValidate:r,open:s,title:i})=>{const o=ct(),[l,c]=m.useState(e),[d,u]=m.useState(!1),[p,h]=m.useState({type:null}),[f,g]=m.useState(null),x=()=>{o()&&(h({type:null}),g(null),u(!1))},b=()=>{x();const{errorMessage:w,formattedValue:S,parsedValue:E}=Pce(l);return w?(h({message:w,type:"syntax"}),{error:!0,parsedValue:null}):(c(S),{error:!1,parsedValue:E})},y=async()=>{const{error:w,parsedValue:S}=b();if(w||!r)return;u(!0);const{apiErrors:E,otherError:k}=await r(S);o()&&(E||k?(h({message:E||k||"An unknown error occurred",type:"validation"}),g(!1)):g(!0),u(!1))},v=async()=>{const{error:w,parsedValue:S}=b();w||n({isValid:f,parsedValue:S})},C=w=>{w.preventDefault(),h(S=>({...S,isValid:!1})),g(null),c(w.target.value)};return a.jsxs(yt,{fullWidth:!0,maxWidth:"lg",open:s,PaperProps:{sx:{maxHeight:"80vh"}},TransitionProps:{onExited:()=>{x(),o()&&c(e)}},children:[a.jsxs(vt,{component:"h6",sx:{pt:4},children:[i,a.jsx(Ie,{"aria-label":"close",disabled:d,onClick:t,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})})]}),a.jsx(zce,{checkFormatting:b,checkValidity:y,error:p,isValid:f,loading:d,onChange:C,onValidate:r,value:l}),a.jsxs(un,{sx:{px:3,py:2,justifyContent:"flex-end"},children:[a.jsx(re,{color:"secondary",disabled:d,onClick:t,variant:"outlined",children:"Close"}),a.jsx(re,{disabled:d,onClick:v,variant:"contained",children:"Confirm"})]})]})};U.object({input:U.unknown(),loc:U.array(U.union([U.string(),U.number()])),msg:U.string()});const qs=U.record(U.string(),U.unknown()),pl=U.array(qs),Ky=({loading:e=!1,value:t})=>e?a.jsx(fe,{variant:"rounded",sx:{height:28,width:48,borderRadius:2}}):a.jsx(ut,{color:t?"success":"secondary",label:t?"Yes":"No",sx:{height:28,width:48}}),or=({children:e,endIcon:t,title:n,titleSx:r})=>a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{columnGap:1,display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{sx:{fontSize:"18px",fontWeight:600,lineHeight:"22px",mb:2,...r},children:n}),t]}),a.jsx(T,{children:e})]})}),Uce={py:2,px:{xs:8,lg:20},minWidth:600},Ru=({fullPage:e=!1,mainContent:t,sideContent:n})=>a.jsxs($,{sx:{...e?Uce:{},flexDirection:{xs:"column",lg:"row"},gap:3,justifyContent:"center"},children:[a.jsx($,{sx:{width:{xs:"100%",lg:"67%"},maxWidth:e?{xs:"none",lg:700}:"none",gap:3},children:t}),a.jsx($,{sx:{width:{xs:"100%",lg:"33%"},maxWidth:e?{xs:"none",lg:350}:"none",gap:3},children:n})]}),Ox=({field:e,loading:t,value:n})=>a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:e}),a.jsx(Ky,{loading:t,value:n})]}),cn=({field:e,loading:t,sx:n,sxValue:r,tooltipValue:s,value:i})=>a.jsxs(T,{sx:{display:"flex",flexDirection:"row",...n},children:[a.jsxs(I,{sx:{width:200},variant:"body2",color:"text.secondary",children:[e,":"]}
183),t?a.jsx(fe,{variant:"text",sx:{fontSize:14,width:100}}):a.jsx(be,{title:s,children:a.jsx(I,{sx:r,variant:"body2",children:i})})]}),Vce=e=>{switch(e?.toLowerCase()){case"completed":case"success":case"succeeded":return"success";case"running":case"in progress":return"info";case"failed":case"error":return"error";case"pending":case"queued":return"warning";default:return"default"}},Wce=e=>e==="small"?{skeleton:{width:80,height:22},chip:{fontSize:11,height:22,minWidth:64}}:{skeleton:{width:100,height:28},chip:{fontSize:14,height:28,minWidth:100}},Nu=({status:e,size:t="small",isError:n,isLoading:r,onClick:s,sx:i})=>{const o=Vce(e),l=e?Pr(e.toLowerCase()):"-",c=Wce(t);return r?a.jsx(fe,{sx:c.skeleton}):n?a.jsx(I,{variant:"body2",color:"error.main",children:"Error loading status"}):a.jsx(ut,{color:o,label:l,onClick:s,sx:{...c.chip,...i}})},X0=({fullWidth:e})=>a.jsx(T,{sx:{width:"100%"},children:Array.from({length:3}).map((t,n)=>a.jsx(fe,{sx:{fontSize:14,maxWidth:e?"100%":400},variant:"text",width:"100%"},n))}),Jd=({data:e,index:t=0,loading:n})=>n?a.jsx(X0,{}):e?a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:Object.entries(e).map(([r,s])=>a.jsx(cn,{field:KD(r.replaceAll("_"," ")),value:Array.isArray(s)&&s.length&&typeof s[0]=="string"?s.join(", "):typeof s=="object"?JSON.stringify(s,null," "):JSON.stringify(s)},`${t}-${r}`))},t):null,Hce=({data:e,loading:t,placeholder:n="N/A"})=>t?a.jsx(Jd,{loading:!0}):e?a.jsx(T,{sx:{display:"flex",flexDirection:"column"},children:e.map((r,s)=>a.jsx(Jd,{data:r,index:s},s))}):n?a.jsx(T,{children:n}):null,oo=({data:e,index:t=0,loading:n,placeholder:r="N/A",title:s=null})=>{const[i,o]=m.useState(!1),l=n||!e||i,c=m.useCallback(()=>{o(d=>!d)},[]);return a.jsxs(Ka,{sx:{border:"none",boxShadow:"none","&:before":{display:"none"},pointerEvents:e?"auto":"none"},disableGutters:!0,elevation:0,expanded:l,onChange:c,children:[a.jsx(Qa,{sx:{flexDirection:"row-reverse",p:0,".MuiAccordionSummary-content":{my:1}},expandIcon:a.jsx(Mt,{sx:{alignSelf:"center",color:e?"icon.secondary":"icon.disabled",height:24,transform:l?"rotate(-90deg)":"none",width:24},children:a.jsx(yl,{})}),children:a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:a.jsx(I,{variant:"subtitle1",children:s})})}),a.jsx(Ja,{sx:{pt:0},children:a.jsx(Hce,{data:e,loading:n,placeholder:r})})]},t)},qce=40,yL=60,Gce=20,Xd={clickableColumn:"_clickable-column"},Yce=e=>a.jsx(re,{...e,variant:"contained"}),Kce=e=>a.jsx(Br,{sx:{p:2},children:a.jsx(rM,{sx:{".MuiDataGrid-filterForm":{columnGap:2},".MuiDataGrid-panelContent":{pb:1}},...e})}),Qce=yL-8,Jce=()=>a.jsx($,{gap:1,sx:{pt:1},children:Array(Gce).fill(null).map((e,t)=>a.jsx(fe,{height:Qce,variant:"rounded"},t))}),Xce=()=>a.jsx(T,{sx:{display:"flex",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"},children:a.jsx(I,{children:"No data sources found"})}),Zce=rt(Mn)(({theme:e})=>{const{palette:t}=e,{background:n,border:r,text:s}=t;return{border:"none",width:"100%",[`& .${xe.main}`]:{borderRadius:"6px"},[`& .${xe.columnHeaders}`]:{backgroundColor:n.tableHeader},[`& .${xe.columnHeader}`]:{fontSize:12,height:18,textTransform:"uppercase",color:s.secondary},[`& .${xe.columnHeader}.wrap-header`]:{"& .MuiDataGrid-columnHeaderTitle":{lineHeight:1.2,overflow:"visible",textOverflow:"clip",whiteSpace:"normal",wordWrap:"break-word"}},[`& .${xe.columnHeaderCheckbox}`]:{paddingLeft:0,paddingRight:0},[`& .${xe.columnSeparator}`]:{color:r.default,":hover":{color:r.default}},[`& .${xe.row}:nth-of-type(odd)`]:{backgroundColor:n.paper,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.brand.subtlest.default}},[`& .${xe.row}:nth-of-type(even)`]:{backgroundColor:t.surface.tertiary,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.neutral.hovered}},[`& .${xe.cell}`]:{border:"none"},[`& .${Xd.clickableColumn}`]:{cursor:"pointer"},[` 184 & .${xe.cell}:focus, 185 & .${xe.cell}:focus-within, 186 & .${xe.columnHeader}:focus, 187 & .${xe.columnHeader}:focus-within 188 `]:{outline:"none"},"& .MuiTablePagination-selectLabel":{fontWeight:500,letterSpacing:.5,lineHeight:"20px",fontSize:12,color:s.secondary},"& .MuiTablePagination-input":{fontWeight:500,letterSpacing:.5,lineHeight:"20px",fontSize:12}}}),ag=({containerSx:e,hideFooter:t=!0,slots:n,...r})=>a.jsx(T,{sx:{width:"100%",...e},children:a.jsx(Zce,{autoHeight:!0,columnHeaderHeight:qce,disableColumnPinning:!0,disableColumnSelector:!0,hideFooter:t,rowHeight:yL,slots:{baseButton:Yce,filterPanel:Kce,loadingOverlay:Jce,noRowsOverlay:Xce,...n},...r})}),vL=({status:e})=>{const t=B0(e).chipColor;return a.jsx(ut,{color:t,label:e??"-"})},t_=({required:e})=>a.jsxs(I,{children:["No Values ",e?" *":null]}),ede=({required:e,value:t})=>{const n=pl.safeParse(t);if(n.success)return n.data.length?a.jsx($,{sx:{maxHeight:800,overflowY:"auto"},children:n.data.map((s,i)=>a.jsx(oo,{data:[s],index:`header-${i}`,title:z0(s)},i))}):a.jsx(t_,{required:e});const r=qs.safeParse(t);return r.success?Object.keys(r.data).length?a.jsx(Jd,{data:r.data}):a.jsx(t_,{required:e}):null},Z0=({defaultValue:e={},fieldName:t,onClose:n,onConfirm:r,onValidate:s,open:i,required:o,schema:l,title:c})=>{const{control:d}=An(),u=s?async p=>{const h=l.safeParse(p);return h.success?s(h.data):{apiErrors:null,otherError:h.error.issues?.[0]?.message||h.error.message}}:void 0;
188return a.jsx(Et,{control:d,name:t,render:({field:{onChange:p,value:h},fieldState:{error:f}})=>a.jsxs(Qe,{fullWidth:!0,children:[a.jsx(Bce,{initialValue:JSON.stringify(h??e,null,4),onClose:n,onConfirm:({isValid:g,parsedValue:x})=>{p(x),r({isValid:g})},onValidate:u,open:i,title:c}),a.jsx(ede,{required:o,value:h}),a.jsx(Zn,{error:!0,children:f?.message||" "})]})})},Qy=({defaultValue:e,disabled:t=!1,fieldName:n,label:r,onChange:s=()=>{},options:i,required:o})=>{const{control:l}=on(),{isSubmitting:c}=tn().state;return a.jsx(Et,{control:l,name:n,defaultValue:e,render:({field:{value:d,onBlur:u,onChange:p},fieldState:{error:h}})=>a.jsxs(Qe,{disabled:c||t,error:!!h,fullWidth:!0,required:o,variant:"filled",children:[a.jsx(wt,{error:!!h,children:r}),a.jsx(tt,{error:!!h,label:r,onBlur:u,onChange:f=>{const{value:g}=f.target;p(g),s(g)},required:o,value:d??"",children:i.map(f=>a.jsx(Se,{value:f.value,children:f.label},f.value))}),a.jsx(Zn,{error:!!h,children:h?.message||" "})]})})},Qo=({fieldName:e,fullWidth:t,icon:n,label:r,onChange:s=()=>{}})=>{const{control:i}=An(),{isSubmitting:o}=tn().state;return a.jsx(Et,{control:i,name:e,render:({field:{onBlur:l,onChange:c,value:d}})=>a.jsxs(T,{sx:{display:"flex",alignItems:"center",width:t?"100%":"auto",justifyContent:t?"space-between":"flex-start",height:24},children:[a.jsxs(T,{sx:{columnGap:1,display:"flex",width:200,alignItems:"center"},children:[a.jsx(ID,{children:r}),n]}),a.jsx(Dn,{checked:!!d,disabled:o,onBlur:l,onChange:u=>{const{checked:p}=u.currentTarget;c(p),s(p)},size:"small"})]})})},ir=({defaultValue:e="",disabled:t,fieldName:n,InputProps:r,isValidating:s,label:i,maxRows:o,minRows:l,multiline:c,onBlur:d=()=>{},onChange:u=()=>{},required:p=!1})=>{const{control:h}=An(),{isSubmitting:f}=tn().state;return a.jsx(Et,{control:h,defaultValue:e,name:n,render:({field:{onBlur:g,onChange:x,ref:b,value:y},fieldState:{error:v}})=>a.jsx(De,{disabled:f||t,error:!!v,fullWidth:!0,helperText:s?a.jsx(Ze,{size:13}):v?.message||" ",InputProps:r,inputRef:b,label:i,maxRows:o,minRows:l,multiline:c,onBlur:C=>{g(),d(C.target.value||"")},onChange:C=>{x(C.target.value||""),u(C.target.value||"")},required:p,value:y??""})})},tde=({children:e,error:t,label:n,required:r})=>{if(!n)return e;const s=r?`${n} *`:n;return a.jsxs($,{children:[a.jsxs($,{sx:{flexDirection:"row",alignItems:"center",columnGap:2},children:[a.jsx(ID,{error:!!t,children:s}),e]}),a.jsx(Zn,{error:!!t,children:t||" "})]})},CL=({defaultValue:e=null,disabled:t,exclusive:n=!1,fieldName:r,label:s,options:i,required:o,size:l})=>{const{control:c}=An(),{isSubmitting:d}=tn().state;return a.jsx(Et,{control:c,name:r,render:({field:{onBlur:u,onChange:p,value:h},fieldState:{error:f}})=>a.jsx(tde,{error:f?.message,label:s,required:o,children:a.jsx(ml,{color:"primary",disabled:d||t,exclusive:n,onBlur:u,onChange:(g,x)=>{p(x??e??"")},size:l,value:h??e,children:i.map(g=>a.jsx(yi,{value:g.value,children:g.label},g.value))})})})},ew=({defaultValue:e,dialogTitle:t,endIcon:n,fieldName:r,onConfirm:s,onValidate:i,schema:o,title:l})=>{const[c,d]=m.useState(!1),{isSubmitting:u}=tn().state;return a.jsxs(a.Fragment,{children:[a.jsx(St,{sx:{mt:2,mb:3}}),a.jsxs($,{sx:{flexDirection:"row",justifyContent:"space-between",height:32},children:[a.jsx(I,{variant:"subtitle1",children:l}),a.jsxs(T,{sx:{display:"flex",columnGap:2,alignItems:"center"},children:[n,a.jsx(re,{color:"secondary",disabled:u,onClick:()=>{d(!0)},sx:{height:30},size:"small",children:"Edit JSON"})]})]}),a.jsx(Z0,{defaultValue:e,fieldName:r,onClose:()=>{d(!1)},onConfirm:({isValid:p})=>{d(!1),s&&s({isValid:p})},onValidate:i,open:c,schema:o,title:t})]})},Px=({label:e,tooltip:t,value:n="-"})=>a.jsx(be,{title:t||`${e} cannot be changed after creation`,children:a.jsxs($,{sx:{rowGap:.5,cursor:"help",alignItems:"center"},tabIndex:0,children:[a.jsxs($,{sx:{flexDirection:"row",alignItems:"center",columnGap:.5},children:[a.jsx(I,{sx:{fontSize:14,fontWeight:600},children:e}),a.jsx(Si,{size:16})]}),a.jsx(I,{sx:{fontSize:14},children:n})]})}),nde=({disabled:e,loading:t,onClick:n,status:r})=>{const{isSubmitting:s}=tn().state;return a.jsx(tR,{status:r,statusText:"Connection",buttonText:"Test Connection",onClick:n,disabled:s||e,loading:t,size:"small",sx:{height:30,mb:1}})},rde=["executionSteps","fileConfig","headers"],sde={executionSteps:"execution_steps",fileConfig:"file_config",headers:"header_json"},ide="One or more fields are missing or invalid. The data source cannot be activated until those fields are corrected.",ade="One or more fields have an invali
188d configuration. The data source cannot be activated until those fields are corrected.",ode=({handleSaveAsInactive:e})=>{const{dispatch:t}=Je(),{dispatch:n,handleSubmit:r,state:s}=tn(),{errorDialog:i,saveChangesDialogOpen:o}=s,l=()=>{n({type:"saveChangesDialogOpen",value:!1}),t({type:"nextView",value:null})},c=async()=>{await r(),l()};return a.jsxs(a.Fragment,{children:[a.jsx(mt,{acceptLabel:"Save Changes",bodyText:"You have unsaved data. Would you like to save your changes or continue editing?",closeLabel:"Continue Editing",handleClose:l,handleAccept:c,open:o,title:"Save Changes?"}),a.jsx(mt,{acceptLabel:"Save as Inactive",bodyText:i==="incomplete"?ide:ade,closeLabel:"Continue Editing",handleAccept:e,handleClose:()=>{n({type:"errorDialog",value:null})},open:!!i,title:i==="incomplete"?"Incomplete Configuration":"Validation Error"})]})},tw=/^[A-Za-z0-9]+$/,Us=U.string().min(1,{message:"Required"}),n_=U.number({invalid_type_error:"Required"});pl.refine(e=>e.length,{message:"Required"});Us.regex(tw,{message:"Alphanumeric characters only"});const Jf=e=>`Must be at most ${e} characters`,lde="table",cde=({required:e})=>U.discriminatedUnion("type",[U.object({type:U.literal("query"),query:e?Us:U.string()}),U.object({type:U.literal("table"),table:e?Us:U.string()})]).default({type:lde,table:""}),wL=({required:e})=>U.object({connectionId:U.number().nullish().default(null),dateFieldName:U.string().nullable(),filterClause:U.string().nullable(),queryOrTable:cde({required:e})}),dde=({required:e})=>wL({required:e}).merge(U.object({type:U.literal("bigquery"),dataset:e?Us:U.string(),project:e?Us:U.string()})),ude=({required:e})=>wL({required:e}).merge(U.object({type:U.literal("snowflake"),database:e?Us:U.string(),schema:e?Us:U.string(),warehouse:e?Us:U.string()})),pde=({required:e})=>U.object({type:U.literal("api"),apiConfig:qs.default({}),apiSecret:e?Us:U.string()}),hde=({required:e})=>U.object({type:U.literal("s3"),bucket:U.string().superRefine((t,n)=>t?t.split("").includes("/")?(n.addIssue({code:U.ZodIssueCode.custom,message:'"/" is not permitted',fatal:!0}),U.NEVER):t:e?(n.addIssue({code:U.ZodIssueCode.custom,message:"Required",fatal:!0}),U.NEVER):t),fileFilter:U.string().nullable(),path:U.string().refine(t=>t?t.endsWith("/"):!e,{message:'Must end with "/"'})}),fde=()=>U.object({type:U.enum(["amazonads","cm360","dv360","googleads","ga4","sftp","sa360","fbinsights","pinterestads","redditads","linkedinads","tiktokmarketing","tiktokorganic","gsc"]),apiConfig:qs.default({}),connectionId:U.number().nullish().default(null)}),SL=({required:e=!1})=>U.discriminatedUnion("type",[dde({required:e}),pde({required:e}),ude({required:e}),hde({required:e}),fde()]),mde=SL({required:!1}),jL=SL({required:!0}),gde=U.object({type:U.union([U.literal(Tr.type.custom),U.literal(Tr.type.full),U.literal(Tr.type.none)]),attributes:U.array(U.string()).optional(),placements:U.boolean().optional(),creatives:U.boolean().optional(),brand:U.boolean().optional()}),xde=U.discriminatedUnion("type",[U.object({type:U.literal("daily"),offset:U.literal(0).default(0)}),U.object({type:U.literal("weekly"),offset:n_}),U.object({type:U.literal("monthly"),offset:n_})]),kL=({required:e})=>U.string().superRefine((t,n)=>t?t.startsWith(".")?t.length<2?(n.addIssue({code:U.ZodIssueCode.too_small,fatal:!0,inclusive:!0,message:"Must contain at least 2 characters",minimum:2,type:"string"}),U.NEVER):/^.[A-Za-z0-9]+$/.test(t)?t.length>10?(n.addIssue({code:U.ZodIssueCode.too_big,fatal:!0,inclusive:!0,maximum:10,message:Jf(10),type:"string"}),U.NEVER):t:(n.addIssue({code:U.ZodIssueCode.custom,message:'Except for the starting ".", must contain only alphanumeric characters',fatal:!0}),U.NEVER):(n.addIssue({code:U.ZodIssueCode.custom,message:'Must start with "."',fatal:!0}),U.NEVER):e?(n.addIssue({code:U.ZodIssueCode.custom,message:"Required",fatal:!0}),U.NEVER):t),EL=({required:e})=>e?Us.max(5,{message:Jf(5)}):U.string().max(5,{message:Jf(5)}),bde=U.object({deviceResolution:U.string().nullish(),personResolution:U.string().nullish()}),_L=U.object({contacts:U.array(uU).default([]),diConfig:qs,eventsJson:bde.nullish(),executionSteps:pl,fileCompression:U.string().max(10,{message:Jf(10)}).nullish(),fileConfig:qs,frequency:xde,headers:pl,name:U.string().nullish(),nameCleaning:gde,notes:U.string().nullish(),schedule:U.boolean(),verify:U.boolean()}),yde=_L.extend({active:U.literal(!0),connector:jL,fileDelimiter:EL({required:!0}),fileExtension:kL({required:!0})}),vde=_L.extend({active:U.literal(!1),connector:mde,fileDelimiter:EL({required:!1}),fileExtension:kL({required:!1})}),Cde=U.discriminatedUnion("active",[yde,vde]),TL={apiValidation:{executionSteps:null,fileConfig:null,headers:null},errorDialog:null,isSubmitting:!1,saveChangesDialogOpen:!1},wde=(e,t)=>
188{switch(t.type){case"resetApiValidation":return{...e,apiValidation:{executionSteps:null,fileConfig:null,headers:null}};case"apiValidationField":return{...e,apiValidation:{...e.apiValidation,[t.field]:t.value}};case"resetAll":return ZG(TL);default:return t.type in e?{...e,[t.type]:t.value}:e}},r_=tA,Sde={executionSteps:"One or more data processing steps are invalid",fileConfig:"The file configuration is invalid",headers:"One or more header mapping transformations are invalid"},jde=({children:e})=>{const t=ct(),{pushNotification:n}=jt(),{handleUpdateDataSource:r,navigateToTab:s,state:i}=Je(),{nextView:o,selectedDataSource:l}=i,{engagementName:c,engagementNiceId:d}=pe(),[u,p]=m.useReducer(wde,TL),h=Xs({mode:"onChange",resolver:Zs(Cde),defaultValues:Rx({source:null})}),{getValues:f,reset:g,setError:x,setValue:b,trigger:y}=h,v=Rce({engagementNiceId:d,environment:r_}),C=wce(),w=m.useCallback(async M=>{if(!l)return;p({type:"isSubmitting",value:!0});const N=await r({dataSourceId:l.id,formValues:M,previousDataSource:l});if(t()){if(p({type:"isSubmitting",value:!1}),N.error!==null)x("root",{message:N.error,type:"manual"}),n({content:N.error,severity:"error"});else if(o)if(Tn(Hf,o))s({nextSource:null,nextView:o});else if(Tn(Gf,o)){const O=N.updatedSource;s({nextSource:O,nextView:o})}else o==="dataOrchestration"&&s({nextSource:{...l},nextView:o})}},[l,r,t,s,o,n,x]),S=m.useCallback(M=>{n({content:Sde[M],severity:"error"})},[n]),E=m.useCallback(async M=>{const N=rde.map(R=>{const L=u.apiValidation[R];return L!==null?(L||S(R),L):C({data:M[R],validationField:sde[R]}).then(({apiErrors:P,otherError:F})=>{const z=!(P||F);return t()&&(z||S(R),p({type:"apiValidationField",field:R,value:z})),z})});return(await Promise.all(N)).every(R=>R)},[t,S,u.apiValidation,C]),k=m.useCallback(async({formValues:M}={})=>{p({type:"isSubmitting",value:!0});const N=M||f();if(N.active){if(!await y()){t()&&(p({type:"errorDialog",value:"incomplete"}),p({type:"isSubmitting",value:!1}));return}if(!await E(N)){t()&&(p({type:"errorDialog",value:"validation"}),p({type:"isSubmitting",value:!1}));return}}await w(N)},[E,f,t,w,y]),j=m.useCallback(async()=>{p({type:"errorDialog",value:null});const M=f();b("active",!1),k({formValues:{...M,active:!1}})},[f,k,b]),_=m.useCallback(()=>{g(Rx({source:l}),{keepDirty:!1})},[l,g]);m.useEffect(()=>{g(Rx({source:l}),{keepDirty:!1})},[l]);const D=m.useMemo(()=>({connection:v,dispatch:p,engagementName:c,engagementNiceId:d,environment:r_,handleSubmit:k,resetChanges:_,state:u,validateField:C}),[v,c,d,k,_,u,C]);return a.jsx(fL.Provider,{value:D,children:a.jsxs(Js,{...h,children:[e,a.jsx(ode,{handleSaveAsInactive:j})]})})},Jy=e=>e.sort((t,n)=>t.name.localeCompare(n.name)),Xf=({contacts:e,internal:t})=>e.filter(({is_internal:n})=>n===t),kde=({contacts:e,internal:t})=>Jy(Xf({contacts:e,internal:t})),s_=({internal:e,labelName:t})=>{const{allContacts:n,contactsLoading:r}=Je(),{state:s}=tn(),{setValue:i,watch:o}=An(),l=o("contacts"),c=m.useMemo(()=>kde({contacts:n,internal:e}),[n,e]),d=m.useMemo(()=>Xf({internal:e,contacts:l}),[l,e]),u=m.useCallback((p,h)=>{const g=[...Xf({internal:!e,contacts:l}),...h];i("contacts",g,{shouldDirty:!0,shouldTouch:!0})},[l,e,i]);return a.jsx(gl,{disableClearable:!0,disabled:s.isSubmitting,filterSelectedOptions:!0,getOptionKey:p=>p.id,getOptionLabel:p=>p.name,isOptionEqualToValue:(p,h)=>p.id===h.id,loading:r,multiple:!0,noOptionsText:"No contacts found",onChange:u,options:c,renderInput:p=>a.jsx(De,{...p,label:`Search ${t} Contacts`}),renderTags:()=>null,value:d})},Lx=({children:e,color:t,disabled:n,onClick:r,title:s})=>a.jsx(be,{title:n?"":s,children:a.jsx(Ie,{disabled:n,disableRipple:!0,onClick:r,sx:{color:t},children:a.jsx("span",{children:e})})}),Ede=({contact:e})=>{const{getValues:t,setValue:n}=An(),{userIsInternal:r}=Je(),{isSubmitting:s}=tn().state,{id:i,is_internal:o,is_primary:l,is_private:c,name:d}=e,u=o&&r,p=r||!o,h=m.useCallback(()=>{const b=t("contacts").map(y=>y.id===i?{...y,is_private:!c}:y);n("contacts",b,{shouldDirty:!0,shouldTouch:!0})},[t,i,c,n]),f=m.useCallback(()=>
188{const x=!l,y=t("contacts").map(v=>({...v,is_primary:x?v.id===i:!1}));n("contacts",y,{shouldDirty:!0,shouldTouch:!0})},[t,i,l,n]),g=m.useCallback(()=>{const b=t("contacts").filter(y=>y.id!==i);n("contacts",b,{shouldDirty:!0,shouldTouch:!0})},[t,i,n]);return a.jsxs(T,{sx:{alignItems:"center",display:"grid",gridTemplateColumns:"auto repeat(3, 32px)",gridTemplateRows:"1fr",pl:1,borderRadius:1,minHeight:40,":hover":{backgroundColor:"action.hover"}},children:[a.jsx(I,{variant:"body2",sx:{overflowX:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:d}),u?a.jsx(Lx,{color:c?"icon.secondary":"icon.brand.main",disabled:s||l,onClick:h,title:`Make user ${c?"public":"private"}`,children:c?a.jsx(pU,{fontSize:"small"}):a.jsx(hU,{fontSize:"small"})}):a.jsx(T,{}),a.jsx(Lx,{color:l?"icon.brand.main":"icon.secondary",disabled:s||c,onClick:f,title:l?"Primary contact":"Set as primary contact",children:l?a.jsx(nA,{}):a.jsx(fU,{})}),p?a.jsx(Lx,{color:"secondary",disabled:s,onClick:g,title:"Remove assigned contact",children:a.jsx(mU,{fontSize:"small"})}):a.jsx(T,{})]})},Fx=({internal:e})=>{const{userId:t,userIsInternal:n}=Je(),{watch:r}=An(),s=r("contacts"),i=m.useMemo(()=>{const o=Xf({internal:e,contacts:s});return Jy(n?o:o.filter(l=>l.id===t||!l.is_private))},[e,s,t,n]);return a.jsx(a.Fragment,{children:i.map(o=>a.jsx(Ede,{contact:o},o.id))})},_de=()=>{const{userIsInternal:e}=Je(),{engagementName:t}=tn();return a.jsx(or,{title:hr.assignedContacts,titleSx:{mb:1},children:a.jsxs($,{rowGap:2,children:[a.jsx(I,{variant:"body2",color:"icon.secondary",children:"Who should we contact if something goes wrong?"}),e&&a.jsxs(a.Fragment,{children:[a.jsx(s_,{internal:!0,labelName:"Internal"}),a.jsx($,{children:a.jsx(Fx,{internal:!0})})]}),a.jsx(s_,{internal:!1,labelName:e?t:""}),a.jsxs($,{children:[!e&&a.jsx(Fx,{internal:!0}),a.jsx(Fx,{internal:!1})]})]})})},IL=()=>{const{isValidating:e}=tn().connection;return a.jsx(ir,{disabled:e,fieldName:"connector.dateFieldName",InputProps:{startAdornment:a.jsx(Bn,{position:"start",children:a.jsx(be,{placement:"bottom-start",title:"This field is used for filtering data based on the frequency/offset and the partition_date being ingested.",children:a.jsx(aa,{color:"secondary"})})})},label:"Date Field Name"})},Tde=[{label:"Table",value:"table"},{label:"Query",value:"query"}],DL=()=>{const{isValidating:e}=tn().connection,{watch:t}=An(),n=t("connector.queryOrTable.type");return a.jsxs(a.Fragment,{children:[a.jsx(T,{sx:{pb:1},children:a.jsx(CL,{disabled:e,exclusive:!0,fieldName:"connector.queryOrTable.type",options:Tde})}),a.jsx(Yt,{in:n==="table",children:a.jsx(ir,{disabled:e,fieldName:"connector.queryOrTable.table",label:"Table Name",required:!0})}),a.jsx(Yt,{in:n==="query",children:a.jsx(ir,{disabled:e,fieldName:"connector.queryOrTable.query",label:"Query to Pull Data",maxRows:10,multiline:!0,required:!0})})]})},Ide=()=>{const{isValidating:e}=tn().connection,{watch:t}=An(),n=t("connector.type")==="bigquery";return a.jsx(Yt,{in:n,children:a.jsxs($,{rowGap:1,children:[a.jsx(ir,{disabled:e,fieldName:"connector.project",label:"Project Id",required:!0}),a.jsx(ir,{disabled:e,fieldName:"connector.dataset",label:"Dataset Name",required:!0}),a.jsx(DL,{}),a.jsx(IL,{}),a.jsx(ir,{disabled:e,fieldName:"connector.filterClause",label:"Filter Condition"})]})})},Dde="There are no available connections for the selected connector type",Ade=()=>{const{control:e,watch:t}=An(),{availableConnections:n,connectionsLoading:r,connectors:s}=Je(),{state:{isSubmitting:i}}=tn(),o=t("connector.type"),l=m.useMemo(()=>s.find(({niceId:p})=>p===o),[s,o]),c=m.useMemo(()=>n.filter(({connectorName:p})=>p===l?.name),[n,l]),d=c.length===0;if(l?.diProcess!=="connector"&&l?.diProcess!=="glue")return null;const u=r||d||i;return a.jsx(Et,{control:e,name:"connector.connectionId",render:({field:p,fieldState:{error:h}})=>a.jsx(Nt,{isLoading:r,width:"100%",children:a.jsxs(Qe,{disabled:u,error:!!h,fullWidth:!0,required:!0,variant:"filled",children:[a.jsx(wt,{error:!!h,required:!0,children:"Connection"}),a.jsx(tt,{disabled:u,labelId:"connection-selector-label",onBlur:p.onBlur,onChange:f=>p.onChange(f.target.value),renderValue:f=>c.find(x=>x.id===f)?.name||"",value:p.value||"",children:c.map(f=>a.jsx(Se,{value:f.id,children:f.name},f.id))}),a.jsx(Zn,{error:!!h||d,children:d?Dde:h?.message||" "})]})})})},Mde=()=>{const{connectors:e,connectorsLoading:t}=Je(),{control:n,setValue:r}=An(),{isSubmitting:s}=tn().state,i=m.useMemo(()=>e.filter(l=>l.active).toSorted((l,c)=>l.niceId==="api"?1:c.niceId==="api"?-1:l.name.localeCompare(c.name)),[e]),o=t||i.length===0||s;return a.jsx(Et,{control:n,name:"connector.type",render:({field:{onBlur:l,onChange:c,value:d},fieldState:{error:u}})=>a.jsx(Nt,{isLoading:t,width:"100%",children:a.jsxs(Qe,{disabled:o,error:!!u,fullWidth:!0,required:!0,variant:"filled",children:[a.jsx(wt,{error:!!u,required:!0,children:Ge.delivery_method}),a.jsx(tt,{disabled:o,onBlur:l,onChange:p=>{const h=p.target.value;h&&h!==d&&(r("connector.apiConfig",{},{shouldDirty:!0,shouldTouch:!0}),r("connector.connectionId",null,{shouldDirty:!0,shouldTouch:!0}),!["snowflake","bigquery"].includes(d)&&["snowflake","bigquery"].includes(h)&&r("connector.queryOrTable.type","table"),c(p.target.value))},renderValue:p=>{const h=i.find(f=>f.niceId===p);return h?a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[h.logoUrl&&a.jsx(T,{sx:{mr:1},children:a.jsx(sa,{src:h.logoUrl})}),a.jsx("span",{children:h.name})]}):""},value:d||"",children:i.map(p=>a.jsx(Se,{value:p.niceId,children:a.jsxs(T,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(sa,{src:p.logoUrl}),a.jsx("span",{children:p.name})]})},p.id))}),a.jsx(Zn,{error:!!u,children:u?.message||" "})]})})})},Rde=()=>{const{watch:e}=An(),{state:{isSubmitting:t}}=tn(),{connectors:n}=Je(),r=e("connector.type"),s=n.find(({niceId:i})=>i===r);return s?.diProcess!=="connector"?null:a.jsx(FC,{disabled:t,validating:t,fields:s.globalConfig,parentField:"connector.apiConfig"})},Nde=()=>{const{watch:e}=An(),t=e("connector.type")==="api";return a.jsx(Yt,{in:t,children:a.jsxs($,{rowGap:1,children:[a.jsx(ir,{fieldName:"
188connector.apiSecret",label:Ge.api_secret,required:!0}),a.jsx(ew,{defaultValue:{},dialogTitle:"Edit API Config JSON",fieldName:"connector.apiConfig",schema:qs,title:Ge.api_config})]})})},Ode=()=>{const{watch:e}=An(),t=e("connector.type")==="s3",{connection:{isValidating:n}}=tn();return a.jsx(Yt,{in:t,children:a.jsxs($,{rowGap:1,children:[a.jsx(ir,{disabled:n,fieldName:"connector.bucket",label:Ge.s3_bucket,required:!0}),a.jsx(ir,{disabled:n,fieldName:"connector.path",label:"Path",required:!0}),a.jsx(ir,{fieldName:"connector.fileFilter",InputProps:{startAdornment:a.jsx(Bn,{position:"start",children:a.jsx(be,{title:`${Ge.file_filter} is required if not using file_regex in file configuration`,children:a.jsx(aa,{color:"secondary"})})})},label:Ge.file_filter})]})})},Pde=()=>{const{isValidating:e}=tn().connection,{watch:t}=An(),n=t("connector.type")==="snowflake";return a.jsx(Yt,{in:n,children:a.jsxs($,{rowGap:1,children:[a.jsx(ir,{disabled:e,fieldName:"connector.database",label:"Database Name",required:!0}),a.jsx(ir,{disabled:e,fieldName:"connector.schema",label:"Schema Name",required:!0}),a.jsx(ir,{disabled:e,fieldName:"connector.warehouse",label:"Warehouse Name",required:!0}),a.jsx(DL,{}),a.jsx(IL,{}),a.jsx(ir,{disabled:e,fieldName:"connector.filterClause",label:"Filter Condition"})]})})},Lde=()=>{const{connectors:e}=Je(),{isValidating:t,resetStatus:n,status:r,validate:s}=tn().connection,{watch:i}=An(),o=i("connector.type"),l=i("connector"),c=JSON.stringify(l),d=m.useMemo(()=>{try{return jL.parse(l),!0}catch{return!1}},[c]),p=e?.find(h=>h.niceId===o)?.diProcess==="glue";return m.useEffect(()=>{r&&n()},[c]),a.jsxs(or,{endIcon:o!=="api"&&p&&a.jsx(nde,{disabled:!d,loading:t,onClick:()=>s(l),status:r}),title:hr.connector,children:[a.jsx(Mde,{}),a.jsx(Ade,{}),a.jsx(Ide,{}),a.jsx(Nde,{}),a.jsx(Pde,{}),a.jsx(Ode,{}),a.jsx(Rde,{})]})},Fde=()=>a.jsx(or,{title:"Data Ingestion Configuration",children:a.jsx(ew,{defaultValue:{},dialogTitle:"Edit DI Config JSON",fieldName:"diConfig",schema:qs,title:Ge.di_config})}),$de=()=>{const{dispatch:e,validateField:t,state:n}=tn(),[r,s]=m.useState(!1),i=m.useMemo(()=>a.jsxs(T,{sx:{display:"flex",columnGap:2,alignItems:"center"},children:[a.jsx(ig,{isValid:n.apiValidation.executionSteps,type:"Validation"}),a.jsx(re,{color:"secondary",disabled:n.isSubmitting,onClick:()=>{s(!0)},sx:{height:30},size:"small",children:"Edit JSON"})]}),[n.apiValidation.executionSteps,n.isSubmitting]);return a.jsxs(or,{endIcon:i,title:hr.dataProcessing,children:[a.jsx(Z0,{fieldName:"executionSteps",onClose:()=>{s(!1)},onConfirm:({isValid:o})=>{e({type:"apiValidationField",field:"executionSteps",value:o}),s(!1)},onValidate:o=>t({validationField:"execution_steps",data:o}),open:r,schema:pl,title:"Edit Execution Steps JSON"}),a.jsx(St,{sx:{mt:2,mb:3}}),a.jsxs($,{rowGap:1,children:[a.jsx(I,{sx:{mb:2},variant:"subtitle1",children:"Event Resolution"}),a.jsx(ir,{fieldName:"eventsJson.deviceResolution",label:"Device Resolution"}),a.jsx(ir,{fieldName:"eventsJson.personResolution",label:"Person Resolution"})]})]})},zde=wie.map(e=>({label:e,value:e})),Bde=Sie.map(e=>({label:e||"None",value:e})),Ude=Object.entries(jie).map(([e,t])=>({label:t,value:e})),Vde=()=>{const{dispatch:e,validateField:t,state:n}=tn();return a.jsx(or,{title:hr.file,children:a.jsxs($,{rowGap:1,children:[a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:{xs:"1fr",sm:"1fr 1fr 1fr"},gap:1},children:[a.jsx(e_,{fieldName:"fileExtension",freeSolo:!0,label:Ge.file_extension,options:zde,required:!0}),a.jsx(Qy,{fieldName:"fileCompression",label:Ge.file_compression,options:Bde}),a.jsx(e_,{fieldName:"fileDelimiter",freeSolo:!0,label:Ge.file_delimiter,options:Ude,required:!0})]}),a.jsx(ew,{dialogTitle:"Edit File Config JSON",endIcon:a.jsx(ig,{isValid:n.apiValidation.fileConfig,type:"Validation"}),fieldName:"fileConfig",onConfirm:({isValid:r})=>{e({type:"apiValidationField",field:"fileConfig",value:r})},onValidate:r=>t({validationField:"file_config",data:r}),schema:qs,title:Ge.file_config})]})})},Wde=()=>{const{selectedDataSource:e}=Je().state,t=J0({contentType:e?.content_type,measurementCategory:e?.measurement_category}),n=e?.vendor_nice_id,r=e?.feed_nice_id;return a.jsx(or,{title:hr.general,children:a.jsxs($,{rowGap:1,children:[a.jsx(ir,{fieldName:"name",label:"Data Source Name"}),a.jsxs($,{sx:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:1,width:"100%"},children:[a.jsx(Px,{label:"Content Type",value:t}),a.jsx(Px,{label:"Vendor",value:n}),a.jsx(Px,{label:"Feed",value:r})]})]})})},Hde=()=>{const{dispatch:e,validateField:t,state:n}=tn(),[r,s]=m.useState(!1),i=m.useMemo(()=>a.jsxs(T,{sx:{display:"flex",columnGap:2,alignItems:"center"},children:[a.jsx(ig,{isValid:n.apiValidation.headers,type:"Validation"}),a.jsx(re,{color:"secondary",disabled:n.isSubmitting,onClick:()=>{s(!0)},sx:{height:30},size:"small",children:"Edit JSON"})]}),[n.apiValidation.headers,n.isSubmitting]);return a.jsx(or,{endIcon:i,title:hr.headers,children:a.jsx(Z0,{fieldName:"headers",onClose:()=>{s(!1)},onConfirm:({isValid:o})=>{e({type:"apiValidationField",field:"headers",value:o}),s(!1)},open:r,onValidate:o=>t({validationField:"header_json",data:o}),schema:pl,title:"Edit Headers JSON"})})},AL="Cleaning placements requires cleaning all attributes",i_="_selectAll",{glAttributes:$x}=Tr,qde=({disabled:e})=>{const{control:t}=An(),{isSubmitting:n}=tn().state;return a.jsx(Et,{control:t,name:"nameCleaning.attributes",render:({field:{onBlur:r,onChange:s,value:i=[]}})=>{const o=i.length===$x.length;return a.jsx(be,{title:e?AL:"",children:a.jsxs(Qe,{disabled:n||e,children:[a.jsx(wt,{sx:{"&.MuiInputLabel-shrink":{backgroundColor:"white",px:.5}},children:"Attributes to Clean"}),a.jsxs(tt,{disabled:n||e,multiple:!0,onBlur:r,onChange:l=>{const c=l.target.value,d=typeof c=="string"?c.split(","):c;let u=d;d.includes(i_)&&(u=o?[]:[...$x]),s(u)},renderValue:()=>i.length?o?"All Attributes":i.map(l=>Pr(l)).join(", "):"",sx:{width:"100%"},value:i,children:[a.jsxs(Se,{className:o?"Mui-selected":"",sx:{height:48},value:i_,children:[a.jsx(et,{checked:o,indeterminate:!!i?.length&&!o}),a.jsx(Kt,{primary:"Select All"})]}),a.jsx(St,{}),$x.map(l=>a.jsxs(Se,{value:l,sx:{height:48},children:[a.jsx(et,{checked:!!i?.includes(l)}),a.jsx(Kt,{primary:Pr(l)})]},l))]})]})})}})},{glAttributes:Gde,type:_d}=Tr,Yde=[{label:"None",value:_d.none},{label:"Full",value:_d.full},{label:"Custom",value:_d.custom}],Kde=()=>a.jsx(be,{title:AL,children:a.jsx(aa,{color:"secondary"})}),Qde=()=>{const{setValue:e,watch:t}=An(),n=t("nameCleaning.type")===_d.custom,r=!!t("nameCleaning.placements");return a.jsx(or,{title:hr.nameCleaning,children:a.jsxs($,{rowGap:2,children:[a.jsx(CL,{defaultValue:_d.none,exclusive:!0,fieldName:"nameCleaning.type",options:Yde}),a.jsx(Yt,{in:n,children:a.jsxs($,{sx:{pl:4,pt:1,rowGap:2},children:[a.jsx(qde,{disabled:r}),a.jsx(Qo,{fieldName:"nameCleaning.placements",icon:a.jsx(Kde,{}),label:"Placements",onChange:s=>{s&&e("nameCleaning.attributes",[...Gde])}}),a.jsx(Qo,{fieldName:"nameCleaning.creatives",label:"Creatives"}),a.jsx(Qo,{fieldName:"nameCleaning.brand",label:"Brand"})]})})]})})},Jde=()=>{const{clearErrors:e,setValue:t,watch:n}=An(),r=n("frequency.type"),s=m.useMemo(()=>{switch(r){case"weekly":return["Monday","Tuesday","Wednesday","Thursday","Frid
188ay","Saturday","Sunday"].map((i,o)=>({label:i,value:o}));case"monthly":return Array.from({length:31},(i,o)=>({label:String(o+1),value:o+1}));default:return[{label:"0",value:0}]}},[r]);return a.jsxs($,{sx:{display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:2},children:[a.jsx(Qy,{fieldName:"frequency.type",label:Ge.frequency,onChange:i=>{if(i!==r){switch(i){case"daily":case"weekly":t("frequency.offset",0);break;case"monthly":t("frequency.offset",1);break}e("frequency.offset")}},options:[{label:"Daily",value:"daily"},{label:"Weekly",value:"weekly"},{label:"Monthly",value:"monthly"}],required:!0}),a.jsx(Yt,{in:!!r&&r!=="daily",children:a.jsx(Qy,{disabled:!(r==="weekly"||r==="monthly"),fieldName:"frequency.offset",label:Ge.freq_offset,options:s,required:!0})})]})},Xde=()=>a.jsx(or,{title:hr.runSettings,children:a.jsxs($,{rowGap:2,children:[a.jsx(Qo,{fieldName:"active",fullWidth:!0,label:Ge.active}),a.jsx(Qo,{fieldName:"schedule",fullWidth:!0,label:Ge.supervisor_scheduling}),a.jsx(Jde,{}),a.jsx(Qo,{fieldName:"verify",fullWidth:!0,label:Ge.validation_active})]})}),Zde={"allSources.partitions":"Data Processing All Sources Tab","allSources.list":"Data Sources List Tab",dataOrchestration:"Runs History Tab","singleSource.advanced":"Advanced Tab","singleSource.configuration":"Configuration Tab","singleSource.mapAndTransform":"Map and Transform Tab","singleSource.notes":"Notes Tab","singleSource.overview":"Overview Tab","singleSource.partitions":"Data Processing Single Source Tab","singleSource.schedule":"Schedule Tab","singleSource.summary":"Summary Tab"},eue={...Zde,createNew:"Create New",saveEdits:"Save Edits",startNew:"Start New"},ML=()=>pr({actionMap:eue,eventName:"dataSource"}),tue=tA,nue=()=>{const{clientNiceId:e,engagementId:t,engagementNiceId:n}=pe(),{data:r=[],isLoading:s,isUninitialized:i}=RA(t),o=i||s,[l]=DA(),[c]=NA(),d=yn({authorized:"DataSources.Configurations.Edit"}),u=ML(),p=m.useCallback(({id:x,field:b,value:y})=>d?(u("saveEdits",{id:x}),l({dataSourceId:x,engagementId:t,key:b,value:y})):Promise.resolve({error:"Unauthorized"}),[d,t,u,l]),h=m.useCallback(async({dataSourceId:x,formValues:b,previousDataSource:y})=>{const v={client_nice_id:e,engagement_id:t,engagement_nice_id:n},C=Dce({engagementNiceId:n,environment:tue,formValues:b});return u("saveEdits",{id:x,name:Mr(y)}),"error"in await c({...C,...v,id:x})?{error:"There was a server error, please try again or contact customer support."}:{error:null,updatedSource:{...y,...v,...C,updated_at:Z().format("YYYY-MM-DD"),id:x}}},[e,t,n,u,c]),f=m.useCallback(async({contentType:x,deliveryMethod:b,feed:y,name:v,vendor:C})=>{if(!d)return Promise.resolve({error:"Unauthorized"});if(!x||!C||!y)return{error:"Missing required fields"};const w=rg(x);if(!w)return{error:"Missing required fields"};const S={...kie,client_nice_id:e,content_type:w.contentType,delivery_method:b,engagement_id:t,engagement_nice_id:n,feed_nice_id:y,id:null,measurement_category:[...w.measurementCategory],name:v,vendor_nice_id:C};u("createNew",{name:Mr(S)});const E=await c(S);return"error"in E?{error:"There was a server error, please try again or contact customer support."}:{newSource:{...S,id:E.data,contacts:[],created_at:Z().format("YYYY-MM-DD"),last_run_name:null,last_run_state:null,last_run_ts:null,updated_at:Z().format("YYYY-MM-DD")}}},[e,d,t,n,u,c]);return{checkIsDuplicate:m.useCallback(({contentType:x,feed:b,vendor:y})=>o?!0:!!r.find(({content_type:C,feed_nice_id:w,vendor_nice_id:S})=>C===x&&w===b&&S===y),[r,o]),data:r,handleSimpleCreateDataSource:f,handleUpdateDataSource:h,handleUpdateDataSourceField:p,loading:o}},zx=10,rue=({dataSources:e,dataSourcesLoading:t})=>{const{clientId:n,engagementId:r}=pe(),{data:s,isLoading:i}=OA(n,{skip:n===null||r===null}),o=m.useMemo(()=>e.filter(u=>u.active).length,[e]),l=m.useMemo(()=>e.length-o,[e,o]),c=m.useMemo(()=>{if(r!==null&&s){if(Array.isArray(s))return s.find(p=>typeof p=="object"&&p!==null&&"id"in p&&p.id===r)?.ds_license??zx;if("entities"in s&&"ids"in s){const u=s.entities[r];if(u&&typeof u=="object"&&"ds_license"in u)return u.ds_license??zx}}return zx},[s,r]),d=m.useMemo(()=>t||i||r===null?!1:c===0||o>=c,[o,c,t,r,i]);return{activeSourcesCount:o,availableLicenses:c,inactiveSourcesCount:l,isDataSourceLimitReached:d}},sue=U.coerce.number().min(1).optional(),iue=U.enum([...vie]).optional(),aue=e=>{const t=sue.safeParse(e.get("id")),n=iue.safeParse(e.get("view"));let r=null,s=null;return t.success&&(r=t.data??null),n.success&&(s=n.data??null),{id:r,view:s}},oue=()=>{const[e,t]=Jv(),n=m.useMemo(()=>aue(e),[e]),r=m.useCallback(({id:s,view:i})=>{if(s===n.id&&i===n.view)return;const l={view:i};s!==null&&(l.id=String(s)),t(l)},[n.id,n.view,t]);return{paramsState:n,updateSearchParams:r}},lue=()=>{const{engagementNiceId:e}=pe(),[t]=mV();return{handleRunPartition:m.useCallback(({dataSourceId:r,executionSteps:s,partitionDate:i,skipCompleted:o,endDate:l})=>t({engagementNiceId:e,dataSourceId:r,executionSteps:s,partitionDate:i,skipCompleted:o,endDate:l}),[e,t])}},cue=()=>{const{engagementNiceId:e}=pe(),[t,{isLoading:n}]=gV();return{handleRunPartitionBatch:m.useCallback(({dataSourceIds:s,executionDate:i,executionSteps:o,skipCompleted:l,endDate:c})=>t({dataSourceIds:s,endDate:c,engagementNiceId:e,executionDate:i,executionSteps:o,skipCompleted:l}),[e,t]),isRunning:n}},due=409,uue=U.object({errorResponse:U.object({body:U.string().optional(),statusCode:U.number().optional()})}),pue=U.object({message:U.string().trim().min(1)}),RL=(e,t)=>{const n=uue.safeParse(e);if(!n.success)return{error:!0,message:t};const{body:r,statusCode:s}=n.data.errorResponse,i=s===due;if(!r)return{error:!0,message:t,terminal:i};let o;try{o=JSON.parse(r)}catch{return{error:!0,message:t,terminal:i}}const l=pue.safeParse(o);return{error:!0,message:l.success?l.data.message:t,terminal:i}},a_="The data processing run could not be stopped. Refresh the list and try again.",hue=()=>{const{engagementNiceId:e}=pe(),[t,{isLoading:n}]=xV();return{handleStopPartition:m.useCallback(async({dataSourceId:s,partitionId:i})=>{if(!e)return{error:!0,message:"The engagement context is unavailable. Refresh the page and try again."};const o=await t({dataSourceId:s,engagementNiceId:e,partitionId:i});return"data"in o?o.data.success?o.data.reconciled?{error:!1,notice:!0,message:o.data.message}:{error:!1}:{error:!0,message:o.data.message||a_}:RL(o.error,a_)},[e,t]),stoppingPartition:n}},fue=()=>{const{dispatch:e,mpTrack:t}=Je(),n=()=>{e({type:"dialogOpen",value:"createNewSource"}),t("startNew")};return a.jsx(re,{onClick:n,startIcon:a.jsx(wC,{}),sx:{maxHeight:36},variant:"contained",children:"Add Data Source"})},nw=()=>on(),NL=({error:e,label:t,required:n})=>a.jsx(wt,{error:e,required:n,sx:{color:"text.primary",fontWeight:600,pb:.5},children:t}),o_=({disabled:e=!1,field:t,label:n,options:r,placeholder:s,required:i=!1})=>{const{control:o}=nw();return a.jsx(Et,{control:o,name:t,render:({field:{value:l,onBlur:c,onChange:d},fieldState:{error:u}})=>a.jsxs($,{children:[a.jsx(NL,{error:!!u,label:n,required:i}),a.jsx(tt,{disabled:e,displayEmpty:!0,error:!!u,onBlur:c,onChange:p=>{const{value:h}=p.target;d(h)},renderValue:p=>{if(!p)return s;const h=r.find(f=>f.value===p);return h?h.logoUrl?a.jsxs(T,{sx:{display:"flex",alignItems:"center",columnGap:1},children:[a.jsx(sa,{src:h.logoUrl}),a.jsx("span",{children:h.label})]}):h.label:p},value:l??"",variant:"outlined",sx:{"& .MuiSelect-select":{height:24,py:1,display:"flex",alignItems:"center"}},children:r.map(p=>a.jsxs(Se,{value:p.value,sx:{fontSize:14,pl:3,py:1,display:"flex",alignItems:"center",columnGap:1},children:[p.logoUrl?a.jsx(sa,{src:p.logoUrl}):null,p.label]},p.value))}),a.jsx(Zn,{error:!!u,sx:{ml:1.75},children:u?.message||" "})]})})},Bx=({disabled:e=!1,field:t,label:n,placeholder:r,required:s=!1})=>{const{control:i}=nw();return a.jsx(Et,{control:i,name:t,render:({field:{onBlur:o,onChange:l,ref:c,value:d},fieldState:{error:u}})=>a.jsxs($,{children:[a.jsx(NL,{error:!!u,label:n,required:s}),a.jsx(De,{disabled:e,error:!!u,helperText:u?.message||" ",sx:{"& .MuiInputBase-root":{maxHeight:40}},inputRef:c,onBlur:o,onChange:p=>{l(p.target.value||"")},placeholder:r,value:d,variant:"outlined"})]})})},mue=ul.map(e=>({label:e.label,value:e.label})),gue=({submitting:e})=>{const{errors:t}=nw().formState,{connectors:n,connectorsLoading:r}=Je(),s=m.useMemo(()=>n.filter(i=>i.active).map(i=>({label:i.name,logoUrl:i.logoUrl,value:i.niceId})).toSorted((i,o)=>i.value==="api"?1:o.value==="api"?-1:i.label.localeCompare(o.label)),[n]);return a.jsxs($,{sx:{px:2,py:0,mb:-2,rowGap:2},children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:14,pb:1},children:"Create a new data source by providing the basic configuration details."}),a.jsxs($,{sx:{rowGap:1},children:[a.jsx(Bx,{disabled:e,field:"name",label:"Data Source Name",placeholder:"Enter a descriptive name for your data source"}),a.jsx(o_,{disabled:r||e,field:"deliveryMethod",label:"Method",o
188ptions:s,placeholder:"Select connection method",required:!0}),a.jsx(o_,{disabled:e,field:"contentType",label:"Content Type",options:mue,placeholder:"Select content type",required:!0}),a.jsx(Bx,{disabled:e,field:"vendor",label:"Data Provider",placeholder:"Enter the data provider (e.g. Google, Facebook, Salesforce)",required:!0}),a.jsx(Bx,{disabled:e,field:"feed",label:"Data Feed",placeholder:"Enter the data feed (e.g. email, posts, analytics)",required:!0}),a.jsx(I,{variant:"caption",color:"error",children:t?.root?.message||""})]})]})},Xy=U.string().min(1,"Required"),l_=Xy.regex(tw,{message:"Alphanumeric characters only"}),xue=U.object({contentType:Xy,deliveryMethod:Xy,name:U.string().optional(),feed:l_,vendor:l_}),c_={contentType:"",deliveryMethod:"",feed:"",name:"",vendor:""},bue=({formMethods:e})=>{const{clearErrors:t,formState:n,setError:r,watch:s}=e,{checkIsDuplicate:i}=Je(),o=s("contentType"),l=s("feed"),c=s("vendor"),[d]=gU(()=>{if(!o||!l||!c)return!1;const u=rg(o);return u?i({contentType:u.contentType,feed:l,vend
188or:c}):!1},1e3);return m.useEffect(()=>{const{errors:u}=n;d?r("root",{message:"The data source already exists. The combination of Content Type, Vendor, and Feed must be unique.",type:"duplicate"}):u.root?.type==="duplicate"&&t("root")},[t,n,d,r]),{isDuplicate:d}},yue=()=>{const e=ct(),[t,n]=m.useState(!1),{pushNotification:r}=jt(),{dispatch:s,handleSimpleCreateDataSource:i,navigateToTab:o,state:l}=Je(),c=Xs({mode:"onChange",resolver:Zs(xue),defaultValues:c_}),{isDuplicate:d}=bue({formMethods:c}),u=m.useMemo(()=>{const{errors:f}=c.formState;return d||Object.keys(f).some(g=>g!=="root")},[c.formState,d]),p=m.useCallback(()=>{s({type:"dialogOpen",value:null}),c.reset(c_)},[s,c]),h=m.useCallback(async()=>{c.clearErrors("root");const f=c.getValues();if(!await c.trigger())return;n(!0);const x=await i({...f,name:f.name??null});if(e())if(n(!1),"error"in x)c.setError("root",{message:x.error,type:"manual"});else{const{newSource:b}=x;p(),r({content:"Data source successfully created",timeout:5e3,severity:"success"}),o({nextSource:b,nextView:"singleSource.configuration"})}},[c,p,i,o,e,r]);return a.jsx(Js,{...c,children:a.jsx(mt,{acceptButtonProps:{disabled:u},acceptLabel:"Create Data Source",body:a.jsx(gue,{submitting:t}),handleAccept:h,handleClose:p,resetLoadingAfterAccept:!0,open:l.dialogOpen==="createNewSource",title:a.jsxs(T,{display:"flex",alignItems:"center",gap:1,children:[a.jsx(wC,{})," Add New Data Source"]})})})};var vc={},d_;function vue(){if(d_)return vc;d_=1;var e=Pt();Object.defineProperty(vc,"__esModule",{value:!0}),vc.default=void 0;var t=e(Lt()),n=Ot();return vc.default=(0,t.default)((0,n.jsx)("path",{d:"M8 5v14l11-7z"}),"PlayArrow"),vc}var Cue=vue();const Gs=dt(Cue);var Cc={},u_;function wue(){if(u_)return Cc;u_=1;var e=Pt();Object.defineProperty(Cc,"__esModule",{value:!0}),Cc.default=void 0;var t=e(Lt()),n=Ot();return Cc.default=(0,t.default)((0,n.jsx)("path",{d:"M10 8.64 15.27 12 10 15.36zM8 5v14l11-7z"}),"PlayArrowOutlined"),Cc}var Sue=wue();const og=dt(Sue);var wc={},p_;function jue(){if(p_)return wc;p_=1;var e=Pt();Object.defineProperty(wc,"__esModule",{value:!0}),wc.default=void 0;var t=e(Lt()),n=Ot();return wc.default=(0,t.default)((0,n.jsx)("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4z"}),"Refresh"),wc}var kue=jue();const rw=dt(kue);var Sc={},h_;function Eue(){if(h_)return Sc;h_=1;var e=Pt();Object.defineProperty(Sc,"__esModule",{value:!0}),Sc.default=void 0;var t=e(Lt()),n=Ot();return Sc.default=(0,t.default)((0,n.jsx)("path",{d:"M16 8v8H8V8zm2-2H6v12h12z"}),"StopOutlined"),Sc}var _ue=Eue();const lg=dt(_ue),OL=({checked:e,disabled:t=!1,label:n="Active only",onChange:r})=>a.jsx(sn,{control:a.jsx(Dn,{checked:e,disabled:t,onChange:s=>r(s.target.checked),size:"small"}),label:a.jsx(I,{sx:{fontSize:13,userSelect:"none"},children:n}),sx:{m:0}}),f_="_selectAll",Ou=({columns:e,columnVisibilityModel:t,disabled:n=!1,onChange:r})=>{const s=m.useMemo(()=>e.filter(({hideable:d})=>d!==!1).map(({field:d,headerName:u})=>({label:u??d,value:d})).sort((d,u)=>d.label.toLowerCase()<u.label.toLowerCase()?-1:1),[e]),i=m.useCallback(d=>t[d]!==!1,[t]),o=m.useMemo(()=>s.filter(({value:d})=>i(d)).map(d=>d.value),[i,s]),l=o.length===s.length,c=m.useCallback(d=>{const{value:u}=d.target,p=typeof u=="string"?u.split(","):u;if(p.includes(f_)){const h=!l;r(s.reduce((f,{value:g})=>({...f,[g]:h}),{}));return}r(s.reduce((h,{value:f})=>({...h,[f]:p.includes(f)}),{}))},[l,r,s]);return a.jsxs(tt,{disabled:n,multiple:!0,onChange:c,renderValue:()=>a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center",color:n?"text.disabled":"text.secondary"},children:[a.jsx(po,{size:19}),a.jsx(I,{component:"span",sx:{height:24,lineHeight:"24px"},children:"Columns"})]}),sx:{height:38,width:142},value:o,children:[a.jsxs(Se,{className:l?"Mui-selected":"",value:f_,children:[a.jsx(et,{checked:l,indeterminate:!!o.length&&!l}),a.jsx(Kt,{primary:"Select All"})]}),a.jsx(St,{}),s.map(({label:d,value:u})=>a.jsxs(Se,{sx:{height:48},value:u,children:[a.jsx(et,{checked:i(u)}),a.jsx(Kt,{primary:d})]},u))]})},Pu=({left:e,right:t})=>a.jsxs(km,{sx:{justifyContent:"space-between",p:0,pb:1},children:[a.jsx($,{sx:{alignItems:"center",flexDirection:"row",gap:1.5},children:e}),a.jsx($,{sx:{alignItems:"center",flexDirection:"row",gap:2},children:t})]}),Lu=({apiRef:e,loading:t})=>{const[n,r]=m.useState(""),s=m.useMemo(()=>gm(o=>{e.current.setQuickFilterValues(o.split(" ").filter(l=>l!==""))},150),[e]),i=o=>{const l=o.target.value;r(l),s(l)};return a.jsx(Qe,{children:a.jsx(ys,{disabled:t,startAdornment:a.jsx(Mt,{sx:{color:"text.disabled",fontSize:20},children:a.jsx(er,{})}),onChange:i,placeholder:"Search",sx:{borderRadius:1,height:42,width:228,px:1.5,".MuiInputBase-inputAdornedStart":{pl:1.5,pr:0,height:24},"&.Mui-focused":{".MuiOutlinedInput-notchedOutline":{boxShadow:"none"}}},value:n})})},Ux={selectedViewName:null,views:[]},$s="Default",Zy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tue=e=>Zy(e)&&typeof e.name=="string"&&Zy(e.state),Iue=e=>{try{const t=localStorage.getItem(e);if(!t)return Ux;const n=JSON.parse(t);if(!Zy(n))return Ux;const r=Array.isArray(n.views)?n.views.filter(Tue):[],s=typeof n.selectedViewName=="string"?n.selectedViewName:null;return{selectedViewName:s===$s||r.some(o=>o.name===s)?s:null,views:r}}catch{return Ux}},Fu=({apiRef:e,onApplyState:t,storageKey:n})=>{const[{selectedViewName:r,views:s},i]=m.useState(()=>Iue(n)),o=m.useRef(!1),l=m.useRef(null),c=m.useCallback(g=>{i(g);try{localStorage.setItem(n,JSON.stringify(g))}catch{}},[n]),d=m.useCallback(g=>e.current?.restoreState?(e.current.restoreState(g),t?.(g),!0):!1,[e,t]),u=m.useCallback(g=>{const x=s.find(b=>b.name===g);return!x||!d(x.state)?!1:(c({selectedViewName:g,views:s}),!0)},[c,d,s]),p=m.useCallback(()=>{l.current&&d(l.current),c({selectedViewName:$s,views:s})},[c,d,s]),h=m.useCallback(g=>{if(g===$s||!e.current?.exportState)return!1;const x=e.current.exportState(),b=[...s.filter(y=>y.name!==g),{name:g,state:x}];return c({selectedViewName:g,views:b}),!0},[e,c,s]),f=m.useCallback(g=>{const x=s.filter(b=>b.name!==g);
188if(r===g){l.current&&d(l.current),c({selectedViewName:$s,views:x});return}c({selectedViewName:r,views:x})},[c,d,r,s]);return m.useEffect(()=>{if(!o.current&&e.current?.exportState){if(l.current||(l.current=e.current.exportState()),r&&r!==$s){const g=s.find(x=>x.name===r);g&&d(g.state)}o.current=!0}},[e,d,r,s]),{applyDefault:p,applyView:u,deleteView:f,saveView:h,selectedViewName:r,views:s}},Due="",Aue=e=>({borderColor:e.palette.mode==="dark"?e.palette.divider:e.palette.neutral[200],color:"text.secondary",height:38,textTransform:"none","&:hover":{backgroundColor:e.palette.action.hover,borderColor:e.palette.mode==="dark"?e.palette.divider:e.palette.neutral[200]}}),cg=({disabled:e,onApplyDefault:t,onApplyView:n,onDeleteView:r,onSaveView:s,selectedViewName:i,views:o})=>{const[l,c]=m.useState(!1),[d,u]=m.useState(""),p=d.trim(),h=p.toLowerCase()===$s.toLowerCase(),f=!i||i===$s,g=v=>{const{value:C}=v.target;C===$s?t():C&&n(C)},x=(v,C)=>{v.stopPropagation(),r(C)},b=()=>{u(""),c(!0)},y=()=>{!p||h||(s(p),c(!1))};return a.jsxs(a.Fragment,{children:[a.jsxs(tt,{disabled:e,displayEmpty:!0,onChange:g,renderValue:()=>a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center",color:"text.secondary"},children:[a.jsx(xU,{size:18}),a.jsx(I,{component:"span",sx:{height:24,lineHeight:"24px"},children:o.length?`Custom View (${o.length})`:"Custom View"})]}),sx:{height:38,minWidth:160},value:Due,children:[a.jsx(Se,{sx:{display:"flex",gap:2,justifyContent:"space-between"},value:$s,children:a.jsxs($,{direction:"row",sx:{alignItems:"center",gap:1,minWidth:0},children:[f?a.jsx(Oh,{size:16}):a.jsx(T,{sx:{width:16}}),a.jsx(Kt,{primary:$s})]})}),o.map(v=>a.jsxs(Se,{sx:{display:"flex",gap:2,justifyContent:"space-between"},value:v.name,children:[a.jsxs($,{direction:"row",sx:{alignItems:"center",gap:1,minWidth:0},children:[v.name===i?a.jsx(Oh,{size:16}):a.jsx(T,{sx:{width:16}}),a.jsx(Kt,{primary:v.name})]}),a.jsx(be,{title:"Delete view",children:a.jsx(Ie,{"aria-label":`Delete view ${v.name}`,onClick:C=>x(C,v.name),size:"small",children:a.jsx(Xr,{size:16})})})]},v.name))]}),a.jsx(re,{disabled:e,onClick:b,startIcon:a.jsx(ca,{size:18}),sx:Aue,variant:"outlined",children:"Save Current View"}),a.jsxs(yt,{fullWidth:!0,maxWidth:"xs",onClose:()=>c(!1),open:l,children:[a.jsx(vt,{children:"Save Current View"}),a.jsx(Ct,{children:a.jsx(T,{sx:{pt:1},children:a.jsx(De,{autoFocus:!0,error:h,fullWidth:!0,helperText:h?'"Default" is a reserved name':" ",label:"View name",onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y()},value:d})})}),a.jsxs(un,{children:[a.jsx(re,{onClick:()=>c(!1),sx:{textTransform:"none"},variant:"outlined",children:"Cancel"}),a.jsx(re,{disabled:!p||h,onClick:y,sx:{textTransform:"none"},variant:"contained",children:"Save"})]})]})]})}
188,m_="The job could not be stopped. Refresh the list and try again.",sw=({handleClose:e,handleStop:t,jobLabel:n,open:r})=>{const[s,i]=m.useState(null),[o,l]=m.useState(null),[c,d]=m.useState(!1),u=()=>{i(null),l(null),d(!1),e()},p=async()=>{i(null),l(null);try{const h=await t();if(h.error){i(h.message??m_),d(h.terminal===!0);return}if(h.notice){l(h.message??"The run had already finished. Its status has been corrected."),d(!0);return}u()}catch{i(m_)}};return a.jsx(mt,{acceptButtonProps:{color:"error",disabled:c},acceptLabel:"Stop Run",body:a.jsxs(a.Fragment,{children:[a.jsxs(I,{children:["Stop the job for ",a.jsx("strong",{children:n}),"?"]}),a.jsx(I,{sx:{color:"text.secondary",mt:2},children:"Stopping this job may not stop downstream jobs that are already running. Check their status separately."}),s?a.jsx(I,{"aria-live":"polite",color:"error",role:"alert",sx:{mt:2},children:s}):null,o?a.jsx(vn,{"aria-live":"polite",severity:"info",sx:{mt:2},children:o}):null]}),closeLabel:o?"Close":"Cancel",handleAccept:p,handleClose:u,open:r,resetLoadingAfterAccept:!0,title:"Stop job?"})};Z.extend(El);const Mue=60,PL=({activeStates:e,status:t,updatedAt:n})=>e.includes(t??"")&&!!n&&Z().diff(Z.utc(n),"minute")<=Mue,LL=["RUNNING"],FL=({dataSource:e,status:t,updatedAt:n})=>e?.active?PL({activeStates:LL,status:t,updatedAt:n})?{disabled:!0,message:"Job is currently running. Please wait until it is completed."}:{disabled:!1,message:""}:{disabled:!0,message:"This action is currently unavailable. The data source is inactive."},$L=({editEnabled:e,status:t})=>e&&LL.includes(t??""),Rue=({id:e,handleShowDetails:t})=>{const n=m.useCallback(()=>{t(e)},[t,e]);return a.jsx(Ji,{ariaLabel:"View job details",color:"brand",icon:aa,iconSize:22,onClick:n,tooltip:"View job details"})},Nue=({disabled:e,handleOpenRunDialog:t,id:n,tooltipMessage:r})=>{const s=m.useCallback(()=>{t(n)},[t,n]);return a.jsx(Ji,{ariaLabel:"Run data processing job",color:"success",disabled:e,icon:og,onClick:s,tooltip:r||"Run data processing job"})},Oue=({datasourceId:e,id:t,status:n,updatedAt:r})=>{const{dataSources:s,dispatch:i,editEnabled:o,partitions:l,stoppingPartition:c,state:{selectedDataSource:d}}=Je(),u=e!=null?s.find(y=>y.id===e):d,p=m.useCallback(()=>{const y=l.find(v=>v.id===t);y&&(i({type:"selectedPartition",value:y}),i({type:"dialogOpen",value:"runPartition"}))},[i,t,l]),h=m.useCallback(()=>{const y=l.find(v=>v.id===t);y&&(i({type:"selectedPartition",value:y}),i({type:"dialogOpen",value:"partitionDetails"}))},[i,t,l]),f=m.useCallback(()=>{const y=l.find(v=>v.id===t);y&&(i({type:"selectedPartition",value:y}),i({type:"dialogOpen",value:"stopPartition"}))},[i,t,l]),{disabled:g,message:x}=FL({dataSource:u,status:n,updatedAt:r}),b=$L({editEnabled:o,status:n});return a.jsxs($,{direction:"row",spacing:1,children:[a.jsx(Nue,{tooltipMessage:x,disabled:g,handleOpenRunDialog:p,id:t}),b?a.jsx(Ji,{ariaLabel:"Stop data processing run",color:"error",disabled:c,icon:lg,iconSize:36,onClick:f,tooltip:"Stop data processing run"}):a.jsx(MM,{}),a.jsx(Rue,{id:t,handleShowDetails:h})]})},Pue=({id:e,status:t=null})=>{const{dispatch:n,partitions:r}=Je(),s=()=>{const i=r.find(o=>o.id===e);i&&(n({type:"selectedPartition",value:i}),n({type:"dialogOpen",value:"partitionDetails"}))};return a.jsx(Nu,{onClick:s,size:"medium",status:t,sx:{cursor:"pointer"}})};var jc={},g_;function Lue(){if(g_)return jc;g_=1;var e=Pt();Object.defineProperty(jc,"__esModule",{value:!0}),jc.default=void 0;var t=e(Lt()),n=Ot();return jc.default=(0,t.default)((0,n.jsx)("path",{d:"M19 5v9h-5v5H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10l6-6V5c0-1.1-.9-2-2-2m-7 11H7v-2h5zm5-4H7V8h10z"}),"StickyNote2Outlined"),jc}var Fue=Lue();const zL=dt(Fue),$ue=({existingNotes:e,id:t})=>{const{dispatch:n,partitions:r}=Je(),s=m.useCallback(()=>{const i=r.find(o=>o.id===t);i&&(n({type:"selectedPartition",value:i}),n({type:"dialogOpen",value:"notes"}))},[n,t,r]);return a.jsx(Ie,{onClick:s,size:"small",sx:{color:e?"primary.main":"action.disabled"},children:a.jsx(zL,{})})},zue=({dataSourceId:e,id:t,status:n=null})=>{const{editEnabled:r,handleUpdatePartition:s}=Je(),i=o=>{o.stopPropagation();const l=o.target.value;Tn(Ph,l)&&s({dataSourceId:e,partitionId:t,techopsStatus:l})};return r?a.jsx(tt,{onChange:i,size:"small",sx:{color:B0(n).color,fontSize:14,minWidth:140},value:n||"",children:Ph.map(o=>a.jsx(Se,{value:o,children:o},o))}):a.jsx(vL,{status:n})},Bue=e=>e===null?"-":new Intl.NumberFormat("en-US",{currency:"USD",style:"currency"}).format(e),Uue=e=>e===null?"-":new Intl.NumberFormat("en-US").format(e),x_=e=>e?Z(e).format("YYYY-MM-DD"):"-";Z.extend(El);const Vue=({allSources:e,editEnabled:t,showMetricColumns:n})=>{const r=[{field:"partitionDate",flex:1,headerName:"Partition",minWidth:100},{field:"jobName",flex:1,headerName:"Last Process Run",minWidth:135,valueFormatter:({value:l})=>l??"-"},{field:"updatedAt",flex:1,headerName:"Last Updated",minWidth:150,valueFormatter:({value:l})=>l?Z.utc(l).local().format("L LT"):"-"},{field:"jobState",flex:1,headerName:"Job Status",minWidth:120,renderCell:({row:l})=>a.jsx(Pue,{id:l.id,status:l.jobState})},{field:"minDate",flex:1,headerName:"Min Date",minWidth:100,valueFormatter:({value:l})=>x_(l)},{field:"maxDate",flex:1,headerName:"Max Date",minWidth:100,valueFormatter:({value:l})=>x_(l)},{field:"techopsStatus",flex:1,headerName:"Tech Ops Status",minWidth:160,renderCell:({row:l})=>a.jsx(zue,{dataSourceId:l.datasourceId,id:l.id,status:l.techopsStatus})},{field:"notes",headerName:"Notes",minWidth:60,renderCell:({row:l})=>a.jsx($ue,{existingNotes:!!l.notes,id:l.id}),sortable:!1,width:60}],s=[{field:"totalCost",flex:1,headerName:"Total Spend",minWidth:120,type:"number",valueFormatter:({value:l})=>Bue(l)},{field:"totalImpressions",flex:1,headerName:"Total Impressions",minWidth:120,type:"number",valueFormatter:({value:l})=>Uue(l)}];let i=[];return n?i=[...r.slice(0,7),...s,...r.slice(7)]:i=r,t&&i.push({f
188ield:"actions",headerName:"Actions",minWidth:165,renderCell:({row:l})=>a.jsx(Oue,{datasourceId:e?l.datasourceId:void 0,status:l.jobState,updatedAt:l.updatedAt,id:l.id}),sortable:!1,width:165}),e&&(i=[{field:"datasourceName",flex:1.5,headerName:"Data Source",minWidth:200,renderCell:({value:l})=>a.jsx(T,{sx:{fontWeight:600},children:l}),valueGetter:({row:l})=>l.datasourceName||l.datasourceNiceId},...i]),i},Wue=()=>a.jsx(T,{sx:{display:"flex",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"},children:a.jsx(I,{children:"No partitions found"})}),Hue=({editEnabled:e,onClose:t,open:n,row:r})=>{const[s,i]=m.useState(r?.notes||""),{handleUpdatePartition:o}=Je(),l=()=>{i(r?.notes||""),t()},c=()=>{r?.id&&(o({dataSourceId:r.datasourceId,partitionId:r.id,notes:s}),t())};return m.useEffect(()=>{i(r?.notes||"")},[r]),a.jsxs(yt,{fullWidth:!0,maxWidth:"md",onClose:l,open:n,children:[a.jsxs(vt,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between"},children:[a.jsxs(I,{sx:{fontSize:24,fontWeight:600},children:[e&&"Edit"," QA Notes - Partition ",r?.partitionDate||"..."]}),a.jsx(Ie,{onClick:l,size:"small",children:a.jsx(ji,{})})]}),a.jsx(Ct,{children:a.jsx($,{sx:{rowGap:3},children:a.jsxs(T,{sx:{borderTop:"1px solid",borderColor:"divider",pt:3},children:[a.jsx(I,{sx:{fontSize:16,fontWeight:600,mb:1},children:"QA Notes"}),e?a.jsx(cu,{value:s,onChange:i}):a.jsx(ms,{markdownText:r?.notes||"No Notes Saved"})]})})}),a.jsxs(un,{sx:{px:3,py:2},children:[a.jsx(re,{onClick:l,variant:"outlined",children:e?"Cancel":"Close"}),e&&a.jsx(re,{onClick:c,variant:"contained",children:"Save Notes"})]})]})},que=({children:e,onClose:t,onRun:n,open:r,partitionName:s,newPartition:i,runDisabled:o,selectedSteps:l,totalSteps:c,loading:d})=>a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",onClose:t,open:r,PaperProps:{sx:{borderRadius:2}},children:[a.jsxs(vt,{sx:{alignItems:"center",display:"flex",gap:1,pb:2,pt:2.5,px:3},children:[a.jsx(Gs,{sx:{color:"primary.main",fontSize:28}}),a.jsx(I,{component:"span",sx:{flex:1,fontSize:20,fontWeight:600},children:i?"Run New Partition":`Run Partition: ${s}`}),a.jsx(Ie,{"aria-label":"Close dialog",onClick:t,disabled:d,size:"small",sx:{color:"text.secondary"},children:a.jsx(ji,{})})]}),a.jsx(Ct,{sx:{px:3,py:2},children:e}),a.jsxs(un,{sx:{justifyContent:"space-between",px:3,py:2},children:[a.jsxs(I,{sx:{color:"text.secondary",fontSize:14},children:[l," of ",c," steps selected"]}),a.jsxs(T,{sx:{display:"flex",gap:1.5},children:[a.jsx(re,{onClick:t,disabled:d,sx:{textTransform:"none"},variant:"outlined",children:"Cancel"}),a.jsx(re,{disabled:o||d,onClick:n,startIcon:a.jsx(Gs,{}),sx:{textTransform:"none"},variant:"contained",children:"Run Selected Steps"})]})]})]}),Gue=({newPartition:e,startDate:t,endDate:n,setStartDate:r,setEndDate:s,disabled:i})=>e?a.jsxs(a.Fragment,{children:[a.jsx(I,{sx:{color:"text.secondary",mb:2},children:"Specify the date range for the new partition run."}),a.jsxs(T,{sx:{display:"flex",gap:2,mb:1},children:[a.jsx(eo,{format:"YYYY-MM-DD",label:"Start Date",disabled:i,onChange:o=>r(o),slotProps:{textField:{fullWidth:!0,placeholder:"yyyy-mm-dd",required:!0}},value:t}),a.jsx(eo,{format:"YYYY-MM-DD",label:"End Date (Optional)",...t&&{minDate:t},disabled:i,onChange:o=>s(o),slotProps:{textField:{error:!!(n&&t&&n.isBefore(t)),fullWidth:!0,placeholder:"yyyy-mm-dd"}},value:n})]}),a.jsx(I,{sx:{color:"text.secondary",fontSize:14,mb:3},children:"Enter the date range for this partition run (e.g., 2024-06-15 to 2024-06-30)"})]}):null,Yue=({skippedPartitions:e,datasourceName:t})=>a.jsxs(T,{minWidth:"500px",children:[a.jsxs(I,{variant:"h6",gutterBottom:!0,sx:{color:"success.contrastText"},children:["Blocked partitions for ",t]}),e.map(n=>a.jsx(I,{variant:"body2",children:n},n))]}),b_=({description:e,isEnabled:t,name:n})=>a.jsxs(T,{sx:{ml:t?void 0:"42px"},children:[a.jsx(I,{sx:{fontWeight:t?600:void 0,color:t?void 0:"text.secondary"},children:n}),a.jsx(I,{sx:{fontSize:14,color:t?void 0:"text.secondary"},children:e})]}),BL=({checked:e,step:t,handleToggleStep:n,disabled:r})=>a.jsx(be,{title:t.isEnabled?"":"This step needs to be configured before it can be used",arrow:!0,children:a.jsx(T,{sx:{"&:hover":{backgroundColor:"background.input.hovered"},backgroundColor:"background.input.default",border:1,borderColor:"border.input",borderRadius:1,cursor:t.isEnabled&&!r?"pointer":"help",px:2,py:1.5},onClick:t.isEnabled&&!r?()=>n(t.niceId):void 0,children:t.isEnabled?a.jsx(sn,{sx:{m:0,width:"100%",pointerEvents:"none"},control:a.jsx(et,{checked:e,disabled:r,sx:{py:0}}),label:a.jsx(b_,{name:t.name,description:t.description,isEnabled:t.isEnabled})}):a.jsx(b_,{name:t.name,description:t.description,isEnabled:t.isEnabled})})}),Kue=({executedJobs:e,datasourceName:t})=>a.jsxs(T,{minWidth:"400px",sx:{color:"success.contrastText"},children:[a.jsxs(I,{variant:"h6",gutterBottom:!0,sx:{color:"success.contrastText"},children:["Partitions started for ",t]}),e.map(n=>a.jsx(I,{variant:"body2",sx:{color:"success.contrastText"},children:n.execution_date},n.executionArn??n.execution_date))]}),iw={data_ingestion:{description:"Import raw data files",name:"Data Ingestion",niceId:"data_ingestion"},clean:{description:"Data cleaning and validation",name:"Clean",niceId:"clean"},media_resolution:{description:"Resolve media references",name:"Media Resolution",niceId:"media_resolution"},touchpoint_resolution:{description:"Map touchpoint data",name:"Touchpoint Resolution",niceId:"touchpoint_resolution"},brand_resolution:{description:"Resolve brand information",name:"Brand Resolution",niceId:"brand_resolution"},normalize:{description:"Standardize data format",name:"Normalize",niceId:"normalize"},export:{description:"Export processed data",name:"Export",niceId:"export"}},Que=e=>{const n=e.execution_steps?.map(({step:s})=>s)||[];return Object.entries(iw).map(([s,{description:i,name:o,niceId:l}])=>({description:i,isEnabled:n.includes(s)||l==="data_ingestion",name:o,niceId:l}))},Zf=e=>e.filter(t=>t.isEnabled&&t.niceId!==iw.export.niceId).map(t=>t.niceId),Jue=({dataSource:e,onClose:t,open:n,partitionDate:r,newPartition:s=!1})=>{const{pushNotification:i}=jt(),{handleRunPartition:o}=Je(),[l,c]=m.useState(null),[d,u]=m.useState(null),p=m.useMemo(()=>Que(e),[e]),[h,f]=m.useState(Zf(p)),[g,x]=m.useState(!1),[b,y]=m.useState(!1),v=O=>{f(R=>R.includes(O)?R.filter(L=>L!==O):[...R,O])},C=()=>{const O=p.filter(R=>R.isEnabled);h.length===O.length?f([]):f(O.map(R=>R.niceId))},w=()=>{t(),c(null),u(null)},S=async()=>{const O=l?.format("YYYY-MM-DD"),R=d?.format("YYYY-MM-DD"),L=r??O;if(!L)return;y(!0);const P=await o({dataSourceId:e.id,endDate:R,executionSteps:h,partitionDate:L,skipCompleted:g});y(!1);const F=Mr(e);if("data"in P){const{executed_jobs:z,blocked_partitions:B}=P.data;z.length>0&&i({content:a.jsx(Kue,{executedJobs:z,datasourceName:F}),severity:"success"}),B.length>0&&i({content:a.jsx(Yue,{skippedPartitions:B,datasourceName:F}),severity:"warning"}),z.length===0&&B.length===0&&i({content:"No valid partitions were found in the selected date range",severity:"warning"})}else i({content:`Run partition failed ${String(P.error)}`,severity:"error"});t()},E=h.length,k=p.filter(O=>O.isEnabled).length,j=E===k,_=s?!!l&&(!d||d.isAfter(l)):!0,D=E===0||!_||!s&&!r;m.useEffect(()=>{n&&f(Zf(p))},[p,n]);const M=a.jsxs(a.Fragment,{children:[a.jsx(Gue,{newPartition:s,startDate:l,endDate:d,setStartDate:c,setEndDate:u,disabled:b}),!s&&a.jsx(I,{sx:{color:"text.secondary",mb:2},children:"Select the processing steps you want to run for this partition."}),a.jsx(T,{sx:{backgroundColor:"background.neutral.default",border:1,borderColor:"border.default",borderRadius:1.5,mb:2.5,p:2},children:a.jsx(sn,{control:a.jsx(Dn,{checked:g,onChange:O=>x(O.target.checked),disabled:b}),label:a.jsxs(T,{children:[a.jsx(I,{sx:{color:"text.primary",fontWeight:600},children:"Skip Successfully Completed Steps"}),a.jsx(I,{sx:{color:"text.secondary",fontSize:14},children:"Only re-run steps that previously failed or haven't been executed"})]}),sx:{alignItems:"flex-start",m:0}})}),a.jsxs(T,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between",mb:1.5},children:[a.jsx(I,{sx:{fontWeight:600},children:"Select Steps to Run"}),a.jsx(re,{disabled:b,onClick:C,size:"small",sx:{color:"primary.main",fontSize:14,textTransform:"none"},children:j?"Unselect All":"Select All"})]}),a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:p.map(O=>a.jsx(BL,{checked:h.includes(O.niceId),step:O,handleToggleStep:v,disabled:b},O.niceId))})]}),N=a.jsx(que,{onClose:w,onRun:S,open:n,newPartition:s,partitionName:r||"...",runDisabled:D,selectedSteps:E,totalSteps:k,loading:b,children:M});return a.jsx(xu,{dateAdapter:Cu,children:N})},Xue=({description:e,prompt:t,title:n})=>{const r=!!t,{sendPrompt:s}=Fm(),i=()=>{r&&s({prompt:t})},o=l=>{r&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),i())};return a.jsx(be,{title:r?"Click to start a new chat with this suggestion":"This suggestion requires manual review",arrow:!0,placement:"top",children:a.jsx(Ve,{onClick:r?i:void 0,onKeyDown:o,tabIndex:r?0:-1,role:r?"button":void 0,"aria-label":r?`Apply suggestion: ${n}`:void 0,"aria-disabled":!r,sx:{cursor:r?"pointer":"default",transition:"all 0.2s","&:hover":r?{boxShadow:4,transform:"translateY(-2px)"}:{}
188,"&:focus-visible":r?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:{}},children:a.jsxs(Ue,{children:[a.jsxs(T,{display:"flex",alignItems:"center",gap:1,mb:1,children:[r?a.jsx(bU,{size:16}):a.jsx(rA,{size:16}),a.jsx(I,{variant:"subtitle2",fontWeight:600,children:n})]}),a.jsx(I,{variant:"body2",color:"text.secondary",children:e})]})})})},y_=["Reading partition data","Analyzing traceback error","Processing error patterns","Generating recommendations","Suggesting fixes"],Zue=({isLoading:e,summary:t="",suggestions:n=[],error:r})=>{const[s,i]=m.useState(0),[o,l]=m.useState(!1);return m.useEffect(()=>{if(!e)return;const c=setInterval(()=>{i(d=>(d+1)%y_.length)},8e3);return()=>clearInterval(c)},[e]),a.jsx(T,{sx:{backgroundColor:"background.neutral.default",borderRadius:2,p:2},children:a.jsxs($,{textAlign:"justify",children:[a.jsxs(T,{display:"flex",gap:1,alignItems:"center",children:[a.jsx(T,{color:"primary.main",children:a.jsx(du,{size:20})}),a.jsx(I,{variant:"h6",children:"AI Analysis"}),a.jsxs(T,{display:"flex",gap:1,alignItems:"center",children:[e&&a.jsx(Ze,{size:16}),a.jsx(I,{children:e?y_[s]:""})]}),a.jsx(Ie,{onClick:()=>l(!o),size:"small",sx:{ml:"auto"},children:o?a.jsx(yU,{}):a.jsx(vU,{})})]}),a.jsxs(Yt,{in:!o&&!e,children:[r&&a.jsx(I,{variant:"body2",color:"error.main",padding:2,children:"Failed to perform AI analysis"}),t&&a.jsx(I,{variant:"body2",color:"text.secondary",padding:2,children:t}),n.length>0&&a.jsxs($,{children:[a.jsx(I,{variant:"subtitle1",sx:{ml:2},children:"Suggested actions:"}),a.jsx($,{mt:2,spacing:1.5,children:n.map(c=>a.jsx(Xue,{description:c.description,prompt:c.prompt,title:c.title},`${c.title}-${c.prompt}`))})]})]})]})})},epe=({details:e})=>e?a.jsxs(Ka,{disableGutters:!0,elevation:0,sx:{mt:2,py:1,bgcolor:"transparent",border:"1px solid",borderColor:"border.default",borderRadius:1,"&:before":{display:"none"}},children:[a.jsx(Qa,{expandIcon:a.jsx(T,{color:"error.dark",display:"flex",alignItems:"center",children:a.jsx(vs,{size:16})}),sx:{minHeight:0,"& .MuiAccordionSummary-content":{my:.5}},children:a.jsx(I,{variant:"body2",sx:{fontWeight:500,color:"error.dark"},children:"Details"})}),a.jsx(Ja,{sx:{pt:0},children:a.jsx(T,{mt:1,sx:{maxHeight:240,overflow:"auto"},children:a.jsx(I,{component:"pre",variant:"body2",sx:{whiteSpace:"pre-wrap",fontFamily:"monospace",fontSize:12,color:"error.main"},children:JSON.stringify(e,null,2)})})})]}):null,tpe=e=>!!e&&typeof e=="object",npe=e=>{if(!e)return{error:null};const{Cause:t,Error:n}=e;if(tpe(t)){const{ErrorMessage:r,errorMessage:s,...i}=t,o=(typeof r=="string"?r:void 0)??(typeof s=="string"?s:void 0);return typeof o=="string"?{error:o,details:i}:{error:n,details:i}}return typeof t=="string"?{error:t}:{error:n}},UL=({isLoading:e,traceback:t=[]})=>{if(e)return null;const n=t.at(-1),r=npe(n);return r.error?a.jsxs(T,{sx:{backgroundColor:"error.light",borderRadius:2,p:2},children:[a.jsxs($,{direction:"row",spacing:1,alignItems:"center",mb:1,children:[a.jsx(T,{color:"error.main",display:"flex",alignItems:"center",children:a.jsx(wl,{size:18})}),a.jsx(I,{variant:"subtitle2",sx:{fontWeight:600,color:"error.dark"},children:"Error Message"})]}),a.jsx(I,{color:"error.dark",sx:{wordBreak:"break-word"},children:r.error}),a.jsx(epe,{details:r.details})]}):null},rpe=({href:e,isLoading:t,isError:n})=>t?a.jsx(fe,{width:120,height:24}):e?a.jsxs(xm,{href:e,target:"_blank",rel:"noopener noreferrer",underline:"hover",sx:{display:"inline-flex",alignItems:"center",gap:.5},children:["Step Function",a.jsx(Xv,{size:12})]}):n?a.jsx(I,{variant:"body2",color:"error.main",children:"Error loading execution link"}):a.jsx(I,{variant:"body2",color:"text.secondary",children:"Not available"}),spe=({status:e,executionUrl:t,isLoading:n,isError:r})=>a.jsxs(T,{sx:{backgroundColor:"background.neutral.default",borderRadius:2,p:2},children:[a.jsx(I,{mb:1.5,variant:"h6",children:"Job Information"}),a.jsxs($,{spacing:2,children:[a.jsxs(T,{children:[a.jsx(I,{variant:"body2",color:"text.secondary",sx:{mb:.5},children:"Job Status"}),a.jsx(Nu,{status:e??null,isLoading:n,isError:r,size:"small"})]}),a.jsxs(T,{children:[a.jsx(I,{variant:"body2",color:"text.secondary",sx:{mb:.5},children:"Step Function ARN"}),a.jsx(rpe,{href:t,isLoading:n,isError:r})]})]})]}),ipe=({actions:e,dataSourceId:t,open:n,onClose:r,row:s})=>{const i=s?.id,{data:o,isLoading:l,isFetching:c,isError:d}=bV({dataSourceId:t,partitionId:i??0},{skip:!n||!i}),u=s?.jobState==="FAILED",p=n&&i&&t&&u,{data:h,isFetching:f,isError:g}=yV({dataSourceId:t,partitionId:i??0},{skip:!p,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1}),x=h?.task_id,b=h?.task_status==="completed",[y,v]=m.useState(!1),{data:C,isError:w}=vV({taskId:x??""},{skip:!x||y||b,pollingInterval:8e3,refetchOnFocus:!1});m.useEffect(()=>{["COMPLETED","FAILED","CANCELLED"].includes(C?.status??"")&&v(!0)},[C?.status]);const S=!n||g||y||b,E=h?.response?.summary??C?.result?.summary,k=h?.response?.suggestions??C?.result?.suggestions,j=s?.partitionDate??"...";return a.jsxs(yt,{open:n,onClose:r,fullWidth:!0,maxWidth:"sm",children:[a.jsx(vt,{sx:{py:1.5},children:a.jsxs($,{direction:"row",spacing:1.5,alignItems:"center",children:[a.jsx(T,{color:"primary.main",display:"flex",children:a.jsx(Si,{size:20})}),a.jsx(I,{variant:"h6",sx:{flexGrow:1},children:`Partition Details: ${j}`}),e?.length?a.jsx($,{direction:"row",spacing:.5,children:e.map(_=>a.jsx(Ji,{..._},_.ariaLabel))}):null]})}),a.jsxs(Ct,{children:[a.jsx(I,{variant:"body2",color:"text.secondary",children:"Detailed information about this data partition"}),a.jsxs(T,{sx:{pt:1,display:"flex",flexDirection:"column",gap:2.5},children:[a.jsx(spe,{status:o?.status,executionUrl:o?.executionUrl,isLoading:l||c,isError:d}),u?a.jsx(Zue,{isLoading:f||!S,summary:E,suggestions:k,error:w||g}):null,a.jsx(UL,{isLoading:l||c,traceback:l||c?void 0:o?.traceback})]})]}),a.jsx(un,{sx:{pb:2,px:3},children:a.jsx(re,{onClick:r,variant:"outlined",color:"secondary",children:"Close"})})]})},ape=({disabled:e,endDate:t,setEndDate:n,setStartDate:r,startDate:s})=>a.jsxs(T,{sx:{display:"flex",gap:2,mb:2.5},children:[a.jsx(eo,{disabled:e,format:"YYYY-MM-DD",label:"Start Date",onCh
188ange:i=>r(i),slotProps:{textField:{fullWidth:!0,placeholder:"yyyy-mm-dd",required:!0}},value:s}),a.jsx(eo,{disabled:e,format:"YYYY-MM-DD",label:"End Date (Optional)",...s&&{minDate:s},onChange:i=>n(i),slotProps:{textField:{error:!!(t&&s&&t.isBefore(s)),fullWidth:!0,placeholder:"yyyy-mm-dd"}},value:t})]}),ope=({children:e,loading:t,onClose:n,onRun:r,open:s,runDisabled:i,selectedCount:o,totalCount:l})=>a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",onClose:n,open:s,PaperProps:{sx:{borderRadius:2}},children:[a.jsxs(vt,{sx:{alignItems:"center",display:"flex",gap:1,pb:2,pt:2.5,px:3},children:[a.jsx(Gs,{sx:{color:"primary.main",fontSize:28}}),a.jsx(I,{component:"span",sx:{flex:1,fontSize:20,fontWeight:600},children:"Run New Partitions"}),a.jsx(Ie,{"aria-label":"Close dialog",disabled:t,onClick:n,size:"small",sx:{color:"text.secondary"},children:a.jsx(ji,{})})]}),a.jsx(Ct,{sx:{px:3,py:2},children:e}),a.jsxs(un,{sx:{justifyContent:"space-between",px:3,py:2},children:[a.jsxs(I,{sx:{color:"text.secondary",fontSize:14},children:[o," of ",l," data sources selected"]}),a.jsxs(T,{sx:{display:"flex",gap:1.5},children:[a.jsx(re,{disabled:t,onClick:n,sx:{textTransform:"none"},variant:"outlined",children:"Cancel"}),a.jsx(re,{disabled:i,onClick:r,startIcon:a.jsx(Gs,{}),sx:{textTransform:"none"},variant:"contained",children:"Run Partitions"})]})]})]}),lpe=({disabled:e,nameById:t,onChange:n,selectedIds:r,sortedActiveDataSources:s})=>a.jsxs(Qe,{fullWidth:!0,sx:{mb:2.5},children:[a.jsx(wt,{id:"batch-run-datasources-label",children:"Data Sources to Run"}),a.jsx(tt,{disabled:e,input:a.jsx(ys,{label:"Data Sources to Run"}),labelId:"batch-run-datasources-label",multiple:!0,onChange:n,renderValue:i=>a.jsx(T,{sx:{display:"flex",flexWrap:"wrap",gap:.5},children:i.map(o=>a.jsx(ut,{label:t.get(o)??o,size:"small"},o))}),value:r,children:s.length===0?a.jsx(Se,{disabled:!0,value:-1,children:"No active data sources"}):s.map(i=>a.jsxs(Se,{value:i.id,children:[a.jsx(et,{checked:r.includes(i.id)}),a.jsx(Kt,{primary:Mr(i)})]},i.id))})]}),cpe=({checked:e,disabled:t,onChange:n})=>a.jsx(T,{sx:{backgroundColor:"background.neutral.default",border:1,borderColor:"border.default",borderRadius:1.5,p:2},children:a.jsx(sn,{control:a.jsx(Dn,{checked:e,disabled:t,onChange:r=>n(r.target.checked)}),label:a.jsxs(T,{children:[a.jsx(I,{sx:{color:"text.primary",fontWeight:600},children:"Skip Successfully Completed Steps"}),a.jsx(I,{sx:{color:"text.secondary",fontSize:14},children:"Only re-run steps that previously failed or haven't been executed"})]}),sx:{alignItems:"flex-start",m:0}})}),dpe=({allStepsSelected:e,disabled:t,onToggleAll:n,onToggleStep:r,processingSteps:s,selectedSteps:i})=>a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between",mb:1.5,mt:2.5},children:[a.jsx(I,{sx:{fontWeight:600},children:"Select Steps to Run"}),a.jsx(re,{disabled:t,onClick:n,size:"small",sx:{color:"primary.main",fontSize:14,textTransform:"none"},children:e?"Unselect All":"Select All"})]}),a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:s.map(o=>a.jsx(BL,{checked:i.includes(o.niceId),disabled:t,handleToggleStep:r,step:o},o.niceId))})]}),upe=()=>Object.values(iw).map(e=>({...e,isEnabled:!0})),ppe=(e,t)=>{const{results:n}=e,r=(d,u)=>t.get(d)??u??String(d);let s=0;const i=[],o=[],l=[];n.forEach(d=>{const u=r(d.datasource_id,d.datasource_name),p=d.executed_jobs?.length??0;if(d.error){o.push(`${u} (${d.error})`);return}p>0?(s+=p,i.push(u)):(d.blocked_partitions?.length??0)>0&&l.push(u)});const c=[];return i.length>0&&c.push(`Started ${s} partition run${s===1?"":"s"} across ${i.length} data source${i.length===1?"":"s"}.`),l.length>0&&c.push(`Skipped (no runnable partitions): ${l.join(", ")}.`),o.length>0&&c.push(`Failed: ${o.join(", ")}.`),i.length===0?{content:c.length>0?c.join(" "):"No partition runs were started.",severity:o.length>0?"error":"warning"}:{content:c.join(" "),severity:o.length>0?"warning":"success"}},hpe=({activeDataSources:e,isRunning:t,onClose:n,onRun:r,open:s})=>{const{pushNotification:i}=jt(),o=m.useMemo(()=>upe(),[]),[l,c]=m.useState([]),[d,u]=m.useState(null),[p,h]=m.useState(null),[f,g]=m.useState(!1),[x,b]=m.useState(Zf(o)),y=m.useMemo(()=>Qb(e,O=>O.content_type,O=>O.vendor_nice_id,O=>O.feed_nice_id),[e]),v=m.useMemo(()=>new Map(y.map(O=>[O.id,Mr(O)])),[y]);m.useEffect(()=>{s&&(c([]),u(null),h(null),g(!1),b(Zf(o)))},[s,o]);const C=O=>{const{value:R}=O.target;
188c(typeof R=="string"?R.split(",").map(Number):R)},w=O=>{b(R=>R.includes(O)?R.filter(L=>L!==O):[...R,O])},S=()=>{const O=o.filter(R=>R.isEnabled);b(x.length===O.length?[]:O.map(R=>R.niceId))},E=x.length,k=o.filter(O=>O.isEnabled).length,j=E===k,_=!!d&&(!p||!p.isBefore(d)),D=l.length===0||E===0||!_||t,M=()=>{n()},N=async()=>{const O=d?.format("YYYY-MM-DD");if(!O)return;const R=await r({dataSourceIds:l,endDate:p?.format("YYYY-MM-DD"),executionDate:O,executionSteps:x,skipCompleted:f});if("data"in R){const{content:L,severity:P}=ppe(R.data,v);i({content:L,severity:P}),n()}else i({content:"Failed to start batch partition run",severity:"error"})};return a.jsx(xu,{dateAdapter:Cu,children:a.jsxs(ope,{loading:t,onClose:M,onRun:N,open:s,runDisabled:D,selectedCount:l.length,totalCount:e.length,children:[a.jsx(I,{sx:{color:"text.secondary",mb:2},children:"Select the date range and the active data sources to run. Each data source runs its configured processing steps."}),a.jsx(ape,{disabled:t,endDate:p,setEndDate:h,setStartDate:u,startDate:d}),a.jsx(lpe,{disabled:t,nameById:v,onChange:C,selectedIds:l,sortedActiveDataSources:y}),a.jsx(cpe,{checked:f,disabled:t,onChange:g}),a.jsx(dpe,{allStepsSelected:j,disabled:t,onToggleAll:S,onToggleStep:w,processingSteps:o,selectedSteps:x})]})})},fpe=({apiRef:e,columns:t,columnVisibilityModel:n,loading:r,onApplyDefault:s,onApplyView:i,onColumnVisibilityChange:o,onDeleteView:l,onSaveView:c,selectedViewName:d,views:u})=>a.jsx(Pu,{left:a.jsxs(a.Fragment,{children:[a.jsx(Ou,{columns:t,columnVisibilityModel:n,disabled:r,onChange:o}),a.jsx(cg,{disabled:r,onApplyDefault:s,onApplyView:i,onDeleteView:l,onSaveView:c,selectedViewName:d,views:u})]}),right:a.jsx(Lu,{apiRef:e,loading:r})}),VL=({allSources:e})=>{const{dataSources:t,dispatch:n,editEnabled:r,gridApiRefs:s,handleStopPartition:i,partitions:o,partitionsLoading:l,refetchPartitions:c,state:d,stoppingPartition:u}=Je(),{dialogOpen:p,selectedDataSource:h,selectedPartition:f}=d,{handleRunPartitionBatch:g,isRunning:x}=cue(),[b,y]=m.useState({}),[v,C]=m.useState(!1),w=e?s.allSourcesPartitions:s.singleSourcePartitions,S=Fu({apiRef:w,onApplyState:B=>y(B.columns?.columnVisibilityModel??{}),storageKey:e?"dataProcessing:views:allSources":"dataProcessing:views:singleSource"}),E=e||h?.content_type==="agg",k=m.useMemo(()=>Vue({allSources:e,editEnabled:r,showMetricColumns:E}),[e,r,E]),j=m.useMemo(()=>e?o:o.filter(B=>B.datasourceId===h?.id),[e,o,h]),_=m.useMemo(()=>t.filter(B=>B.active),[t]),D=e?t.find(B=>B.id===f?.datasourceId)??null:h,M=o.find(B=>B.id===f?.id)??f,N=m.useCallback(()=>{n({type:"selectedPartition",value:null}),n({type:"dialogOpen",value:"runNewPartition"})},[n]),O=m.useCallback(()=>{n({type:"dialogOpen",value:null}),n({type:"selectedPartition",value:null})},[n]),R=m.useCallback(()=>{n({type:"dialogOpen",value:"runPartition"})},[n]),L=m.useCallback(()=>{n({type:"dialogOpen",value:"stopPartition"})},[n]),P=FL({dataSource:D,status:M?.jobState,updatedAt:M?.updatedAt}),F=$L({editEnabled:r,status:M?.jobState}),z=[...r?[{ariaLabel:"Run data processing job",color:"success",disabled:P.disabled,icon:og,onClick:R,tooltip:P.message||"Run data processing job"}]:[],...F?[{ariaLabel:"Stop data processing run",color:"error",disabled:u,icon:lg,iconSize:36,onClick:L,tooltip:"Stop data processing run"}]:[]];return a.jsxs(a.Fragment,{children:[a.jsxs($,{sx:{alignItems:"center",flexDirection:"row",justifyContent:"flex-end",gap:1,mb:4},children:[a.jsx(be,{title:"Refresh",children:a.jsx("span",{children:a.jsx(Ie,{"aria-label":"Refresh partitions",disabled:l,onClick:()=>c(),children:a.jsx(rw,{})})})}),e?a.jsx(re,{disabled:!r,onClick:()=>C(!0),startIcon:a.jsx(Gs,{}),sx:{textTransform:"none"},variant:"contained",children:"Run New Partitions"}):a.jsx(be,{title:h?.active?"":"This action is currently unavailable. The data source is inactive.",children:a.jsx(T,{children:a.jsx(re,{disabled:!r,onClick:N,startIcon:a.jsx(Gs,{}),sx:{textTransform:"none"},variant:"contained",children:"Run New Partition"})})})]}),a.jsx(T,{children:a.jsx(ag,{apiRef:w,columns:k,columnVisibilityModel:b,disableRowSelectionOnClick:!0,hideFooter:j.length<25,hideFooterSelectedRowCount:!0,initialState:{pagination:{paginationModel:{pageSize:25}}},loading:l,onColumnVisibilityModelChange:y,pageSizeOptions:[10,25,50,100],pagination:!0,rows:j,slots:{noRowsOverlay:Wue,toolbar:fpe},slotProps:{toolbar:{apiRef:w,columns:k,columnVisibilityModel:b,loading:l,onApplyView:S.applyView,onApplyDefault:S.applyDefault,onColumnVisibilityChange:y,onDeleteView:S.deleteView,onSaveView:S.saveView,selectedViewName:S.selectedViewName,views:S.views}}})}),a.jsx(Hue,{editEnabled:r,open:p==="notes",onClose:O,row:f}),D?a.jsx(Jue,{dataSource:D,open:p==="runNewPartition"||p==="runPartition",onClose:O,partitionDate:f?.partitionDate??null,newPartition:p==="runNewPartition"}):null,f?a.jsxs(a.Fragment,{children:[a.jsx(sw,{handleClose:O,handleStop:()=>i({dataSourceId:f.datasourceId,partitionId:f.id}),jobLabel:`${f.datasourceName??f.datasourceNiceId} (${f.partitionDate})`,open:p==="stopPartition"}),a.jsx(ipe,{actions:z,dataSourceId:f.datasourceId,open:p==="partitionDetail
188s",onClose:O,row:f})]}):null,e?a.jsx(hpe,{activeDataSources:_,isRunning:x,onClose:()=>C(!1),onRun:g,open:v}):null]})},mpe=()=>a.jsx(VL,{allSources:!0}),gpe=()=>{const{dataSourcesListDispatch:e,handleUpdateDataSourceField:t,dataSourcesListState:{selectedSourceForAction:n}}=Je();if(!n)return null;const{name:r,active:s,id:i}=n,o=()=>e({type:"selectedSourceForAction",value:null}),l=async()=>{await t({id:i,field:"active",value:!s}),o()},c=a.jsxs(a.Fragment,{children:[a.jsxs(I,{children:["Are you sure you want to ",s?"deactivate":"activate","Â ",a.jsx(I,{component:"span",sx:{color:"primary.main",fontWeight:"bold"},children:r}),"?"]}),a.jsx(I,{sx:{color:"text.secondary",mt:2},children:s?"This will stop data processing for this source.":"This will enable data processing for this source."})]});return a.jsx(mt,{body:c,acceptLabel:s?"Deactivate":"Activate",closeLabel:"Cancel",open:!0,handleAccept:l,handleClose:o,title:`${s?"Deactivate":"Activate"} Data Source?`,resetLoadingAfterAccept:!0})},xpe=({isSubmitting:e,isValid:t,onCancel:n,onSubmit:r})=>a.jsxs(T,{sx:{display:"flex",gap:1,justifyContent:"flex-end",pt:1},children:[a.jsx(re,{color:"secondary",disabled:e,onClick:n,children:"Cancel"}),a.jsx(Dt,{disabled:!t,loading:e,onClick:r,variant:"contained",children:"Create User"})]}),bpe=({errorMessage:e})=>a.jsx(Yt,{in:!!e,children:a.jsx(vn,{severity:"error",sx:{mb:2,bgcolor:"background.error.default",color:"text.primary","& .MuiAlert-icon":{color:"text.primary"}},children:e})}),ype=({isSubmitting:e,engagementNiceId:t})=>{const{watch:n,register:r,formState:{errors:s}}=on(),i=n("username");return a.jsxs($,{mt:1,spacing:2.5,children:[a.jsx(De,{autoFocus:!0,disabled:e,error:!!s.firstName,fullWidth:!0,helperText:s.firstName?.message,label:"First name",required:!0,...r("firstName")}),a.jsx(De,{disabled:e,error:!!s.lastName,fullWidth:!0,helperText:s.lastName?.message,label:"Last name",required:!0,...r("lastName")}),a.jsx(De,{disabled:e,error:!!s.email,fullWidth:!0,helperText:s.email?.message,label:"Email",required:!0,type:"email",...r("email")}),a.jsx(De,{disabled:e,fullWidth:!0,label:"Mobile phone (optional)",...r("phoneNumber")}),a.jsx(De,{disabled:e,error:!!s.username,fullWidth:!0,helperText:s.username?.message||"Auto-generated from name",label:"Username",required:!0,InputLabelProps:{shrink:!!i},...r("username")}),a.jsxs(T,{children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:14},children:"Engagement"}),a.jsx(I,{sx:{fontSize:14,fontWeight:500,mt:.5},children:t})]})]})},vpe=({email:e,setError:t,validateEmail:n})=>{const r=ct(),[s,i]=m.useState(!1),o=m.useCallback(async c=>{const{isValid:d}=await n(c);r()&&(i(d),d||t("email",{message:"Email already exists"}))},[r,t,n]),l=fs(o,1e3);return m.useEffect(()=>{i(!1),e&&l(e)},[l,e]),{validEmail:s}},Cpe=({setError:e,validateUsername:t,username:n})=>{const r=ct(),[s,i]=m.useState(!1),o=m.useCallback(async c=>{const{isValid:d}=await t(c);r()&&(i(d),d||e("username",{message:"Username already exists"}))},[r,e,t]),l=fs(o,1e3);return m.useEffect(()=>{i(!1),n&&l(n)},[l,n]),{validUsername:s}},Ap=()=>U.string().min(1),wpe=U.object({firstName:Ap(),lastName:Ap(),email:Ap().email(),phoneNumber:U.string().optional().or(U.literal("")),username:Ap()}),Spe=()=>{const{engagementNiceId:e}=pe(),{handleCreateContact:t,processingContacts:n,dataSourcesListState:r,dataSourcesListDispatch:s,validateEmail:i,validateUsername:o}=Je(),{dataToCreate:l,processingError:c,processingEvent:d}=r,u=Xs({resolver:Zs(wpe),mode:"onChange"}),p=d==="FailedUserCreation"?c:"",{watch:h,reset:f,setError:g,setValue:x,formState:{isValid:b},getValues:y}=u,v=h("firstName"),C=h("lastName"),w=h("email"),S=h("username"),{validEmail:E}=vpe({email:w,setError:g,validateEmail:i}),{validUsername:k}=Cpe({setError:g,validateUsername:o,username:S});m.useEffect(()=>{if(v?.trim()||C?.trim()){const D=`${v??""}.${C??""}`.replaceAll(/[^a-zA-Z0-9._]/g,"").toLowerCase();x("username",D,{shouldValidate:!0,shouldDirty:!0})}},[v,C,x]);const j=m.useCallback(()=>{f({firstName:"",lastName:"",email:"",phoneNumber:"",username:""}),s({type:"dataToCreate",value:null}),s({type:"processingError",value:""}),s({type:"processingEvent",value:""})},[s,f]),_=m.useCallback(async()=>{const D=y();l&&(t(l,D),j())},[l,y,j,t]);return a.jsxs(yt,{maxWidth:"sm",open:!!l,children:[a.jsxs(vt,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between",pb:1},children:[a.jsx(I,{sx:{fontSize:20,fontWeight:500},children:"Create an external user"}),a.jsx(Ie,{disabled:n,onClick:j,size:"small",children:a.jsx(Jt,{size:20})})]}),a.jsx(Ct,{sx:{width:480},children:a.jsx(Js,{...u,children:a.jsxs($,{mt:1,spacing:2.5,children:[a.jsx(ype,{engagementNiceId:e,isSubmitting:n}),a.jsx(bpe,{errorMessage:p}),a.jsx(xpe,{isSubmitting:n,isValid:b&&E&&k,onCancel:j,onSubmit:_})]})})})]})},jpe={color:"text.primary","& .MuiAlert-icon":{color:"text.primary"},display:"flex",alignItems:"center"},kpe=({isLimitReached:e,activeCount:t,availableLicenses:n})=>e?a.jsxs(vn,{severity:"warning",sx:{bgcolor:"background.warning.default",mb:2,...jpe},children:["Data source limit reached (",t,"/",n,"). Please deactivate existing data sources or contact support to increase your limit."]}):null,Epe=()=>
188{const{handleUpdateContacts:e,dataSourcesListState:{dataToRemove:t},dataSourcesListDispatch:n}=Je(),r=()=>{if(!t)return;const{dataSource:{id:c,contacts:d},contact:u}=t,p=d?.filter(({id:h})=>u.id!==h).map(h=>({id:h.id,is_primary:h.is_primary,is_private:h.is_private,name:h.name,is_internal:h.is_internal}));e(c,p||[]),n({type:"dataToRemove",value:null})},s=()=>{n({type:"dataToRemove",value:null})},i=t?.contact.name,o=t?.contact.isInternal?"Internal":"External",l=a.jsxs(I,{sx:{color:"text.secondary",fontSize:"0.75rem"},children:["Are you sure you want to remove ",a.jsx(I,{component:"span",sx:{fontWeight:600},children:i})," from this data source?"]});return a.jsx(mt,{body:l,closeLabel:"Cancel",acceptLabel:"Remove",handleClose:s,handleAccept:r,open:!!t,title:`Remove ${o} Contact`,resetLoadingAfterAccept:!0})},WL="lll",_pe=({row:e})=>{const{navigateToTab:t}=Je(),n=r=>{r.stopPropagation(),t({nextSource:e,nextView:"singleSource.configuration"})};return a.jsx(be,{title:"Configuration",children:a.jsx(Ie,{onClick:n,size:"small",children:a.jsx(sA,{size:18})})})},Tpe=({dataSource:e})=>{const{dataSourcesListDispatch:t,editEnabled:n}=Je(),r=()=>{t({type:"selectedSourceForAction",value:e})};return a.jsx(Dn,{checked:e.active,color:"primary",disabled:!n,onChange:r})},Ipe=({row:e})=>{const{allContacts:t,canManageUsers:n,dataSourcesListDispatch:r,editEnabled:s,handleUpdateContacts:i,processingContacts:o}=Je(),l=m.useMemo(()=>e.contacts?.filter(({is_internal:f})=>!f)??[],[e.contacts]),c=m.useMemo(()=>l.map(f=>({id:f.id,name:f.name,email:f.email,initials:Md(f.name),isInternal:!1})),[l]),d=m.useMemo(()=>{const f=new Set(l.map(g=>g.id));return t.filter(g=>!f.has(g.id)&&!g.is_internal).map(g=>({id:g.id,name:g.name,initials:Md(g.name),isInternal:!1}))},[l,t]),u=f=>{s&&r({type:"dataToRemove",value:{dataSource:e,contact:f}})},p=()=>{n&&r({type:"dataToCreate",value:e})},h=f=>{if(!s)return;const x=[...e.contacts?.map(b=>({id:b.id,is_private:b.is_private,is_primary:b.is_primary,name:b.name,is_internal:b.is_internal}))??[],{id:f.id,is_private:!1,is_primary:!1,name:f.name,is_internal:!1}];i(e.id,x)};return a.jsx(nR,{addTooltip:"Add external contact",allowUserCreation:n,availableContacts:d,canEdit:s,isUpdating:o,onAdd:h,onCreateNewUser:p,onClickRemove:u,selectedContacts:c})},Dpe=({row:e})=>{const t=$0({frequency:e.frequency,offset:e.freq_offset});return a.jsx(ut,{label:t,sx:{backgroundColor:"background.neutral.default",borderRadius:6,color:"text.primary",fontSize:11,fontWeight:500,height:26,minWidth:64}})},Ape=({row:e})=>{const{allContacts:t,canManageUsers:n,editEnabled:r,handleUpdateContacts:s,dataSourcesListDispatch:i,processingContacts:o}=Je(),l=m.useMemo(()=>e.contacts?.filter(({is_internal:h})=>h)??[],[e.contacts]),c=m.useMemo(()=>l.map(h=>({id:h.id,name:h.name,email:h.email,initials:Md(h.name),isInternal:!0})),[l]),d=m.useMemo(()=>{const h=new Set(l.map(f=>f.id));return t.filter(f=>!h.has(f.id)&&f.is_internal).map(f=>({id:f.id,name:f.name,initials:Md(f.name),isInternal:!0}))},[l,t]),u=h=>{r&&i({type:"dataToRemove",value:{dataSource:e,contact:h}})},p=h=>{if(!r)return;const g=[...e.contacts?.map(x=>({id:x.id,is_private:x.is_private,is_primary:x.is_primary,name:x.name,is_internal:x.is_internal}))??[],{id:h.id,is_private:!1,is_primary:!1,name:h.name,is_internal:!0}];s(e.id,g)};return a.jsx(nR,{addTooltip:"Add internal contact",allowUserCreation:n,availableContacts:d,canEdit:r,isUpdating:o,onAdd:p,onClickRemove:u,selectedContacts:c,onCreateNewUser:()=>{}})},Mpe=({row:e})=>{const{last_run_name:t,last_run_ts:n}=e;return n?a.jsxs(T,{sx:{display:"flex",flexDirection:"column",lineHeight:1.3},children:[a.jsx(I,{component:"span",sx:{fontSize:12},children:Z(n).format(WL)}),t&&a.jsx(I,{component:"span",sx:{color:"text.secondary",fontSize:11},children:t})]}):null},Rpe=({row:e})=>{const t=e.contacts?.find(({is_primary:n})=>n);return t?a.jsxs($,{sx:{width:"100%"},children:[a.jsx(I,{sx:{overflowX:"hidden",textOverflow:"ellipsis",textWrap:"nowrap"},children:t.name}),a.jsx(be,{title:"Click to copy email",children:a.jsx(T,{component:xm,onClick:()=>{const n=new ClipboardItem({"text/plain":t.email});navigator.clipboard.write([n])},sx:{overflowX:"hidden",textOverflow:"ellipsis",textWrap:"nowrap",":hover":{cursor:"copy"}},children:t.email})})]}):null},Vx=(e,t)=>e?t?Z(e).isBefore(Z(t))?-1:1:-1:1,xr={cellClassName:Xd.clickableColumn,flex:1}
188,Wx={cellClassName:Xd.clickableColumn,disableColumnMenu:!1,filterable:!0,filterOperators:wW(),flex:1,sortable:!0,type:"boolean"},HL=({userIsInternal:e})=>[{...xr,field:"id",flex:0,getApplyQuickFilterFn:n=>r=>typeof r.value!="number"?!1:r.value.toString().includes(n),headerName:Ge.id,renderCell:n=>n.value,type:"number",width:55},{...xr,field:"name",flex:1.5,headerName:Ge.name,minWidth:150,renderCell:({row:n})=>a.jsx("span",{style:{fontWeight:600},children:Mr(n)}),valueGetter:({row:n})=>Mr(n)},{...xr,field:"content_type",headerName:Ge.content_type,minWidth:80,valueGetter:({row:n})=>J0({contentType:n.content_type,measurementCategory:n.measurement_category})},{...xr,field:"vendor_nice_id",headerName:Ge.vendor_nice_id,minWidth:110},{...xr,field:"feed_nice_id",headerName:Ge.feed_nice_id,minWidth:90},{...xr,field:"frequency",headerName:Ge.frequency,minWidth:110,renderCell:({row:n})=>a.jsx(Dpe,{row:n}),valueGetter:({row:n})=>$0({frequency:n.frequency,offset:n.freq_offset})},e?{cellClassName:Xd.clickableColumn,field:"internal_assigned",flex:1,getApplyQuickFilterFn:n=>({row:r})=>{const s=r.contacts?.find(({is_internal:c})=>c);if(!s)return!1;const i=n.toLowerCase(),o=s.name.toLowerCase(),l=s.email?.toLowerCase();return o.includes(i)||l?.includes(i)},headerClassName:"wrap-header",headerName:Ge.internal_assigned,minWidth:100,renderCell:({row:n})=>a.jsx(Ape,{row:n}),renderHeader:()=>a.jsxs("span",{style:{lineHeight:1.2,textAlign:"center"},children:["INTERNAL",a.jsx("br",{}),"ASSIGNED"]})}:void 0,{cellClassName:Xd.clickableColumn,field:"external_contacts",flex:1,getApplyQuickFilterFn:n=>({row:r})=>Eie(r,n),headerClassName:"wrap-header",headerName:Ge.external_contacts,minWidth:100,renderCell:({row:n})=>a.jsx(Ipe,{row:n}),renderHeader:()=>a.jsxs("span",{style:{lineHeight:1.2,textAlign:"center"},children:["EXTERNAL",a.jsx("br",{}),"CONTACTS"]})},{...Wx,field:"active",headerName:Ge.active,minWidth:110,renderCell:({row:n})=>a.jsx(Tpe,{dataSource:n})},{...Wx,field:"validation_active",headerName:Ge.validation_active,minWidth:105,renderCell:({value:n})=>a.jsx(Ky,{value:!!n})},{...xr,field:"delivery_method",headerName:Ge.delivery_method,minWidth:100},{...xr,field:"created_at",headerName:Ge.created_at,minWidth:120,sortComparator:Vx,valueGetter:({value:n})=>Z(n).format("ll")},{...xr,field:"updated_at",headerName:Ge.updated_at,minWidth:120,sortComparator:Vx,valueGetter:({value:n})=>Z(n).format("ll")},{...xr,field:"last_run_state",headerName:Ge.last_run_state,minWidth:105,renderCell:({value:n})=>a.jsx(Nu,{status:n??null})},{...xr,field:"last_run_ts",getApplyQuickFilterFn:n=>({row:r})=>{const s=n.toLowerCase(),i=Z(r.last_run_ts).format(WL).toLowerCase(),o=r.last_run_name?.toLowerCase()??"";return i.includes(s)||o.includes(s)},headerName:Ge.last_run_ts,minWidth:100,width:100,flex:0,sortComparator:Vx,renderCell:({row:n})=>a.jsx(Mpe,{row:n})},{...Wx,field:"supervisor_scheduling",headerName:Ge.supervisor_scheduling,minWidth:105,renderCell:({value:n})=>a.jsx(Ky,{value:!!n})},{...xr,field:"file_extension",headerName:Ge.file_extension,minWidth:75,valueGetter:({value:n})=>Yf(n)},{...xr,field:"file_compression",headerName:Ge.file_compression,minWidth:100,valueGetter:({value:n})=>Yf(n)},{...xr,field:"path",headerName:Ge.path,minWidth:200},{...xr,field:"file_filter",headerName:Ge.file_filter,minWidth:170},{flex:1,field:"contacts",getApplyQuickFilterFn:n=>({row:r})=>{const s=r.contacts?.find(({is_primary:c})=>c);if(!s)return!1;const i=n.toLowerCase(),o=s.name.toLowerCase(),l=s.email?.toLowerCase()??"";return o.includes(i)||l.includes(i)},headerName:Ge.primary_contact,minWidth:200,renderCell:({row:n})=>a.jsx(Rpe,{row:n})},{align:"center",disableColumnMenu:!0,field:"actions",filterable:!1,headerAlign:"center",headerName:Ge.actions,minWidth:80,renderCell:({row:n})=>a.jsx(_pe,{row:n}),sortable:!1,width:80}].filter(n=>!!n),Npe=e=>HL({userIsInternal:e}).map(({field:t})=>t).reduce((t,n)=>({...t,[n]:!1}),{}),Ope=({userIsInternal:e})=>({...Npe(e),actions:!0,active:!0,content_type:!0,external_contacts:!0,feed_nice_id:!0,frequency:!0,id:!0,internal_assigned:e,last_run_state:!0,last_run_ts:!0,name:!0,vendor_nice_id:!0}),Ppe=({apiRef:e,loading:t,onActiveFilterChange:n,showActiveOnly:r,viewControl
188s:s})=>{const{dataSourcesListDispatch:i,dataSourcesListState:o}=Je(),{columns:l,columnVisibilityModel:c}=o;return a.jsx(Pu,{left:a.jsxs(a.Fragment,{children:[a.jsx(Ou,{columns:l,columnVisibilityModel:c,disabled:t,onChange:d=>i({type:"columnVisibilityModel",value:d})}),a.jsx(cg,{...s}),a.jsx(OL,{checked:r,onChange:n})]}),right:a.jsx(Lu,{apiRef:e,loading:t})})},v_={field:"active",operator:"is",value:"true"},Lpe=()=>{const{dataSources:e,dataSourcesListDispatch:t,gridApiRefs:{dataSourcesList:n},handleViewDataSource:r,dataSourcesLoading:s,dataSourcesListState:i}=Je(),{columns:o,columnVisibilityModel:l}=i,[c,d]=m.useState({items:[v_]}),u=Fu({apiRef:n,onApplyState:g=>{t({type:"columnVisibilityModel",value:g.columns?.columnVisibilityModel??{}}),d(g.filter?.filterModel??{items:[]})},storageKey:"dataSources:views:overview"}),p=m.useMemo(()=>c.items.some(g=>g.field==="active"&&g.value==="true"),[c]),h=g=>{d(x=>{const b=x.items.filter(y=>y.field!=="active");return g?{...x,items:[...b,v_]}:{...x,items:b}})},f=({colDef:g,row:x})=>{g.field!=="internal_assigned"&&g.field!=="external_contacts"&&g.field!=="active"&&g.field!=="actions"&&r(x)};return a.jsx(ag,{apiRef:n,columns:o,columnVisibilityModel:l,filterModel:c,loading:s,onCellClick:f,onFilterModelChange:d,rows:s?[]:e,slots:{toolbar:Ppe},slotProps:{toolbar:{apiRef:n,loading:s,onActiveFilterChange:h,showActiveOnly:p,viewControls:{disabled:s,onApplyDefault:u.applyDefault,onApplyView:u.applyView,onDeleteView:u.deleteView,onSaveView:u.saveView,selectedViewName:u.selectedViewName,views:u.views}}}})},Hx=({type:e,count:t,loading:n})=>{const r=()=>{switch(e){case"active":return"success.main";case"attention":return"error.main";default:return"text.secondary"}},s=()=>{switch(e){case"active":return"Active Sources";case"attention":return"Sources Need Attention";default:return"Inactive Sources"}},i=r();return a.jsxs($,{sx:{alignItems:"center",backgroundColor:"background.paper",border:"1px solid",borderColor:"divider",borderRadius:"6px",justifyContent:"center",p:2,width:250},children:[a.jsx(I,{sx:{color:i,fontSize:32,fontWeight:700,lineHeight:1},children:n?"...":t}),a.jsx(I,{sx:{color:i,fontSize:16,fontWeight:500,mt:.5},children:s()})]})},Fpe=()=>{const{dataSourcesListState:{processingError:e,processingEvent:t},dataSourcesListDispatch:n}=Je(),{open:r,severity:s,message:i}=m.useMemo(()=>t==="FailedAssignment"?{open:!0,severity:"error",message:e}:t==="Success"?{open:!0,severity:"success",message:"Contacts successfully updated"}:{open:!1,severity:"success",message:""},[e,t]),o=()=>{n({type:"processingError",value:""}),n({type:"processingEvent",value:""})};return a.jsx(DD,{open:r,onClose:o,anchorOrigin:{horizontal:"center",vertical:"top"},autoHideDuration:5e3,children:a.jsx(vn,{severity:s,children:i})})},$pe=()=>{const{activeSourcesCount:e,availableLicenses:t,dataSources:n,dataSourcesLoading:r,inactiveSourcesCount:s,isDataSourceLimitReached:i}=Je(),o=m.useMemo(()=>n.filter(l=>l.last_run_state==="FAILED").length,[n]);return a.jsxs($,{sx:{rowGap:2,width:"100%"},children:[a.jsxs($,{sx:{flexDirection:"row",gap:2,mb:1},children:[a.jsx(Hx,{type:"active",count:e,loading:r}),a.jsx(Hx,{type:"inactive",count:s,loading:r}),a.jsx(Hx,{type:"attention",count:o,loading:r})]}),a.jsx(kpe,{activeCount:e,availableLicenses:t,isLimitReached:i}),a.jsx(Lpe,{}),a.jsx(Epe,{}),a.jsx(Spe,{}),a.jsx(gpe,{}),a.jsx(Fpe,{})]})},ev={overview:{label:"Overview",value:"allSources.list",authorized:"DataSources.Configurations"},dataProcessing:{label:"Data Processing",value:"allSources.partitions",authorized:"DataSources.Configurations"}},C_=Object.values(ev),zpe=()=>{const{editEnabled:e,navigateToTab:t,state:{view:n}}=Je(),r=m.useCallback(s=>{const i=C_.find(o=>o.value===s)?.value;i&&t({nextSource:null,nextView:i})},[t]);return a.jsxs($,{sx:{width:"100%",minWidth:600,rowGap:4},children:[a.jsxs($,{sx:{flexDirection:"row",justifyContent:"space-between",alignItems:"center"},children:[a.jsxs($,{sx:{rowGap:1},children:[a.jsx(Xt,{title:"Data Sources Configurations"}),a.jsx(I,{sx:{color:"text.secondary",fontSize:14},children:"Manage and monitor all your data sources in one centralized location"})]}),e&&a.jsx(fue,{})]}),a.jsxs(fo,{onChange:r,tabs:C_,value:n,children:[a.jsx(xt,{sx:{p:0,pt:3},value:ev.overview.value,children:a.jsx($pe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:ev.dataProcessing.value,children:a.jsx(mpe,{})})]}),a.jsx(yue,{})]})},Bpe=()=>a.jsx(VL,{allSources:!1}),$u=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je();return e?a.jsx(T,{height:40}):a.jsxs(T,{sx:{height:40,pl:3},children:[a.jsxs(I,{sx:{fontWeight:400},color:"textSecondary",component:"p",variant:"caption",children:["Created ",Z(t?.created_at).format("LLL")]}),a.jsxs(I,{sx:{fontWeight:400},color:"textSecondary",component:"p",variant:"caption",children:["Updated ",Z(t?.updated_at).format("LLL")]})]})},Upe=()=>a.jsx(Ru,{mainContent:a.jsxs(a.Fragment,{children:[a.jsx(Fde,{}),a.jsx(Qde,{}),a.jsx($de,{}),a.jsx(sg,{nextView:"singleSource.summary"})]}),sideContent:a.jsx($u,{})}),Vpe=()=>a.jsx(Ru,{mainContent:a.jsxs(a.Fragment,{children:[a.jsx(Hde,{}),a.jsx(sg,{nextView:"singleSource.schedule"})]}),sideContent:a.jsx($u,{})}),Wpe=()=>a.jsx(Ru,{mainContent:a.jsxs(a.Fragment,{children:[a.jsx(Wde,{}),a.jsx(Lde,{}),a.jsx(Vde,{}),a.jsx(sg,{nextView:"singleSource.mapAndTransform",saveText:"Proceed to Map and Transform"})]}),sideContent:a.jsx($u,{})}),Hpe=()=>a.jsx(Ru,{mainContent:a.jsxs(a.Fragment,{children:[a.jsx(Xde,{}),a.jsx(sg,{nextView:"singleSource.summary"})]}),sideContent:a.jsxs(a.Fragment,{children:[a.jsx(_de,{}),a.jsx($u,{})]})}),qpe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je();return a.jsx(T,{sx:{display:"flex",justifyContent:"space-between",pb:2},children:a.jsx(T,{sx:{display:"flex",overflow:"hidden",alignItems:"center",gap:2,height:40},children:e?a.jsx(fe,{sx:{fontSize:24,width:300},variant:"text"}):a.jsx(I,{sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},variant:"h5",children:Mr(t)})})})},Gpe=({handleClose:e})=>{const{dispatch:t,handleUpdateDataSourceField:n,state:{selectedDataSource:r}}=Je(),[s,i]=m.useState(r?.notes??""),[o,l]=m.useState(!1),c=()=>{i(r?.notes??""),e()},d=async()=>
188{if(l(!0),!r)return;const u=await n({field:"notes",id:r.id,value:s});if(l(!1),"error"in u){window.alert("There was an error while updating the datasource, please try again later");return}t({type:"selectedDataSource",value:{...r,notes:s}}),e()};return a.jsxs($,{width:"100%",gap:2,children:[a.jsx(cu,{height:500,value:s,onChange:i}),a.jsxs($,{direction:"row",justifyContent:"flex-end",gap:1,children:[a.jsx(re,{disabled:o,onClick:c,children:"Discard changes"}),a.jsx(Dt,{disabled:o,loading:o,variant:"contained",onClick:d,children:"Save"})]})]})},Ype=({handleDoubleClick:e,notes:t})=>a.jsx(T,{width:"100%",onDoubleClick:e,children:a.jsx(ms,{markdownText:t??"No notes were added."})}),Kpe=()=>{const{dataSourcesLoading:e,editEnabled:t,state:{selectedDataSource:n}}=Je(),[r,s]=m.useState(!1);return a.jsx(Nt,{isLoading:e,children:a.jsx(Ve,{children:a.jsx(Ue,{sx:{display:"flex",justifyContent:"center",cursor:"default",width:"100%",maxHeight:"600px",overflow:"auto"},children:r?a.jsx(Gpe,{handleClose:()=>s(!1)}):a.jsx(Ype,{handleDoubleClick:()=>s(t),notes:n?.notes})})})})};var ai={},oi={},qx={},w_;function Qpe(){return w_||(w_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=1,n=function(){return"".concat(t++)};e.default=n})(qx)),qx}var kc={},Ec={},Gx={},S_;function qL(){return S_||(S_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(r){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:60,i=null;return function(){for(var o=this,l=arguments.length,c=new Array(l),d=0;d<l;d++)c[d]=arguments[d];clearTimeout(i),i=setTimeout(function(){r.apply(o,c)},s)}};e.default=t})(Gx)),Gx}var li={},j_;function aw(){if(j_)return li;j_=1,Object.defineProperty(li,"__esModule",{value:!0}),li.SizeSensorId=li.SensorTabIndex=li.SensorClassName=void 0;var e="size-sensor-id";li.SizeSensorId=e;var t="size-sensor-object";li.SensorClassName=t;var n="-1";return li.SensorTabIndex=n,li}var k_;function Jpe(){if(k_)return Ec;k_=1,Object.defineProperty(Ec,"__esModule",{value:!0}),Ec.createSensor=void 0;var e=n(qL()),t=aw();function n(s){return s&&s.__esModule?s:{default:s}}var r=function(i,o){var l=void 0,c=[],d=function(){getComputedStyle(i).position==="static"&&(i.style.position="relative");var x=document.createElement("object");return x.onload=function(){x.contentDocument.defaultView.addEventListener("resize",u),u()},x.style.display="block",x.style.position="absolute",x.style.top="0",x.style.left="0",x.style.height="100%",x.style.width="100%",x.style.overflow="hidden",x.style.pointerEvents="none",x.style.zIndex="-1",x.style.opacity="0",x.setAttribute("class",t.SensorClassName),x.setAttribute("tabindex",t.SensorTabIndex),x.type="text/html",i.appendChild(x),x.data="about:blank",x},u=(0,e.default)(function(){c.forEach(function(g){g(i)})}),p=function(x){l||(l=d()),c.indexOf(x)===-1&&c.push(x)},h=function(){l&&l.parentNode&&(l.contentDocument&&l.contentDocument.defaultView.removeEventListener("resize",u),l.parentNode.removeChild(l),i.removeAttribute(t.SizeSensorId),l=void 0,c=[],o&&o())},f=function(x){var b=c.indexOf(x);b!==-1&&c.splice(b,1),c.length===0&&l&&h()};return{element:i,bind:p,destroy:h,unbind:f}};return Ec.createSensor=r,Ec}var _c={},E_;function Xpe(){if(E_)return _c;E_=1,Object.defineProperty(_c,"__esModule",{value:!0}),_c.createSensor=void 0;var e=aw(),t=n(qL());function n(s){return s&&s.__esModule?s:{default:s}}var r=function(i,o){var l=void 0,c=[],d=(0,t.default)(function(){c.forEach(function(g){g(i)})}),u=function(){var x=new ResizeObserver(d);return x.observe(i),d(),x},p=function(x){l||(l=u()),c.indexOf(x)===-1&&c.push(x)},h=function(){l.disconnect(),c=[],l=void 0,i.removeAttribute(e.SizeSensorId),o&&o()},f=function(x){var b=c.indexOf(x);b!==-1&&c.splice(b,1),c.length===0&&l&&h()};return{element:i,bind:p,destroy:h,unbind:f}};return _c.createSensor=r,_c}var __;function Zpe(){if(__)return kc;__=1,Object.defineProperty(kc,"__esModule",{value:!0}),kc.createSensor=void 0;var e=Jpe(),t=Xpe(),n=typeof ResizeObserver<"u"?t.createSensor:e.createSensor;return kc.createSensor=n,kc}var T_;function ehe(){if(T_)return oi;T_=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.removeSensor=oi.getSensor=oi.Sensors=void 0;var e=r(Qpe()),t=Zpe(),n=aw();function r(c){return c&&c.__esModule?c:{default:c}}var s={};oi.Sensors=s;function i(c){c&&s[c]&&delete s[c]}var o=function(d){var u=d.getAttribute(n.SizeSensorId);if(u&&s[u])return s[u];var p=(0,e.default)();d.setAttribute(n.SizeSensorId,p);var h=(0,t.createSensor)(d,function(){return i(p)});return s[p]=h,h};oi.getSensor=o;var l=function(d){var u=d.element.getAttribute(n.SizeSensorId);d.destroy(),i(u)};return oi.removeSensor=l,oi}var I_;function GL(){if(I_)return ai;I_=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.ver=ai.clear=ai.bind=void 0;var e=ehe(),t=function(i,o){var l=(0,e.getSensor)(i);return l.bind(o),function(){l.unbind(o)}};ai.bind=t;var n=function(i){var o=(0,e.getSensor)(i);(0,e.removeSensor)(o)};ai.clear=n;var r="1.0.2";return ai.ver=r,ai}var D_=GL();function A_(e,t){var n={};return t.forEach(function(r){n[r]=e[r]}),n}function Yx(e){return typeof e=="function"}function the(e){return typeof e=="string"}var Kx,M_;function YL(){return M_||(M_=1,Kx=function e(t,n){if(t===n)return!0;
188if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,s,i;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[s]))return!1;for(s=r;s--!==0;){var o=i[s];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}),Kx}var nhe=YL();const Mo=dt(nhe);var rhe=(function(e){mA(t,e);function t(n){var r=e.call(this,n)||this;return r.echarts=n.echarts,r.ele=null,r.isInitialResize=!0,r}return t.prototype.componentDidMount=function(){this.renderNewEcharts()},t.prototype.componentDidUpdate=function(n){var r=this.props.shouldSetOption;if(!(Yx(r)&&!r(n,this.props))){if(!Mo(n.theme,this.props.theme)||!Mo(n.opts,this.props.opts)||!Mo(n.onEvents,this.props.onEvents)){this.dispose(),this.renderNewEcharts();return}var s=["option","notMerge","lazyUpdate","showLoading","loadingOption"];Mo(A_(this.props,s),A_(n,s))||this.updateEChartsOption(),(!Mo(n.style,this.props.style)||!Mo(n.className,this.props.className))&&this.resize()}},t.prototype.componentWillUnmount=function(){this.dispose()},t.prototype.getEchartsInstance=function(){return this.echarts.getInstanceByDom(this.ele)||this.echarts.init(this.ele,this.props.theme,this.props.opts)},t.prototype.dispose=function(){if(this.ele){try{D_.clear(this.ele)}catch(n){console.warn(n)}this.echarts.dispose(this.ele)}},t.prototype.renderNewEcharts=function(){var n=this,r=this.props,s=r.onEvents,i=r.onChartReady,o=this.updateEChartsOption();this.bindEvents(o,s||{}),Yx(i)&&i(o),this.ele&&D_.bind(this.ele,function(){n.resize()})},t.prototype.bindEvents=function(n,r){function s(o,l){the(o)&&Yx(l)&&n.on(o,function(c){l(c,n)})}for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&s(i,r[i])},t.prototype.updateEChartsOption=function(){var n=this.props,r=n.option,s=n.notMerge,i=s===void 0?!1:s,o=n.lazyUpdate,l=o===void 0?!1:o,c=n.showLoading,d=n.loadingOption,u=d===void 0?null:d,p=this.getEchartsInstance();return p.setOption(r,i,l),c?p.showLoading(u):p.hideLoading(),p},t.prototype.resize=function(){var n=this.getEchartsInstance();if(!this.isInitialResize)try{n.resize()}catch(r){console.warn(r)}this.isInitialResize=!1},t.prototype.render=function(){var n=this,r=this.props,s=r.style,i=r.className,o=i===void 0?"":i,l=c5({height:300},s);return Ne.createElement("div",{ref:function(c){n.ele=c},style:l,className:"echarts-for-react "+o})},t})(m.PureComponent),Fl=(function(e){mA(t,e);function t(n){var r=e.call(this,n)||this;return r.echarts=_W,r}return t})(rhe);const she={dataPreview:"Data Preview",dataDictionary:"Data Dictionary"},KL=348,QL="mr_",R_={cost:{index:0,isCurrency:!0,name:"Spend"},impressions:{index:1,isCurrency:!1,name:"Impressions"}},JL={daily:{unit:"day",value:29},monthly:{unit:"month",value:3},weekly:{unit:"week",value:11}},ihe=({currency:e="USD",partitionDates:t,seriesData:n,theme:r,title:s})=>{const{palette:i,typography:o}=r,{border:l,chartBrand:c,text:d}=i,{secondary:u}=d,{fontFamily:p=""}=o;return{color:[c.main.bold,c.secondary.bold],grid:{top:64,right:24,bottom:0,left:24,containLabel:!0},legend:{data:n.map(({name:h})=>h),icon:"circle",itemGap:8,padding:[0,29,24,5],right:48,textStyle:{color:u,fontFamily:p,padding:-6}}
188,xAxis:{type:"category",data:t,axisLine:{show:!1},axisTick:{show:!1},axisLabel:{color:u,fontFamily:p,fontSize:11}},yAxis:n.map(({isCurrency:h})=>({type:"value",splitLine:{show:!1},axisLabel:{color:u,fontFamily:p,fontSize:11,formatter:h?f=>Math.ceil(f).toLocaleString("en-US",{style:"currency",currency:e,notation:"compact"}):f=>Math.ceil(f).toLocaleString("en-US",{notation:"compact"})}})),series:n.map(({data:h,index:f,isCurrency:g,name:x})=>({barGap:"10%",itemStyle:{borderRadius:[8,8,0,0]},type:"bar",data:h,name:x,tooltip:{valueFormatter:g?(b=0)=>Number(b).toLocaleString("en-US",{style:"currency",currency:e}):(b=0)=>Math.round(Number(b)).toLocaleString()},yAxisIndex:n.length>1?f:0})),title:{padding:[0,0,0,24],text:s,textStyle:{fontFamily:p,fontSize:16,fontWeight:500}},tooltip:{trigger:"axis",axisPointer:{type:"none"},textStyle:{color:u,fontFamily:p,fontSize:12,lineHeight:18},padding:8,borderColor:l.default,borderWidth:1}}},ahe=()=>a.jsxs(T,{sx:{display:"flex",flexDirection:"column",height:KL,mx:4},children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",height:32,mb:4},children:[a.jsx(fe,{variant:"text",width:150}),a.jsx(fe,{variant:"text",width:250})]}),a.jsx(T,{sx:{display:"flex",alignItems:"flex-end",height:"100%",justifyContent:"space-between"},children:["65%","55%","75%","85%"].map(e=>a.jsxs(T,{sx:{height:e,width:"18%",display:"flex",alignItems:"flex-end",columnGap:1},children:[a.jsx(fe,{variant:"rounded",height:"95%",width:"50%"}),a.jsx(fe,{variant:"rounded",height:"100%",width:"50%"})]},e))})]});var kh={exports:{}};var ohe=kh.exports,N_;function lhe(){return N_||(N_=1,(function(e,t){(function(n,r){e.exports=r()})(ohe,function n(){var r=typeof self<"u"?self:typeof window<"u"?window:r!==void 0?r:{},s=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,o={},l=0,c={parse:function(j,_){var D=(_=_||{}).dynamicTyping||!1;if(k(D)&&(_.dynamicTypingFunction=D,D={}),_.dynamicTyping=D,_.transform=!!k(_.transform)&&_.transform,_.worker&&c.WORKERS_SUPPORTED){var M=(function(){if(!c.WORKERS_SUPPORTED)return!1;var O=(L=r.URL||r.webkitURL||null,P=n.toString(),c.BLOB_URL||(c.BLOB_URL=L.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",P,")();"],{type:"text/javascript"})))),R=new r.Worker(O),L,P;return R.onmessage=v,R.id=l++,o[R.id]=R})();return M.userStep=_.step,M.userChunk=_.chunk,M.userComplete=_.complete,M.userError=_.error,_.step=k(_.step),_.chunk=k(_.chunk),_.complete=k(_.complete),_.error=k(_.error),delete _.worker,void M.postMessage({input:j,config:_,workerId:M.id})}var N=null;return c.NODE_STREAM_INPUT,typeof j=="string"?(j=(function(O){return O.charCodeAt(0)===65279?O.slice(1):O})(j),N=_.download?new p(_):new f(_)):j.readable===!0&&k(j.read)&&k(j.on)?N=new g(_):(r.File&&j instanceof File||j instanceof Object)&&(N=new h(_)),N.stream(j)},unparse:function(j,_){var D=!1,M=!0,N=",",O=`\r 189`,R='"',L=R+R,P=!1,F=null,z=!1;(function(){if(typeof _=="object"){if(typeof _.delimiter!="string"||c.BAD_DELIMITERS.filter(function(V){return _.delimiter.indexOf(V)!==-1}).length||(N=_.delimiter),(typeof _.quotes=="boolean"||typeof _.quotes=="function"||Array.isArray(_.quotes))&&(D=_.quotes),typeof _.skipEmptyLines!="boolean"&&typeof _.skipEmptyLines!="string"||(P=_.skipEmptyLines),typeof _.newline=="string"&&(O=_.newline),typeof _.quoteChar=="string"&&(R=_.quoteChar),typeof _.header=="boolean"&&(M=_.header),Array.isArray(_.columns)){if(_.columns.length===0)throw new Error("Option columns is empty");F=_.columns}_.escapeChar!==void 0&&(L=_.escapeChar+R),(typeof _.escapeFormulae=="boolean"||_.escapeFormulae instanceof RegExp)&&(z=_.escapeFormulae instanceof RegExp?_.escapeFormulae:/^[=+\-@\t\r].*$/)}})();var B=new RegExp(b(R),"g");if(typeof j=="string"&&(j=JSON.parse(j)),Array.isArray(j)){if(!j.length||Array.isArray(j[0]))return W(null,j,P);if(typeof j[0]=="object")return W(F||Object.keys(j[0]),j,P)}
189else if(typeof j=="object")return typeof j.data=="string"&&(j.data=JSON.parse(j.data)),Array.isArray(j.data)&&(j.fields||(j.fields=j.meta&&j.meta.fields||F),j.fields||(j.fields=Array.isArray(j.data[0])?j.fields:typeof j.data[0]=="object"?Object.keys(j.data[0]):[]),Array.isArray(j.data[0])||typeof j.data[0]=="object"||(j.data=[j.data])),W(j.fields||[],j.data||[],P);throw new Error("Unable to serialize unrecognized input");function W(V,G,X){var K="";typeof V=="string"&&(V=JSON.parse(V)),typeof G=="string"&&(G=JSON.parse(G));var ie=Array.isArray(V)&&0<V.length,le=!Array.isArray(G[0]);if(ie&&M){for(var ce=0;ce<V.length;ce++)0<ce&&(K+=N),K+=H(V[ce],ce);0<G.length&&(K+=O)}for(var J=0;J<G.length;J++){var he=ie?V.length:G[J].length,ne=!1,Y=ie?Object.keys(G[J]).length===0:G[J].length===0;if(X&&!ie&&(ne=X==="greedy"?G[J].join("").trim()==="":G[J].length===1&&G[J][0].length===0),X==="greedy"&&ie){for(var ae=[],je=0;je<he;je++){var me=le?V[je]:je;ae.push(G[J][me])}ne=ae.join("").trim()===""}if(!ne){for(var ve=0;ve<he;ve++){0<ve&&!Y&&(K+=N);var Me=ie&&le?V[ve]:ve;K+=H(G[J][Me],ve)}J<G.length-1&&(!X||0<he&&!Y)&&(K+=O)}}return K}function H(V,G){if(V==null)return"";if(V.constructor===Date)return JSON.stringify(V).slice(1,25);var X=!1;z&&typeof V=="string"&&z.test(V)&&(V="'"+V,X=!0);var K=V.toString().replace(B,L);return(X=X||D===!0||typeof D=="function"&&D(V,G)||Array.isArray(D)&&D[G]||(function(ie,le){for(var ce=0;ce<le.length;ce++)if(-1<ie.indexOf(le[ce]))return!0;return!1})(K,c.BAD_DELIMITERS)||-1<K.indexOf(N)||K.charAt(0)===" "||K.charAt(K.length-1)===" ")?R+K+R:K}}};if(c.RECORD_SEP="�",c.UNIT_SEP="�",c.BYTE_ORDER_MARK="\uFEFF",c.BAD_DELIMITERS=["\r",` 190`,'"',c.BYTE_ORDER_MARK],c.WORKERS_SUPPORTED=!s&&!!r.Worker,c.NODE_STREAM_INPUT=1,c.LocalChunkSize=10485760,c.RemoteChunkSize=5242880,c.DefaultDelimiter=",",c.Parser=y,c.ParserHandle=x,c.NetworkStreamer=p,c.FileStreamer=h,c.StringStreamer=f,c.ReadableStreamStreamer=g,r.jQuery){var d=r.jQuery;d.fn.parse=function(j){var _=j.config||{},D=[];return this.each(function(O){if(!(d(this).prop("tagName").toUpperCase()==="INPUT"&&d(this).attr("type").toLowerCase()==="file"&&r.FileReader)||!this.files||this.files.length===0)return!0;for(var R=0;R<this.files.length;R++)D.push({file:this.files[R],inputElem:this,instanceConfig:d.extend({},_)})}),M(),this;function M(){if(D.length!==0){var O,R,L,P,F=D[0];if(k(j.before)){var z=j.before(F.file,F.inputElem);if(typeof z=="object"){if(z.action==="abort")return O="AbortError",R=F.file,L=F.inputElem,P=z.reason,void(k(j.error)&&j.error({name:O},R,L,P));if(z.action==="skip")return void N();typeof z.config=="object"&&(F.instanceConfig=d.extend(F.instanceConfig,z.config))}else if(z==="skip")return void N()}var B=F.instanceConfig.complete;F.instanceConfig.complete=function(W){k(B)&&B(W,F.file,F.inputElem),N()},c.parse(F.file,F.instanceConfig)}else k(j.complete)&&j.complete()}function N(){D.splice(0,1),M()}}}function u(j){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(_){var D=S(_);D.chunkSize=parseInt(D.chunkSize),_.step||_.chunk||(D.chunkSize=null),this._handle=new x(D),(this._handle.streamer=this)._config=D}).call(this,j),this.parseChunk=function(_,D){if(this.isFirstChunk&&k(this._config.beforeFirstChunk)){var M=this._config.beforeFirstChunk(_);M!==void 0&&(_=M)}this.isFirstChunk=!1,this._halted=!1;var N=this._partialLine+_;this._partialLine="";var O=this._handle.parse(N,this._baseIndex,!this._finished);if(!this._handle.paused()&&!this._handle.aborted()){var R=O.meta.cursor;this._finished||(this._partialLine=N.substring(R-this._baseIndex),this._baseIndex=R),O&&O.data&&(this._rowCount+=O.data.length);var L=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(i)r.postMessage({results:O,workerId:c.WORKER_ID,finished:L});else if(k(this._config.chunk)&&!D){if(this._config.chunk(O,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);O=void 0,this._completeResults=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(O.data),this._completeResults.errors=this._completeResults.errors.concat(O.errors),this._completeResults.meta=O.meta),this._completed||!L||!k(this._config.complete)||O&&O.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),L||O&&O.meta.paused||this._nextChunk(),O}this._halted=!0},this._sendError=function(_){k(this._config.error)?this._config.error(_):i&&this._config.error&&r.postMessage({workerId:c.WORKER_ID,error:_,finished:!1})}}function p(j){var _;(j=j||{}).chunkSize||(j.chunkSize=c.RemoteChunkSize),u.call(this,j),this._nextChunk=s?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(D){this._input=D,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(_=new XMLHttpRequest,this._config.withCredentials&&(_.withCredentials=this._config.withCredentials),s||(_.onload=E(this._chunkLoaded,this),_.onerror=E(this._chunkError,this)),_.open(this._config.downloadRequestBody?"POST":"GET",this._input,!s),this._config.downloadRequestHeaders){var D=this._config.downloadRequestHeaders;for(var M in D)_.setRequestHeader(M,D[M])}if(this._config.chunkSize){var N=this._start+this._config.chunkSize-1;_.setRequestHeader("Range","bytes="+this._start+"-"+N)}try{_.send(this._config.downloadRequestBody)}catch(O){this._chunkError(O.message)}s&&_.status===0&&this._chunkError()}},this._chunkLoaded=function(){_.readyState===4&&(_.status<200||400<=_.status?this._chunkError():(this._start+=this._config.chunkSize?this._config.chunkSize:_.responseText.length,this._finished=!this._config.chunkSize||this._start>=(function(D){var M=D.getResponseHeader("Content-Range");return M===null?-1:parseInt(M.substring(M.lastIndexOf("/")+1))})(_),this.parseChunk(_.responseText)))},this._chunkError=function(D){var M=_.statusText||D;this._sendError(new Error(M))}}function h(j){var _,D;(j=j||{}).chunkSize||(j.chunkSize=c.LocalChunkSize),u.call(this,j);var M=typeof FileReader<"u";this.stream=function(N){this._input=N,D=N.slice||N.webkitSlice||N.mozSlice,M?((_=new FileReader).onload=E(this._chunkLoaded,this),_.onerror=E(this._chunkError,this)):_=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var N=this._input;if(this._config.chunkSize){var O=Math.min(this._start+this._config.chunkSize,this._input.size);N=D.call(N,this._start,O)}var R=_.readAsText(N,this._config.encoding);M||this._chunkLoaded({target:{result:R}})},this._chunkLoaded=function(N){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(N.target.result)},this._chunkError=function(){this._sendError(_.error)}}function f(j){var _;u.call(this,j=j||{}),this.stream=function(D){return _=D,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var D,M=this._config.chunkSize;return M?(D=_.substring(0,M),_=_.substring(M)):(D=_,_=""),this._finished=!_,this.parseChunk(D)}}}function g(j){u.call(this,j=j||{});var _=[],D=!0,M=!1;this.pause=function(){u.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){u.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(N){this._input=N,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){M&&_.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),_.length?this.parseChunk(_.shift()):D=!0},this._streamData=E(function(N){try{_.push(typeof N=="string"?N:N.toString(this._config.encoding)),D&&(D=!1,this._checkIsFinished(),this.parseChunk(_.shift()))}catch(O){this._streamError(O)}},this),this._streamError=E(function(N){this._streamCleanUp(),this._sendError(N)},this),this._streamEnd=E(function(){this._streamCleanUp(),M=!0,this._streamData("")},this),this._streamCleanUp=E(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function x(j){var _,D,M,N=Math.pow(2,53),O=-N,R=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,L=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,P=this,F=0,z=0,B=!1,W=!1,H=[],V={data:[],errors:[],meta:{}};if(k(j.step)){var G=j.step;j.step=function(J){if(V=J,ie())K();else{if(K(),V.data.length===0)return;F+=J.data.length,j.preview&&F>j.preview?D.abort():(V.data=V.data[0],G(V,P))}}}function X(J){return j.skipEmptyLines==="greedy"?J.join("").trim()==="":J.length===1&&J[0].length===0}function K(){return V&&M&&(ce("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+c.DefaultDelimiter+"'"),M=!1),j.skipEmptyLines&&(V.data=V.data.filter(function(J){return!X(J)})),ie()&&(function(){if(!V)return;function J(ne,Y){k(j.transformHeader)&&(ne=j.transformHeader(ne,Y)),H.push(ne)}if(Array.isArray(V.data[0])){for(var he=0;ie()&&he<V.data.length;he++)V.data[he].forEach(J);V.data.splice(0,1)}else V.data.forEach(J)})(),(function(){if(!V||!j.header&&!j.dynamicTyping&&!j.transform)return V;function J(ne,Y){var ae,je=j.header?{}:[];for(ae=0;ae<ne.length;ae++){var me=ae,ve=ne[ae];j.header&&(me=ae>=H.length?"__parsed_extra":H[ae]),j.transform&&(ve=j.transform(ve,me)),ve=le(me,ve),me==="__parsed_extra"?(je[me]=je[me]||[],je[me].push(ve)):je[me]=ve}return j.header&&(ae>H.length?ce("FieldMismatch","TooManyFields","Too many fields: expected "+H.length+" fields but parsed "+ae,z+Y):ae<H.length&&ce("FieldMismatch","TooFewFields","Too few fields: expected "+H.length+" fields but parsed "+ae,z+Y)),je}var he=1;return!V.data.length||Array.isArray(V.data[0])?(V.data=V.data.map(J),he=V.data.length):V.data=J(V.data,0),j.header&&V.meta&&(V.meta.fields=H),z+=he,V})()}function ie(){return j.header&&H.length===0}function le(J,he){return ne=J,j.dynamicTypingFunction&&j.dynamicTyping[ne]===void 0&&(j.dynamicTyping[ne]=j.dynamicTypingFunction(ne)),(j.dynamicTyping[ne]||j.dynamicTyping)===!0?he==="true"||he==="TRUE"||he!=="false"&&he!=="FALSE"&&((function(Y){if(R.test(Y)){var ae=parseFloat(Y);if(O<ae&&ae<N)return!0}return!1})(he)?parseFloat(he):L.test(he)?new Date(he):he===""?null:he):he;var ne}function ce(J,he,ne,Y){var ae={type:J,code:he,message:ne};
190Y!==void 0&&(ae.row=Y),V.errors.push(ae)}this.parse=function(J,he,ne){var Y=j.quoteChar||'"';if(j.newline||(j.newline=(function(me,ve){me=me.substring(0,1048576);var Me=new RegExp(b(ve)+"([^]*?)"+b(ve),"gm"),q=(me=me.replace(Me,"")).split("\r"),Q=me.split(` 191`),ee=1<Q.length&&Q[0].length<q[0].length;if(q.length===1||ee)return` 192`;for(var Ce=0,se=0;se<q.length;se++)q[se][0]===` 193`&&Ce++;return Ce>=q.length/2?`\r 194`:"\r"})(J,Y)),M=!1,j.delimiter)k(j.delimiter)&&(j.delimiter=j.delimiter(J),V.meta.delimiter=j.delimiter);else{var ae=(function(me,ve,Me,q,Q){var ee,Ce,se,oe;Q=Q||[","," ","|",";",c.RECORD_SEP,c.UNIT_SEP];for(var te=0;te<Q.length;te++){var de=Q[te],ke=0,Le=0,at=0;se=void 0;for(var Wt=new y({comments:q,delimiter:de,newline:ve,preview:10}).parse(me),zt=0;zt<Wt.data.length;zt++)if(Me&&X(Wt.data[zt]))at++;else{var Ht=Wt.data[zt].length;Le+=Ht,se!==void 0?0<Ht&&(ke+=Math.abs(Ht-se),se=Ht):se=Ht}0<Wt.data.length&&(Le/=Wt.data.length-at),(Ce===void 0||ke<=Ce)&&(oe===void 0||oe<Le)&&1.99<Le&&(Ce=ke,ee=de,oe=Le)}return{successful:!!(j.delimiter=ee),bestDelimiter:ee}})(J,j.newline,j.skipEmptyLines,j.comments,j.delimitersToGuess);ae.successful?j.delimiter=ae.bestDelimiter:(M=!0,j.delimiter=c.DefaultDelimiter),V.meta.delimiter=j.delimiter}var je=S(j);return j.preview&&j.header&&je.preview++,_=J,D=new y(je),V=D.parse(_,he,ne),K(),B?{meta:{paused:!0}}:V||{meta:{paused:!1}}},this.paused=function(){return B},this.pause=function(){B=!0,D.abort(),_=k(j.chunk)?"":_.substring(D.getCharIndex())},this.resume=function(){P.streamer._halted?(B=!1,P.streamer.parseChunk(_,!0)):setTimeout(P.resume,3)},this.aborted=function(){return W},this.abort=function(){W=!0,D.abort(),V.meta.aborted=!0,k(j.complete)&&j.complete(V),_=""}}function b(j){return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y(j){var _,D=(j=j||{}).delimiter,M=j.newline,N=j.comments,O=j.step,R=j.preview,L=j.fastMode,P=_=j.quoteChar===void 0||j.quoteChar===null?'"':j.quoteChar;if(j.escapeChar!==void 0&&(P=j.escapeChar),(typeof D!="string"||-1<c.BAD_DELIMITERS.indexOf(D))&&(D=","),N===D)throw new Error("Comment character same as delimiter");N===!0?N="#":(typeof N!="string"||-1<c.BAD_DELIMITERS.indexOf(N))&&(N=!1),M!==` 195`&&M!=="\r"&&M!==`\r 196`&&(M=` 197`);var F=0,z=!1;this.parse=function(B,W,H){if(typeof B!="string")throw new Error("Input must be a string");var V=B.length,G=D.length,X=M.length,K=N.length,ie=k(O),le=[],ce=[],J=[],he=F=0;if(!B)return Oe();if(j.header&&!W){var ne=B.split(M)[0].split(D),Y=[],ae={},je=!1;for(var me in ne){var ve=ne[me];k(j.transformHeader)&&(ve=j.transformHeader(ve,me));var Me=ve,q=ae[ve]||0;for(0<q&&(je=!0,Me=ve+"_"+q),ae[ve]=q+1;Y.includes(Me);)Me=Me+"_"+q;Y.push(Me)}if(je){var Q=B.split(M);Q[0]=Y.join(D),B=Q.join(M)}}if(L||L!==!1&&B.indexOf(_)===-1){for(var ee=B.split(M),Ce=0;Ce<ee.length;Ce++){if(J=ee[Ce],F+=J.length,Ce!==ee.length-1)F+=M.length;else if(H)return Oe();if(!N||J.substring(0,K)!==N){if(ie){if(le=[],at(J.split(D)),Pe(),z)return Oe()}else at(J.split(D));if(R&&R<=Ce)return le=le.slice(0,R),Oe(!0)}}return Oe()}for(var se=B.indexOf(D,F),oe=B.indexOf(M,F),te=new RegExp(b(P)+b(_),"g"),de=B.indexOf(_,F);;)if(B[F]!==_)if(N&&J.length===0&&B.substring(F,F+K)===N){if(oe===-1)return Oe();F=oe+X,oe=B.indexOf(M,F),se=B.indexOf(D,F)}else if(se!==-1&&(se<oe||oe===-1))J.push(B.substring(F,se)),F=se+G,se=B.indexOf(D,F);else{if(oe===-1)break;if(J.push(B.substring(F,oe)),Ht(oe+X),ie&&(Pe(),z))return Oe();if(R&&le.length>=R)return Oe(!0)}else for(de=F,F++;;){if((de=B.indexOf(_,de+1))===-1)return H||ce.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:le.length,index:F}),zt();if(de===V-1)return zt(B.substring(F,de).replace(te,_));if(_!==P||B[de+1]!==P){if(_===P||de===0||B[de-1]!==P){se!==-1&&se<de+1&&(se=B.indexOf(D,de+1)),oe!==-1&&oe<de+1&&(oe=B.indexOf(M,de+1));var ke=Wt(oe===-1?se:Math.min(se,oe));if(B.substr(de+1+ke,G)===D){J.push(B.substring(F,de).replace(te,_)),B[F=de+1+ke+G]!==_&&(de=B.indexOf(_,F)),se=B.indexOf(D,F),oe=B.indexOf(M,F);break}var Le=Wt(oe);if(B.substring(de+1+Le,de+1+Le+X)===M){if(J.push(B.substring(F,de).replace(te,_)),Ht(de+1+Le+X),se=B.indexOf(D,F),de=B.indexOf(_,F),ie&&(Pe(),z))return Oe();if(R&&le.length>=R)return Oe(!0);break}ce.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:le.length,index:F}),de++}}else de++}return zt();function at(Fe){le.push(Fe),he=F}function Wt(Fe){var pt=0;if(Fe!==-1){var _t=B.substring(de+1,Fe);_t&&_t.trim()===""&&(pt=_t.length)}return pt}function zt(Fe){return H||(Fe===void 0&&(Fe=B.substring(F)),J.push(Fe),F=V,at(J),ie&&Pe()),Oe()}function Ht(Fe){F=Fe,at(J),J=[],oe=B.indexOf(M,F)}function Oe(Fe){return{data:le,errors:ce,meta:{delimiter:D,linebreak:M,aborted:z,truncated:!!Fe,curs
197or:he+(W||0)}}}function Pe(){O(Oe()),le=[],ce=[]}},this.abort=function(){z=!0},this.getCharIndex=function(){return F}}function v(j){var _=j.data,D=o[_.workerId],M=!1;if(_.error)D.userError(_.error,_.file);else if(_.results&&_.results.data){var N={abort:function(){M=!0,C(_.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:w,resume:w};if(k(D.userStep)){for(var O=0;O<_.results.data.length&&(D.userStep({data:_.results.data[O],errors:_.results.errors,meta:_.results.meta},N),!M);O++);delete _.results}else k(D.userChunk)&&(D.userChunk(_.results,N,_.file),delete _.results)}_.finished&&!M&&C(_.workerId,_.results)}function C(j,_){var D=o[j];k(D.userComplete)&&D.userComplete(_),D.terminate(),delete o[j]}function w(){throw new Error("Not implemented.")}function S(j){if(typeof j!="object"||j===null)return j;var _=Array.isArray(j)?[]:{};for(var D in j)_[D]=S(j[D]);return _}function E(j,_){return function(){j.apply(_,arguments)}}function k(j){return typeof j=="function"}return i&&(r.onmessage=function(j){var _=j.data;if(c.WORKER_ID===void 0&&_&&(c.WORKER_ID=_.workerId),typeof _.input=="string")r.postMessage({workerId:c.WORKER_ID,results:c.parse(_.input,_.config),finished:!0});else if(r.File&&_.input instanceof File||_.input instanceof Object){var D=c.parse(_.input,_.config);D&&r.postMessage({workerId:c.WORKER_ID,results:D,finished:!0})}}),(p.prototype=Object.create(u.prototype)).constructor=p,(h.prototype=Object.create(u.prototype)).constructor=h,(f.prototype=Object.create(f.prototype)).constructor=f,(g.prototype=Object.create(u.prototype)).constructor=g,c})})(kh)),kh.exports}var che=lhe();const ow=dt(che),dhe=({partitionDates:e,seriesData:t})=>{const n=e.map((o,l)=>{const c={"Partition Date":Z(o).format("L")};return t.forEach(({data:d,name:u})=>{c[u]=d[l]}),c}),r=ow.unparse(n),s=new Blob([r],{type:"text/csv;charset=utf-8;"});return URL.createObjectURL(s)},uhe=({error:e,fileName:t,loading:n,partitionDates:r,seriesData:s,title:i})=>{const o=m.useRef(null),l=Re(),{engagementCurrency:c}=pe(),d=m.useMemo(()=>ihe({currency:c,partitionDates:r,seriesData:s,theme:l,title:i}),[c,r,s,l,i]),u=m.useMemo(()=>e||s.every(({data:h})=>!h.length),[e,s]),p=m.useCallback(h=>{let f="";return h==="png"&&o.current?f=o.current.getEchartsInstance().getDataURL({backgroundColor:"white"}):h==="csv"&&(f=dhe({partitionDates:r,seriesData:s})),{dataUrl:f,error:!f,fileName:t}},[t,r,s]);return a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.default",borderRadius:3.5,mb:4},children:a.jsx(Ue,{children:n?a.jsx(ahe,{}):a.jsx(T,{height:KL,children:a.jsx(gs,{isDataEmpty:u,isError:e,children:a.jsxs(a.Fragment,{children:[a.jsx(T,{sx:{display:"flex",justifyContent:"flex-end",position:"relative"},children:a.jsx(T,{sx:{position:"absolute",top:-12,right:24,zIndex:10},children:a.jsx(Rm,{getFileData:p})})}),a.jsx(Fl,{notMerge:!0,option:d,ref:o,style:{height:"100%"}})]})})})})})},phe=[{field:"name",flex:1},{field:"type",flex:1}],hhe=({apiRef:e,loading:t,rows:n})=>a.jsx(ag,{apiRef:e,columns:phe,getRowId:({name:r})=>r,loading:t,rows:t?[]:n}),fhe=e=>{switch(e){case"bigint":case"decimal":case"double":case"float":case"int":case"smallint":case"tinyint":return"number";case"date":case"timestamp":return"date";default:return"string"}},mhe=e=>{if(e==="date")return({value:t})=>t&&new Date(t)},ghe=e=>e.map(t=>{const n=fhe(t.type),r=mhe(n),s=t.name==="cost"||t.name==="mr_cost";return{field:t.name,type:n,valueGetter:r,...s&&{renderCell:({value:i})=>a.jsx(ft,{value:i,isCurrency:!0})}}}),xhe=({apiRef:e,loading:t,rows:n,schema:r})=>{const s=m.useMemo(()=>ghe(r),[r]);return a.jsx(ag,{apiRef:e,columns:s,getRowId:({uuid:i})=>i,loading:t,rows:n})},bhe="Our ETL process has many steps, and this is the date of last Data Curation step. This is when the chart and data preview on this page were last updated.",yhe=({dataSource:e,loading:t,summaryData:n})=>{if(t)return a.jsxs(a.Fragment,{children:[a.jsx(fe,{variant:"text",height:21}),a.jsx(fe,{variant:"text",width:"50%",height:21})]});if(!n)return null;const r=`${Mr(e)}'s`,s=(n?.totalRowsCount??0).toLocaleString(),i=Z(n?.lastRunTimestamp??"").format("l"),o=n?.nextScheduleTimestamp?a.jsxs(a.Fragment,{children:[" ","and the next expected refresh is on"," ",a.jsx("b",{children:Z(n?.nextScheduleTimestamp).format("l")}),"."]}):".";return a.jsxs(I,{children:["The data source ",a.jsx("b",{children:r})," most recent partition contains ",a.jsx("b",{children:s})," rows."," ",a.jsx(be,{title:bhe,children:a.jsxs(I,{component:"span",sx:{cursor:"help"},children:["The last data refresh was on ",a.jsx("b",{children:i})," ",a.jsx(aa,{sx:{display:"inline",fontSize:14}})]})}),o]})},vhe=({apiRef:e,loading:t})=>{const[n,r]=m.useState(""),s=m.useMemo(()=>gm(o=>{e.current.setQuickFilterValues(o.split(" ").filter(l=>l!==""))},150),[e]),i=o=>{const l=o.target.value;r(l),s(l)};return m.useEffect(()=>{r(""),e.current.setQuickFilterValues([])},[e]),a.jsx(Qe,{children:a.jsx(ys,{disabled:t,startAdornment:a.jsx(Mt,{sx:{color:"text.disabled",fontSize:20},children:a.jsx(er,{})}),onChange:i,placeholder:"Search",sx:{borderRadius:1,height:42,width:228,px:1.5,".MuiInputBase-inputAdornedStart":{pl:1.5,pr:0,height:24},"&.Mui-focused":{".MuiOutlinedInput-notchedOutline":{boxShadow:"none"}}},value:n})})},Che=({apiRef:e,loading:t,onChangeTable:n,tableType:r})=>a.jsxs(T,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",pb:3},children:[a.jsx(ml,{color:"primary",exclusive:!0,onChange:(s,i)=>{i!==null&&n(i)},value:r,children:Object.entries(she).map(([s,i])=>a.jsx(yi,{value:s,children:i},s))}),a.jsx(vhe,{apiRef:e,loading:t})]}),XL=e=>{switch(e?.frequency){case"daily":case"weekly":return e.frequency;default:return"monthly"}}
197,lw=({metrics:e=["cost","impressions"],schemaData:t})=>{const n=t.reduce((r,s)=>(r.add(s.name),r),new Set);return e.map(r=>{if(n.has(r))return r;const s=`${QL}${r}`;return n.has(s)?s:""}).filter(r=>!!r)},whe=(e,t)=>{const r=e.toSorted((l,c)=>c.localeCompare(l))[0];if(!r)return{endDate:"",startDate:""};const s=JL[XL(t)],i=Z(r),o=i.subtract(s.value,s.unit);return{endDate:i.format("YYYY-MM-DD"),startDate:o.format("YYYY-MM-DD")}},She=({dataSource:e,engagementNiceId:t,metaData:n})=>{const{partitionDates:r,schema:s}=n,{endDate:i,startDate:o}=whe(r,e),l=lw({schemaData:s});return{contentType:e?.content_type??"",endDate:i,engagementNiceId:t,feedNiceId:e?.feed_nice_id??"",metrics:l,startDate:o,vendorNiceId:e?.vendor_nice_id??""}},jhe=({aggData:e,dataSource:t,schemaData:n})=>{const r=JL[XL(t)],s=Im(`Last ${r.value+1} ${r.unit}s`),i=lw({schemaData:n}),o=e.toSorted((d,u)=>d.partitionDate.localeCompare(u.partitionDate)),l=o.map(({partitionDate:d})=>Z(d).format("MMM DD YYYY")),c=i.map(d=>{const u=d.startsWith(QL)?d.slice(3):d;if(u in R_){const{index:p,isCurrency:h,name:f}=R_[u];return{data:o.map(x=>x[d]??0),index:p,isCurrency:h,name:f}}return null}).filter(d=>d!==null).toSorted((d,u)=>d.index-u.index);return{partitionDates:l,seriesData:c,title:s}},khe={partitionDates:[],schema:[]},Ehe=({dataSource:e,pageSize:t=10})=>{const{engagementNiceId:n}=pe(),{data:r=khe,isError:s,isFetching:i,isUninitialized:o}=CV({contentType:e?.content_type??"",engagementNiceId:n,feedNiceId:e?.feed_nice_id??"",vendorNiceId:e?.vendor_nice_id??""},{skip:!e}),{data:l=[],isError:c,isFetching:d,isUninitialized:u}=wV({contentType:e?.content_type??"",engagementNiceId:n,feedNiceId:e?.feed_nice_id??"",pageSize:t,vendorNiceId:e?.vendor_nice_id??""},{skip:!e}),p=m.useMemo(()=>She({dataSource:e,engagementNiceId:n,metaData:r}),[e,n,r]),{data:h=[],isError:f,isFetching:g,isUninitialized:x}=SV(p,{skip:!e||!p.endDate||!p.metrics.length}),{data:b=null,isError:y,isFetching:v,isUninitialized:C}=jV(e?.id??0,{skip:!e});return{aggData:h,error:{aggData:f,metaData:s,summaryData:y,tableData:c},loading:{aggData:g||x,metaData:i||o,summaryData:v||C,tableData:d||u},metaData:r,summaryData:b,tableData:l}},_he=({dataSource:e})=>{const[t,n]=m.useState("dataPreview"),{aggData:r,error:s,loading:i,metaData:o,summaryData:l,tableData:c}=Ehe({dataSource:e}),{schema:d}=o,u=zn(),p=zn(),h=i.metaData||i.tableData,f=m.useMemo(()=>t==="dataDictionary"?u:p,[u,p,t]),{partitionDates:g,seriesData:x,title:b}=m.useMemo(()=>jhe({aggData:r,dataSource:e,schemaData:d}),[r,e,d]),y=m.useMemo(()=>lw({schemaData:d}).length>0,[d]),v=i.metaData||y,C=m.useMemo(()=>d.toSorted((E,k)=>E.name.localeCompare(k.name)),[d]),w=m.useMemo(()=>`${Mr(e)}-${b}-${new Date().toLocaleDateString()}`,[e,b]),S=E=>{n(E)};return!i.metaData&&s.metaData?a.jsx(I,{children:"There is no data available for this source"}):a.jsxs(T,{children:[a.jsx(T,{sx:{minHeight:42,mb:5},children:a.jsx(yhe,{dataSource:e,loading:i.summaryData,summaryData:l})}),a.jsx(Yt,{in:v,children:a.jsx(uhe,{error:s.aggData,fileName:w,loading:i.aggData,partitionDates:g,seriesData:x,title:b})}),a.jsx(Che,{apiRef:f,loading:h,onChangeTable:S,tableType:t}),a.jsx(Yt,{in:t==="dataPreview",children:a.jsx(xhe,{apiRef:p,loading:h,rows:c,schema:d})}),a.jsx(Yt,{in:t==="dataDictionary",children:a.jsx(hhe,{apiRef:u,loading:h,rows:C})})]})},The=({email:e,name:t,primary:n})=>a.jsxs(T,{sx:{backgroundColor:"background.neutral.default",borderRadius:"8px",display:"flex",flexDirection:"column",p:"8px"},children:[a.jsxs(T,{sx:{display:"flex",alignItems:"center",columnGap:.5},children:[n&&a.jsx(nA,{sx:{color:"icon.brand.main"}}),a.jsx(I,{variant:"subtitle2",children:t})]}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",gap:.5},children:[a.jsx(I,{color:"text.secondary",component:"span",variant:"body2",children:"Email:"}),a.jsx(I,{component:"span",overflow:"hidden",textOverflow:"ellipsis",variant:"body2",children:e})]})]}),Ihe=()=>a.jsxs(T,{sx:{backgroundColor:"background.neutral.default",borderRadius:"8px",display:"flex",flexDirection:"column",p:"8px"},children:[a.jsx(fe,{sx:{fontSize:14,maxWidth:300},variant:"text",width:"100%"}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",gap:.5},children:[a.jsx(I,{color:"text.secondary",component:"span",variant:"body2",children:"Email:"}),a.jsx(fe,{sx:{fontSize:14,maxWidth:256},component:"span",variant:"text",width:"100%"})]})]}),O_=({contacts:e,loading:t,title:n})=>!t&&!e.length?null:a.jsxs(T,{children:[a.jsx(I,{sx:{mb:1},variant:"subtitle1",children:n??""}),t?a.jsx(Ihe,{}):a.jsx($,{rowGap:1,children:e.map(({email:r,id:s,is_primary:i,name:o})=>a.jsx(The,{email:r,name:o,primary:i},s))})]}),Dhe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je(),n=m.useMemo(()=>{const r=t?.contacts||[];return{external:r.filter(({is_internal:s,is_private:i})=>!s&&!i),internal:r.filter(({is_internal:s,is_private:i})=>s&&!i)}},[t]);return a.jsx(or,{title:hr.assignedContacts,titleSx:{mb:1},children:a.jsxs($,{rowGap:2,children:[a.jsx(I,{variant:"body2",color:"text.secondary",children:"Who should we contact if something goes wrong?"}),a.jsx(O_,{contacts:n.internal,loading:e,title:"Customer Support"}),a.jsx(O_,{contacts:n.external,loading:e,title:"Customer Data Owner"}),e||t?.contacts?.length?null:a.jsx(I,{color:"text.secondary",children:"No contacts were assigned."})]})})},Ahe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je();return a.jsxs(a.Fragment,{children:[a.jsx(oo,{data:t?.api_config,loading:e,title:Ge.api_config}),a.jsx(St,{sx:{my:3}}),a.jsx(oo,{data:t?.di_config,loading:e,title:Ge.di_config})]})},Mhe=()=>{const{availableConnections:e,dataSourcesLoading:t,state:{selectedDataSource:n}}=Je(),r=n?.delivery_method,s=m.useMemo(()=>r&&Tn(TP,r)?IP[r]:"Unknown",[r]),i=()=>!r||!["api","bigquery","snowflake"].includes(r)?null:a.jsx(cn,{field:Ge.api_secret,loading:t,value:n.api_secret}),o=()=>
197{if(!r||!["cm360","dv360","googleads","ga4"].includes(r))return null;const l=e.find(c=>c.id===n.connection_id)?.name;return a.jsx(cn,{field:Ge.connection_id,loading:t,value:l??"unknown"})};return a.jsxs($,{rowGap:1,children:[a.jsx(cn,{field:Ge.delivery_method,loading:t,sxValue:{textTransform:"capitalize"},value:s}),i(),o()]})},Rhe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je();return a.jsxs(a.Fragment,{children:[a.jsx(I,{variant:"subtitle1",mb:2,children:"S3 Configuration"}),a.jsxs($,{rowGap:1,children:[a.jsx(cn,{field:Ge.s3_bucket,loading:e,value:t?.s3_bucket}),a.jsx(cn,{field:Ge.path,loading:e,value:t?.path}),a.jsx(cn,{field:Ge.file_filter,loading:e,value:t?.file_filter})]}),a.jsx(St,{sx:{my:3}}),a.jsx(oo,{data:t?.di_config,loading:e,title:Ge.di_config})]})},Nhe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je(),n=m.useMemo(()=>t?.delivery_method&&Tn(TP,t.delivery_method)?IP[t.delivery_method]:"Unknown",[t]),r=m.useMemo(()=>{switch(n){case"S3":return a.jsx(Rhe,{});case"BigQuery":case"Snowflake":case"Other API":case"Campaign Manager 360":case"Display Video 360":case"Google Ads":case"Google Analytics 4":return a.jsx(Ahe,{});default:return a.jsx(Jd,{loading:e})}},[n,e]);return a.jsxs(or,{title:hr.connector,children:[a.jsx(Mhe,{}),a.jsx(St,{sx:{my:3}}),r,a.jsx(St,{sx:{my:3}}),a.jsx(I,{variant:"subtitle1",mb:2,children:"Data Settings"}),a.jsx($,{rowGap:1,children:a.jsx(cn,{field:Ge.frequency,loading:e,value:t&&$0({frequency:t.frequency,offset:t.freq_offset})})})]})},Ohe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je(),n=t?.execution_steps||[],r=m.useMemo(()=>{const s=t?.events_json?.length&&t.events_json?.[0]||{};return{deviceRes:"idr"in s?`Yes, using table "${String(s.idr)}"`:"No",personRes:"pr"in s?`Yes, using table "${String(s.pr)}"`:"No"}},[t]);return a.jsxs(or,{title:hr.dataProcessing,children:[a.jsx($,{rowGap:2,children:e?a.jsx(X0,{}):n.map(s=>a.jsx(oo,{data:[s],index:String(s.step),title:z0(s)},String(s.step)))}),a.jsx(St,{sx:{my:3}}),a.jsxs($,{rowGap:1,children:[a.jsx(I,{variant:"subtitle1",mb:2,children:"Event Resolution"}),a.jsx(cn,{field:"Device Resolution",loading:e,value:r.deviceRes}),a.jsx(cn,{field:"Person Resolution",loading:e,value:r.personRes})]})]})},Phe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je();return a.jsxs(or,{title:hr.file,children:[a.jsxs($,{rowGap:1,children:[a.jsx(cn,{field:Ge.file_extension,loading:e,value:t?.file_extension,sxValue:{textTransform:"lowercase"}}),a.jsx(cn,{field:Ge.file_compression,loading:e,value:t?.file_compression,sxValue:{textTransform:"lowercase"}}),a.jsx(cn,{field:Ge.file_delimiter,loading:e,value:t?.file_delimiter})]}),t?.file_config&&a.jsxs(a.Fragment,{children:[a.jsx(St,{sx:{my:3}}),a.jsx(Jd,{data:t.file_config,loading:e})]})]})},Lhe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je();return a.jsx(or,{title:hr.general,children:a.jsxs($,{rowGap:1,children:[a.jsx(cn,{field:Ge.content_type,loading:e,value:J0({contentType:t?.content_type,measurementCategory:t?.measurement_category})}),a.jsx(cn,{field:Ge.vendor_nice_id,loading:e,value:t?.vendor_nice_id}),a.jsx(cn,{field:Ge.feed_nice_id,loading:e,value:t?.feed_nice_id})]})})},Fhe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je(),n=t?.header_json||[];return a.jsx(or,{title:hr.headers,children:e?a.jsx(X0,{}):a.jsx($,{sx:{maxHeight:800,overflowY:"auto"},children:n.map((r,s)=>a.jsx(oo,{data:[r],index:`header-${s}`,title:z0(r)},s))})})},$he=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je(),n=m.useMemo(()=>{const r=bL(t),{type:s,attributes:i,placements:o,creatives:l,brand:c}=r;if(e)return a.jsx(cn,{field:"Type",loading:e});if(s==="none")return a.jsx(cn,{field:"Type",value:"None"});if(s==="full")return a.jsx(cn,{field:"Type",value:"Full"});if(s==="custom"){const{execution_steps:d}=t??{},u=Die({nameCleaningValues:r,executionSteps:d});return a.jsxs($,{rowGap:1,children:[a.jsx(cn,{field:"Type",value:"Custom"}),a.jsx(cn,{field:"Attributes",loading:e,tooltipValue:u.attributes,value:Im(i?.join(", ")||"None")}),a.jsx(cn,{field:"Placements",loading:e,tooltipValue:u.placement,value:o?"Yes":"No"}),a.jsx(cn,{field:"Creatives",loading:e,tooltipValue:u.creative,value:l?"Yes":"No"}),a.jsx(cn,{field:"Brand",loading:e,tooltipValue:u.brand,value:c?"Yes":"No"})]})}return null},[t,e]);return a.jsx(or,{title:hr.nameCleaning,children:n})},zhe=()=>{const{dataSourcesLoading:e,state:{selectedDataSource:t}}=Je(),{active:n,supervisor_scheduling:r,validation_active:s}=t||{};return a.jsx(or,{title:hr.runSettings,children:a.jsxs($,{rowGap:1,children:[a.jsx(Ox,{field:Ge.active,loading:e,value:!!n}),a.jsx(Ox,{field:Ge.supervisor_scheduling,loading:e,value:!!r}),a.jsx(Ox,{field:Ge.validation_active,loading:e,value:!!s}
197)]})})},Bhe=()=>a.jsx(Ru,{mainContent:a.jsxs(a.Fragment,{children:[a.jsx(Lhe,{}),a.jsx(Nhe,{}),a.jsx(Phe,{}),a.jsx(Fhe,{}),a.jsx($he,{}),a.jsx(Ohe,{})]}),sideContent:a.jsxs(a.Fragment,{children:[a.jsx(zhe,{}),a.jsx(Dhe,{}),a.jsx($u,{})]})}),pi={dataProcessing:{label:"Data Processing",value:"singleSource.partitions",authorized:"DataSources.Configurations"},overview:{label:"Overview",value:"singleSource.overview",authorized:"DataPlatform"},summary:{label:"Summary",value:"singleSource.summary",authorized:"DataSources.Configurations"},configuration:{label:"Configuration",value:"singleSource.configuration",authorized:"DataSources.Configurations.Edit"},transformHeaders:{label:"Map and Transform",value:"singleSource.mapAndTransform",authorized:"DataSources.Configurations.Edit"},schedule:{label:"Schedule",value:"singleSource.schedule",authorized:"DataSources.Configurations.Edit"},advanced:{label:"Advanced",value:"singleSource.advanced",authorized:"DataSources.Configurations.Edit"},runsHistory:{label:"Runs History",value:"dataOrchestration",authorized:"DataPipeline.Processing.DIGroups"},notes:{label:"Notes",value:"singleSource.notes",authorized:"DataSources.Configurations.Edit"}},P_=Object.values(pi),Uhe=()=>{const{dispatch:e,navigateToTab:t,state:{selectedDataSource:n,view:r}}=Je(),{dispatch:s}=tn(),{formState:{isDirty:i}}
197=An(),o=m.useCallback(c=>{const d=P_.find(p=>p.value===c)?.value;if(!d||!n)return;qf.includes(r)&&i?(e({type:"nextView",value:d}),s({type:"saveChangesDialogOpen",value:!0})):t({nextSource:n,nextView:d})},[e,s,i,t,n,r]),l=m.useCallback(()=>{const c=F0;qf.includes(r)&&i?(e({type:"nextView",value:c}),s({type:"saveChangesDialogOpen",value:!0})):t({nextSource:null,nextView:c})},[e,s,i,t,r]);return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",width:ks,minWidth:600},children:[a.jsx(vu,{handleNavigateHome:l,pageName:Mr(n),parentConfig:{handleNavigateToParent:l,parentName:"Data Sources"}}),a.jsx(qpe,{}),a.jsxs(fo,{onChange:o,tabs:P_,value:r,children:[a.jsx(xt,{sx:{p:0,pt:3},value:pi.dataProcessing.value,children:a.jsx(Bpe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.overview.value,children:a.jsx(_he,{dataSource:n})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.summary.value,children:a.jsx(Bhe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.configuration.value,children:a.jsx(Wpe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.transformHeaders.value,children:a.jsx(Vpe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.schedule.value,children:a.jsx(Hpe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.advanced.value,children:a.jsx(Upe,{})}),a.jsx(xt,{sx:{p:0,pt:3},value:pi.notes.value,children:a.jsx(Kpe,{})})]})]})},Vhe=({view:e})=>({dialogOpen:null,nextView:null,selectedDataSource:null,selectedPartition:null,view:e||F0}),Whe=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,Hhe=({userIsInternal:e})=>({columns:HL({userIsInternal:e}),columnVisibilityModel:Ope({userIsInternal:e}),dataToCreate:null,dataToRemove:null,processingError:"",processingEvent:null,selectedSourceForAction:null}),qhe=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,Ghe=({activeSourcesCount:e,allContacts:t,availableConnections:n,availableLicenses:r,canManageUsers:s,checkIsDuplicate:i,connectionsLoading:o,connectors:l,connectorsLoading:c,contactsLoading:d,dataSources:u,dataSourcesLoading:p,editEnabled:h,handleCreateContact:f,handleRunPartition:g,handleSimpleCreateDataSource:x,handleUpdateContacts:b,handleUpdateDataSource:y,handleUpdateDataSourceField:v,handleUpdatePartition:C,inactiveSourcesCount:w,isDataSourceLimitReached:S,mpTrack:E,partitions:k,partitionsLoading:j,partitionUpdating:_,processingContacts:D,refetchPartitions:M,userId:N,userIsInternal:O,validateEmail:R,validateUsername:L})=>{const P=zn(),F=zn(),z=zn(),{paramsState:B,updateSearchParams:W}=oue(),[H,V]=m.useReducer(Whe,Vhe({view:B.view})),[G,X]=m.useReducer(qhe,Hhe({userIsInternal:O})),K=en(),{handleStopPartition:ie,stoppingPartition:le}=hue(),ce=m.useCallback(({nextSource:ne,nextView:Y})=>{const ae=ne?{id:ne.id,name:Mr(ne)}:void 0;E(Y,ae),Y==="dataOrchestration"?K("/data-pipeline/processing"):(V({type:"view",value:Y}),V({type:"nextView",value:null}),ne!==H.selectedDataSource&&V({type:"selectedDataSource",value:ne}),W({id:ne?ne.id:null,view:Y}))},[E,K,H.selectedDataSource,W]),J=m.useCallback(ne=>{ce({nextSource:ne,nextView:"singleSource.partitions"})},[ce]);m.useEffect(()=>{const Y=(H.selectedDataSource?.id??null)!==B.id||H.view!==B.view;if(!p&&Y){const ae=Aie({currentSource:H.selectedDataSource,currentView:H.view,dataSources:u,editEnabled:h,paramsId:B.id,paramsView:B.view}),{nextSource:je,nextView:me}=ae;(je!==H.selectedDataSource||me!==H.view)&&ce(ae)}},[B.id,B.view,u,p,h,ce,H.selectedDataSource,H.view]);const he=m.useMemo(()=>({activeSourcesCount:e,allContacts:t,availableConnections:n,availableLicenses:r,canManageUsers:s,checkIsDuplicate:i,connectionsLoading:o,connectors:l,connectorsLoading:c,contactsLoading:d,dataSources:u,dataSourcesListDispatch:X,dataSourcesListState:G,dataSourcesLoading:p,dispatch:V,editEnabled:h,gridApiRefs:{allSourcesPartitions:P,dataSourcesList:F,singleSourcePartitions:z},handleCreateContact:f,handleRunPartition:g,handleSimpleCreateDataSource:x,handleUpdateContacts:b,handleUpdateDataSource:y,handleUpdateDataSourceField:v,handleUpdatePartition:C,handleViewDataSource:J,handleStopPartition:ie,inactiveSourcesCount:w,isDataSourceLimitReached:S,mpTrack:E,navigateToTab:ce,partitions:k,partitionsLoading:j,partitionUpdating:_,processingContacts:D,refetchPartitions:M,state:H,stoppingPartition:le,userId:N,userIsInternal:O,validateEmail:R,val
197idateUsername:L}),[e,t,P,n,r,s,i,o,l,c,d,F,u,G,p,h,f,g,x,b,y,v,C,ie,J,w,S,E,ce,k,j,_,D,M,z,H,le,N,O,R,L]);return a.jsx(hL.Provider,{value:he,children:H.view.startsWith("all")?a.jsx(zpe,{}):a.jsx(jde,{children:a.jsx(Uhe,{})})})},Yhe=()=>{const{userId:e,userIsInternal:t}=gt(),{engagementId:n}=pe(),r=yn({authorized:"DataSources.Configurations.Edit"}),s=yn({authorized:"Settings.UserManagement"}),{checkIsDuplicate:i,data:o,handleSimpleCreateDataSource:l,handleUpdateDataSource:c,handleUpdateDataSourceField:d,loading:u}=nue(),{data:p=[],isLoading:h}=fC({engagement_id:n,status:["authorized"]}),{data:f=[],isLoading:g}=mu(),{allContacts:x,contactsLoading:b,handleCreateContact:y,handleUpdateContacts:v,updating:C,validateEmail:w,validateUsername:S}=bce(),{activeSourcesCount:E,availableLicenses:k,inactiveSourcesCount:j,isDataSourceLimitReached:_}=rue({dataSources:o,dataSourcesLoading:u}),{handleUpdatePartition:D,partitions:M,partitionsLoading:N,refetchPartitions:O,updatingPartition:R}=xce(),{handleRunPartition:L}=lue(),P=ML();return a.jsx(Ghe,{activeSourcesCount:E,allContacts:x,availableConnections:p,availableLicenses:k,canManageUsers:s,checkIsDuplicate:i,connectionsLoading:h,connectors:f,connectorsLoading:g,contactsLoading:b,dataSources:o,dataSourcesLoading:u,editEnabled:r,handleCreateContact:y,handleRunPartition:L,handleSimpleCreateDataSource:l,handleUpdateContacts:v,handleUpdateDataSource:c,handleUpdateDataSourceField:d,handleUpdatePartition:D,inactiveSourcesCount:j,isDataSourceLimitReached:_,mpTrack:P,partitions:M,partitionsLoading:N,partitionUpdating:R,processingContacts:C,refetchPartitions:O,userId:e,userIsInternal:t,validateEmail:w,validateUsername:S})},ZL=m.createContext(null),zu=()=>m.useContext(ZL),Khe={createNewKpi:"Create New KPI",editKpi:"Edit KPI",saveKpi:"Save KPI",viewKpiSummary:"View KPI Summary"},e2=()=>pr({actionMap:Khe,eventName:"machineLearningKpi"}),Qhe=e=>e.type===null?"":e.type==="syntax"?"JSON Syntax Error":"Validation Error",Jhe=e=>{if(e.key==="Tab"){e.preventDefault();const t=e.currentTarget.querySelector("textarea");if(!t)return;const{selectionEnd:n,selectionStart:r,value:s}=t,i=r??0,o=n??0,l=" ";t.value=`${s.substring(0,i)}${l}${s.substring(i)}`,t.selectionStart=i+2,t.selectionEnd=o+2;const c=new Event("input",{bubbles:!0});t.dispatchEvent(c)}},Xhe=e=>{try{return JSON.parse(e),{error:!1,errorInfo:{type:null,message:""}}}catch(t){let r=t instanceof Error?t.message:"Unknown error";return r=r.replace(/^SyntaxError: |^JSON\.parse: /g,""),r.includes("position")&&(r=r.replace(/position (\d+)/,(s,i)=>{const o=e.substring(0,parseInt(i,10)).split(` 198`),l=o.length,d=((o.length>0?o[o.length-1]:"")||"").length+1;return`at line ${l}, column ${d}`})),{error:!0,errorInfo:{type:"syntax",message:r}}}},Zhe=({error:e})=>a.jsx(I,{children:e}),efe=({isValid:e,type:t})=>{const{error:n,success:r}=Re().palette;if(e===null)return null;const s=(e?r:n).main,i=e?qv:Gv,o=`${t} ${e?"Successful":"Failed"}`;return a.jsxs(T,{sx:{alignItems:"center",columnGap:1,display:"flex"},children:[a.jsx(i,{sx:{color:s}}),a.jsx(I,{fontSize:"12px",fontWeight:500,children:o})]})},tfe=({checkFormatting:e,checkValidity:t,error:n,isValid:r,loading:s,onChange:i,value:o})=>a.jsxs(Ct,{sx:{display:"grid",gridTemplateRows:"auto 1fr",rowGap:2,mt:2},children:[a.jsxs(T,{sx:{display:"flex",columnGap:1,mb:1,minHeight:"32px"},children:[a.jsx(re,{color:"secondary",disabled:s,onClick:e,size:"small",sx:{height:"32px"},children:"Format JSON"}),a.jsx(Dt,{color:"secondary",loading:s,onClick:t,variant:"outlined",size:"small",sx:{height:"32px"},children:"Validate"}),a.jsx(efe,{isValid:r,type:"Validation"})]}),a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:"3fr 2fr",columnGap:2,minHeight:0},children:[a.jsx(T,{sx:{overflow:"auto",minWidth:0,minHeight:0},children:a.jsx(De,{disabled:s,error:n.type!==null,fullWidth:!0,minRows:10,multiline:!0,onChange:i,onKeyDown:Jhe,value:o})}),a.jsxs(T,{sx:{display:"flex",flexDirection:"column",minHeight:0,minWidth:0},children:[a.jsx(I,{color:"error",variant:"subtitle2",sx:{pb:1},children:Qhe(n)}),n.type!==null&&n.message?a.jsx(Zhe,{error:n.message}):null]})]})]}),nfe=({onClose:e,onSave:t,open:n,title:r,value:s})=>{const[i,o]=m.useState(s),[l,c]=m.useState(!1),[d,u]=m.useState({type:null,message:""}),[p,h]=m.useState(null),f=m.useCallback(v=>{o(v.target.value),u({type:null,message:""}),h(null)},[]),g=m.useCallback(()=>{const v=Xhe(i);return v.errorInfo&&u(v.errorInfo),{error:v.error}},[i]),x=m.useCallback(()=>{try{const v=JSON.parse(i),C=JSON.stringify(v,null,2);return o(C),{parsedValue:v,error:!1}}catch{return{parsedValue:null,error:!0}}},[i]),b=m.useCallback(async()=>{c(!0);const{error:v}=g();h(!v),c(!1)},[g]),y=()=>{const{error:v}=g();if(!v){const{parsedValue:C,error:w}=x();!w&&C&&(t(JSON.stringify(C,null,2)),e())}};return a.jsxs(yt,{open:n,onClose:e,maxWidth:"md",fullWidth:!0,PaperProps:{sx:{maxHeight:"90vh",display:"flex",flexDirection:"column"}},children:[a.jsx(vt,{children:r}),a.jsx(tfe,{checkFormatting:x,checkValidity:b,error:d,isValid:p,loading:l,onCh
198ange:f,value:i}),a.jsxs(un,{children:[a.jsx(re,{onClick:e,color:"inherit",children:"Cancel"}),a.jsx(re,{onClick:y,color:"primary",variant:"contained",children:"Save Changes"})]})]})},rfe=({field:e,value:t})=>a.jsxs(T,{sx:{display:"flex",flexDirection:"row"},children:[a.jsxs(I,{sx:{width:200},variant:"body2",color:"text.secondary",children:[e,":"]}),a.jsx(be,{title:t||"",children:a.jsx(I,{variant:"body2",children:t})})]}),Ro=({dialogTitle:e,emptyMessage:t="No Values",fieldName:n,invalidMessage:r="Invalid JSON configuration",maxHeight:s="200px",title:i,isLoading:o=!1})=>{const{register:l,setValue:c,watch:d}=on(),[u,p]=m.useState(!1),h=d(n),f=typeof h=="string"?h:"{}";l(n);const g=()=>{p(!0)},x=()=>{p(!1)},b=C=>{c(n,C,{shouldValidate:!0,shouldDirty:!0})},y=C=>C.split("_").map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join(" "),v=()=>{try{const C=JSON.parse(f);return typeof C!="object"||C===null?a.jsx(I,{color:"error",children:"Invalid JSON: Not an object"}):Object.keys(C).length===0?a.jsx(I,{variant:"body2",children:t}):a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:Object.entries(C).map(([S,E])=>a.jsx(rfe,{field:y(S),value:typeof E=="object"?JSON.stringify(E,null,2):String(E)},S))})}catch{return a.jsx(I,{variant:"body2",color:"error",children:r})}};return a.jsx(Zt,{title:i,endIcon:a.jsx(re,{variant:"outlined",color:"secondary",onClick:g,size:"small",sx:{minWidth:"100px"},children:"Edit JSON"}),children:a.jsx(Nt,{isLoading:o,width:"100%",children:a.jsxs($,{spacing:2,children:[a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:2},children:a.jsx(T,{sx:{pb:2,pt:1,px:2,maxHeight:s,overflowY:"auto"},children:v()})}),a.jsx(nfe,{open:u,title:e||`Edit ${i}`,value:f,onClose:x,onSave:b})]})})})},cw=m.createContext(null),dg=()=>on(),sfe=({isLoading:e=!1})=>{const{register:t}=dg();return a.jsx(Zt,{title:"Key Performance Indicators",children:a.jsxs($,{gap:2,children:[a.jsx(T,{sx:{display:"flex",alignItems:"center",gap:"5px"},children:a.jsx(Nt,{isLoading:e,width:"100%",children:a.jsx(De,{label:"KPI",...t("objective_name"),required:!0,fullWidth:!0})})}),a.jsxs(T,{sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},alignItems:"center",gap:2},children:[a.jsx(T,{sx:{flex:1,minWidth:{xs:"100%",sm:"200px"}},children:a.jsx(Nt,{isLoading:e,width:"100%",children:a.jsx(De,{label:"Revenue per Conversion",...t("value_per_conversion",{valueAsNumber:!0}),type:"number",required:!0,fullWidth:!0})})}),a.jsx(T,{sx:{flex:1,minWidth:{xs:"100%",sm:"200px"}},children:a.jsx(Nt,{isLoading:e,width:"100%",children:a.jsx(De,{label:"KPI Scalar",...t("kpi_scalar",{setValueAs:n=>n===""?null:Number(n)}),type:"number",fullWidth:!0})})})]})]})})},ife=({isLoading:e=!1})=>{const{control:t}=dg();return a.jsx(Et,{control:t,name:"notes",render:({field:{value:n="",onChange:r}})=>a.jsx(Qe,{fullWidth:!0,variant:"filled",children:a.jsx(Zt,{title:"Notes",children:a.jsxs(xn,{gap:2,children:[a.jsx(I,{children:"Provide additional information about the KPI, if needed"}),a.jsx(Nt,{isLoading:e,width:"100%",children:a.jsx(cu,{value:n,onChange:r,height:370})})]})})})})},afe=({isLoading:e=!1})=>{const{control:t}=dg();return a.jsx(Et,{control:t,name:"active",defaultValue:!0,render:({field:{value:n,onChange:r}})=>a.jsx(Qe,{fullWidth:!0,variant:"filled",children:a.jsx(Zt,{title:"Settings",children:a.jsx(Nt,{isLoading:e,width:"100%",children:a.jsxs(xn,{direction:"row",alignItems:"center",justifyContent:"space-between",minWidth:200,children:[a.jsx(I,{children:"Active"}),a.jsx(Dn,{checked:n,onChange:r})]})})})})})},ofe=({isLoading:e=!1})=>{const{setRaiseConversationIcon:t}=jt();return m.useEffect(()=>(t(!0),()=>{t(!1)}),[t]),a.jsx(T,{component:"form",id:"kpi-form",children:a.jsxs($,{sx:{py:2,px:{xs:8,lg:20},minWidth:600,gap:3,justifyContent:"center",flexDirection:{xs:"column",lg:"row-reverse"}},children:[a.jsxs($,{gap:3,flex:1,width:"100%",mx:"auto",children:[a.jsx(afe,{isLoading:e}),a.jsx(ife,{isLoading:e})]}),a.jsxs($,{flex:2,width:"100%",mx:"auto",gap:3,children:[a.jsx(sfe,{isLoading:e}),a.jsx(Ro,{fieldName:"model_config",title:"Model Config",dialogTitle:"Edit Model Configuration",isLoading:e}),a.jsx(Ro,{fieldName:"algorithm_config",title:"Algorithm Configuration",dialogTitle:"Edit Algorithm Configuration",isLoading:e}),a.jsx(Ro,{fieldName:"step_functions_config",title:"Step Function Config",dialogTitle:"Edit Step Function Configuration",isLoading:e}),a.jsx(Ro,{fieldName:"reporting_config",title:"Reporting Config",dialogTitle:"Edit Reporting Configuration",isLoading:e}),a.jsx(Ro,{fieldName:"planner_config",title:"Planner Config",dialogTitle:"Edit Planner Configuration",isLoading:e}),a.jsx(Ro,{fieldName:"kpi_config",title:"KPI Config",dialogTitle:"Edit KPI Configuration",isLoading:e})]})]})})},t2=({isLoading:e=!1})=>{const{dispatch:t,onClose:n,onSubmit:r,open:s,state:i,formMode:o}=m.useContext(cw),{exitDialogOpen:l}=i,{formState:{isValid:c,isDirty:d,isSubmitting:u},handleSubmit:p}=dg(),h=e2(),f=()=>{if(d){t({type:"exitDialogOpen",value:!0});return}n()},g=()=>{t({type:"exitDialogOpen",value:!1})},x=()=>{t({type:"exitDialogOpen",value:!1}),n()},b=p(async y=>{try{await r(y),h(o==="edit"?"saveKpi":"createNewKpi")}catch{}});return a.jsxs(yt,{fullScreen:!0,open:s,children:[a.jsxs(vt,{variant:"h6",sx:{p:3,pt:4,"&.MuiTypography-h6":{fontSize:18,lineHeight:"22px"}},children:[o==="edit"?"Edit KPI":"Create New KPI",a.jsx(Ie,{onClick:f,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})})]}),a.jsx(Ct,{sx:{pb:6.5,display:"flex",flexDirection:"column"},children:a.jsx(ofe,{isLoading:e})}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(re,{onClick:f,sx:{maxWidth:200,m:2},variant:"outlined",color:"secondary",children:"Cancel"}),a.jsx(Dt,{loading:u,onClick:b,disabled:!c,sx:{m:2,pl:2.5},variant:"contained",children:o==="edit"?"Save Changes":"Create KPI"})]}),a.jsx(mt,{bodyText:"You have unsaved data. If you leave the page, these changes will be lost.",handleClose:g,handleAccept:x,open:l,title:`Cancel ${o==="edit"?"KPI Edit":"New KPI"}?`,acceptLabel:"Yes, Cancel"})]})},n2=U.object({objective_name:U.string().min(1,"Name is required"),value_per_conversion:U.number({required_error:"Value per conversion is required"}).min(0,"Must be greater than or equal to 0"),kpi_scalar:U.preprocess(e=>Number.isNaN(e)?null:e,U.union([U.number().positive("Must be a positive number"),U.null()]).default(null)),notes:U.string().optional(),active:U.boolean().default(!0),model_config:U.string().default("{}"),algorithm_config:U.string().default("{}"),step_functions_config:U.string().default("{}"),reporting_config:U.string().default("{}"),planner_config:U.string().default("{}"),kpi_config:U.string().default("{}")}),r2={exitDialogOpen:!1},s2=(e,t)=>
198t.type in e?{...e,[t.type]:t.value}:e,dw=m.createContext(null),$l=()=>m.useContext(dw),L_="The model run could not be stopped. Refresh the list and try again.",i2=()=>{const{engagementNiceId:e}=pe(),{data:t=[],isError:n,isFetching:r,isLoading:s,refetch:i}=kV(e,{skip:!e}),[o,{isLoading:l}]=EV(),[c,{isLoading:d}]=_V(),u=m.useCallback(async({kpiId:h,partitionId:f})=>{if(!e)return{error:!0,message:"The engagement context is unavailable. Refresh the page and try again."};const g=await o({engagementNiceId:e,kpiId:h,partitionId:f});return"data"in g?g.data.success?g.data.reconciled?{error:!1,notice:!0,message:g.data.message}:{error:!1}:{error:!0,message:g.data.message||L_}:RL(g.error,L_)},[e,o]),p=m.useCallback(async({kpiId:h,partitionId:f,notes:g,techopsStatus:x})=>{if(!e)return{error:!0};const b=await c({engagementNiceId:e,kpiId:h,notes:g,partitionId:f,techopsStatus:x});return"data"in b&&b.data.success?{error:!1}:{error:!0}},[e,c]);return{executions:t,executionsError:n,executionsLoading:r||s,handleStopExecution:u,handleUpdateExecution:p,refetchExecutions:i,stoppingExecution:l,updatingExecution:d}},lfe=()=>{const{engagementNiceId:e}=pe(),[t,{isLoading:n}]=TV();return{handleRunModels:m.useCallback(({emrRuntime:s,endDate:i,executionDate:o,kpiNiceIds:l,refreshDynamicTables:c,runExternalFactors:d,runPhases:u,skipCompleted:p,skipSubSteps:h,startDate:f})=>e?t({emrRuntime:s,endDate:i,engagementNiceId:e,executionDate:o,kpiNiceIds:l,refreshDynamicTables:c,runExternalFactors:d,runPhases:u,skipCompleted:p,skipSubSteps:h,startDate:f}):Promise.resolve({error:new Error("Missing engagementNiceId")}),[e,t]),isRunning:n}},cfe=e=>{const{engagementNiceId:t}=pe(),[n,{isLoading:r}]=PA();return{handleRunModels:m.useCallback(({emrRuntime:i,endDate:o,executionDate:l,refreshDynamicTables:c,runExternalFactors:d,runPhases:u,skipCompleted:p,skipSubSteps:h,startDate:f})=>t?n({emrRuntime:i,endDate:o,engagementNiceId:t,executionDate:l,kpiId:e,refreshDynamicTables:c,runExternalFactors:d,runPhases:u,skipCompleted:p,skipSubSteps:h,startDate:f}):Promise.resolve({error:new Error("Missing engagementNiceId")}),[t,e,n]),isRunning:r}},a2=()=>{const{engagementNiceId:e}=pe(),[t,{isLoading:n}]=PA();return{handleRunRow:m.useCallback((s,{emrRuntime:i,endDate:o,executionDate:l,refreshDynamicTables:c,runExternalFactors:d,runPhases:u,skipCompleted:p,skipSubSteps:h,startDate:f})=>e?t({emrRuntime:i,endDate:o,engagementNiceId:e,executionDate:l,kpiId:s,refreshDynamicTables:c,runExternalFactors:d,runPhases:u,skipCompleted:p,skipSubSteps:h,startDate:f}):Promise.resolve({error:new Error("Missing engagementNiceId")}),[e,t]),isRunningRow:n}},o2=["IN_PROGRESS","RUNNING"],l2=({jobState:e,updatedAt:t})=>PL({activeStates:o2,status:e,updatedAt:t})?{disabled:!0,message:"Models are already running for this KPI. Wait for the run to finish."}:{disabled:!1,message:""},c2=({editEnabled:e,jobState:t,kpiId:n})=>e&&!!n&&o2.includes(t??""),d2=m.memo(({id:e,jobState:t,kpiId:n,updatedAt:r})=>{const{editEnabled:s,executions:i,openDialog:o,stoppingExecution:l}=$l(),c=m.useCallback(()=>{const f=i.find(g=>g.id===e);f&&o("runRowModels",f)},[i,e,o]),d=m.useCallback(()=>{const f=i.find(g=>g.id===e);f&&o("jobDetails",f)},[i,e,o]),u=m.useCallback(()=>{const f=i.find(g=>g.id===e);f&&o("stop",f)},[i,e,o]),p=c2({editEnabled:s,jobState:t,kpiId:n}),h=l2({jobState:t,updatedAt:r});return a.jsxs($,{alignItems:"center",direction:"row",spacing:1,children:[s?a.jsx(Ji,{ariaLabel:"Run models for this KPI",color:"success",disabled:h.disabled,icon:og,onClick:c,tooltip:h.message||"Run models"}):null,p?a.jsx(Ji,{ariaLabel:"Stop model run",color:"error",disabled:l,icon:lg,iconSize:36,onClick:u,tooltip:"Stop model run"}):null,!p&&s?a.jsx(MM,{}):null,a.jsx(Ji,{ariaLabel:"View job details",color:"brand",icon:aa,iconSize:22,onClick:d,tooltip:"View job details"})]})});d2.displayName="ActionCell";const u2=m.memo(({id:e,status:t})=>{const{executions:n,openDialog:r}=$l(),s=m.useCallback(()=>{const i=n.find(o=>o.id===e);i&&r("jobDetails",i)},[n,e,r]);return a.jsx(Nu,{onClick:s,size:"medium",status:t,sx:{cursor:"pointer"}})});u2.displayName="JobStatusCell";const p2=m.memo(({existingNotes:e,id:t})=>{const{executions:n,openDialog:r}=$l(),s=m.useCallback(()=>{const i=n.find(o=>o.id===t);i&&r("notes",i)},[n,t,r]);return a.jsx(Ie,{"aria-label":"Open notes",onClick:s,size:"small",sx:{color:e?"primary.main":"action.disabled"},children:a.jsx(zL,{})})});p2.displayName="NotesCell";const h2=m.memo(({kpiId:e,partitionId:t,status:n=null})=>{const{editEnabled:r,handleUpdateExecution:s}=$l(),i=o=>{o.stopPropagation();const l=o.target.value;e!=null&&Tn(Ph,l)&&s({kpiId:e,partitionId:t,techopsStatus:l})};return!r||e==null?a.jsx(vL,{status:n}):a.jsx(tt,{onChange:i,size:"small",sx:{color:B0(n).color,fontSize:14,minWidth:140},value:n||"",children:Ph.map(o=>a.jsx(Se,{value:o,children:o},o))})});h2.displayName="TechOpsStatusCell";Z.extend(El);const f2=(e={})=>{const{includeKpiColumn:t=!0}
198=e,n=[{field:"kpiName",flex:1.5,headerName:"KPI",minWidth:200,renderCell:({value:r})=>a.jsx(T,{sx:{fontWeight:600},children:r}),valueGetter:({row:r})=>r.kpiName||r.kpiNiceId},{description:"Model Date is the first day of a model run.",field:"modelDate",flex:1,headerName:"Model Date",minWidth:120,valueFormatter:({value:r})=>r??"-"},{field:"jobName",flex:1,headerName:"Last Process Run",minWidth:150,valueFormatter:({value:r})=>r??"-"},{field:"updatedAt",flex:1,headerName:"Last Updated",minWidth:150,valueFormatter:({value:r})=>r?Z.utc(r).local().format("L LT"):"-"},{field:"jobState",flex:1,headerName:"Job Status",minWidth:120,renderCell:({row:r})=>a.jsx(u2,{id:r.id,status:r.jobState})},{field:"techopsStatus",flex:1,headerName:"Tech Ops Status",minWidth:160,renderCell:({row:r})=>a.jsx(h2,{kpiId:r.kpiId,partitionId:r.id,status:r.techopsStatus})},{field:"notes",headerName:"Notes",minWidth:80,renderCell:({row:r})=>a.jsx(p2,{existingNotes:!!r.notes,id:r.id}),sortable:!1,width:80},{field:"actions",headerName:"Actions",minWidth:165,renderCell:({row:r})=>a.jsx(d2,{id:r.id,jobState:r.jobState,kpiId:r.kpiId,updatedAt:r.updatedAt}),sortable:!1,width:165}];return t?n:n.filter(r=>r.field!=="kpiName")},dfe=()=>{const{engagementNiceId:e}=pe(),{data:t,isLoading:n,isFetching:r}=IV(e??"",{skip:!e}),[s,{isLoading:i}]=DV(),o=m.useCallback(l=>e?s({dataReadyDate:l,engagementNiceId:e}):Promise.resolve({error:new Error("Missing engagementNiceId")}),[e,s]);return{dataReadyDate:t?.dataReadyDate??null,handleSetDataReadyDate:o,isLoading:n||r,isSaving:i}},Qx="YYYY-MM-DD",em=40,ufe="This is the date up until which data is processed and verified for ML use",F_=5e3,m2=({editEnabled:e})=>{const{pushNotification:t}=jt(),{dataReadyDate:n,handleSetDataReadyDate:r,isLoading:s,isSaving:i}=dfe(),[o,l]=m.useState(null);m.useEffect(()=>{l(n?Z(n):null)},[n]);const c=n?Z(n).format(Qx):null,d=o?o.format(Qx):null,u=d!==c,p=async()=>{if(!d)return;"data"in await r(d)?t({content:"Data ready date updated",severity:"success",timeout:F_}):t({content:"Failed to update data ready date",severity:"error",timeout:F_})},h=e?"":"You do not have permission to update the data ready date.";return a.jsx(xu,{dateAdapter:Cu,children:a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1.5},children:[a.jsx(be,{arrow:!0,title:ufe,children:a.jsx(I,{sx:{cursor:"help",fontWeight:700},children:"Data Ready Date:"})}),a.jsx(eo,{disabled:!e||s,format:Qx,onChange:l,slotProps:{textField:{size:"small",sx:{width:180,"& .MuiInputBase-root":{alignItems:"center",height:em},"& .MuiInputBase-input":{py:0,textAlign:"center"}}}},value:o}),a.jsx(be,{title:h,children:a.jsx(T,{children:a.jsx(Dt,{disabled:!e||!o||!u||s,loading:i,onClick:p,sx:{height:em,textTransform:"none"},variant:"contained",children:"Update"})})})]})})},pfe=()=>a.jsx(T,{sx:{alignItems:"center",display:"flex",height:"100%",justifyContent:"center",width:"100%"},children:a.jsx(I,{color:"error.main",children:"Failed to load model executions. Try refreshing."})}),g2=({onClose:e,open:t,row:n})=>{const{engagementNiceId:r}=pe(),{editEnabled:s,executions:i,openDialog:o,stoppingExecution:l}=$l(),c=n?.kpiId,d=n?.id,u=i.find(E=>E.id===d&&E.kpiId===c)??n,p=m.useCallback(()=>{u&&o("runRowModels",u)},[o,u]),h=m.useCallback(()=>{u&&o("stop",u)},[o,u]),f=c2({editEnabled:s,jobState:u?.jobState,kpiId:c}),g=l2({jobState:u?.jobState,updatedAt:u?.updatedAt}),x=[...s?[{ariaLabel:"Run models for this KPI",color:"success",disabled:g.disabled,icon:og,onClick:p,tooltip:g.message||"Run models"}]:[],...f?[{ariaLabel:"Stop model run",color:"error",disabled:l,icon:lg,iconSize:36,onClick:h,tooltip:"Stop model run"}]:[]],{data:b,isError:y,isFetching:v,isLoading:C}=AV({engagementNiceId:r,kpiId:c??0,partitionId:d??0},{skip:!t||!c||!d}),w=n?.kpiName||n?.kpiNiceId||"...",S=n?.modelDate??"...";return a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",onClose:e,open:t,children:[a.jsx(vt,{sx:{py:1.5},children:a.jsxs($,{alignItems:"center",direction:"row",spacing:1.5,children:[a.jsx(T,{color:"primary.main",display:"flex",children:a.jsx(Si,{size:20})}),a.jsx(I,{sx:{flexGrow:1},variant:"h6",children:`Model Details: ${w} (${S})`}),x.length>0?a.jsx($,{direction:"row",spacing:.5,children:x.map(E=>a.jsx(Ji,{...E},E.ariaLabel))}):null]})}),a.jsxs(Ct,{children:[a.jsx(I,{color:"text.secondary",variant:"body2",children:"Detailed information about this model execution"}),a.jsxs(T,{sx:{display:"flex",flexDirection:"column",gap:2.5,pt:1},children:[a.jsxs(T,{sx:{backgroundColor:"background.neutral.default",borderRadius:2,p:2},children:[a.jsx(I,{mb:1.5,variant:"h6",children:"Job Information"}),a.jsxs($,{spacing:2,children:[a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{mb:.5},variant:"body2",children:"Job Status"}),a.jsx(Nu,{isError:y,isLoading:C||v,size:"small",status:b?.status??null})]}),a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{mb:.5},variant:"body2",children:"Step Function ARN"}),C||v?a.jsx(fe,{height:24,width:120}):b?.executionUrl?a.jsxs(xm,{href:b.executionUrl,rel:"noopener noreferrer",sx:{alignItems:"center",display:"inline-flex",gap:.5},target:"_blank",underline:"hover",children:["Step Function",a.jsx(Xv,{size:12})]}):a.jsx(I,{color:"text.secondary",variant:"body2",children:"Not available"})]})]})]}),a.jsx(UL,{isLoading:C||v,traceback:C||v?void 0:b?.traceback})]})]}),a.jsx(un,{sx:{pb:2,px:3},children:a.jsx(re,{color:"secondary",onClick:e,variant:"outlined",children:"Close"})})]})},hfe=()=>
198a.jsx(T,{sx:{alignItems:"center",display:"flex",height:"100%",justifyContent:"center",width:"100%"},children:a.jsx(I,{children:"No model executions found"})}),x2=({editEnabled:e,onClose:t,open:n,row:r})=>{const[s,i]=m.useState(r?.notes||""),{handleUpdateExecution:o}=$l(),l=()=>{i(r?.notes||""),t()},c=()=>{!r?.id||!r.kpiId||(o({kpiId:r.kpiId,partitionId:r.id,notes:s}),t())},d=e&&!!r?.kpiId;return a.jsxs(yt,{fullWidth:!0,maxWidth:"md",onClose:l,open:n,children:[a.jsxs(vt,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between"},children:[a.jsxs(I,{sx:{fontSize:24,fontWeight:600},children:[d&&"Edit"," QA Notes - ",r?.kpiName||r?.kpiNiceId||"..."]}),a.jsx(Ie,{"aria-label":"Close notes dialog",onClick:l,size:"small",children:a.jsx(ji,{})})]}),a.jsx(Ct,{children:a.jsx($,{sx:{rowGap:3},children:a.jsxs(T,{sx:{borderTop:"1px solid",borderColor:"divider",pt:3},children:[a.jsx(I,{sx:{fontSize:16,fontWeight:600,mb:1},children:"QA Notes"}),d?a.jsx(cu,{value:s,onChange:i}):a.jsx(ms,{markdownText:r?.notes||"No Notes Saved"})]})})}),a.jsxs(un,{sx:{px:3,py:2},children:[a.jsx(re,{onClick:l,variant:"outlined",children:d?"Cancel":"Close"}),d&&a.jsx(re,{onClick:c,variant:"contained",children:"Save Notes"})]})]})},ea=[{description:"Prepare engagement-level inputs",name:"Engagement Prep",phase:"engagement_prep",subSteps:[{name:"Run User Demos",subStepName:"user_demos"},{name:"Run SOT Demos",subStepName:"sot_demos"},{name:"Run Sim Universe",subStepName:"sim_universe"},{name:"Run Reporting Universe",subStepName:"reporting_universe"}]},{description:"Prepare media data",name:"Media Prep",phase:"media_prep",subSteps:[{name:"Run Pipeline Snapshot",subStepName:"pipeline_snapshot"},{name:"Run SOT Media",subStepName:"sot_media"},{name:"Run Sim Touchpoints",subStepName:"sim_touchpoints"},{name:"Run User Media Features",subStepName:"user_media_features"}]},{description:"Prepare KPI data",name:"KPI Prep",phase:"kpi_prep",subSteps:[{name:"Run SOT KPI",subStepName:"sot_kpi"},{name:"Run User KPI Demos",subStepName:"user_kpi_demos"},{name:"Run User Export",subStepName:"user_export"}]},{description:"Train the model",name:"Model Training",phase:"training",subSteps:[{name:"Run Train Model",subStepName:"train_model"},{name:"Run External Factors",subStepName:"external_factors",defaultChecked:!1}]},{description:"Run attribution",name:"Attribution",phase:"attrib_touchpoint",subSteps:[{name:"Run Attribution QC Checks",subStepName:"training_qc"}]},{description:"Generate reporting outputs",name:"Reporting",phase:"reporting",subSteps:[{name:"Run Report Attribution",subStepName:"report_attrib"},{name:"Run Snowflake Load",subStepName:"snowflake"},{name:"Run Data Delivery",subStepName:"data_delivery"}]},{description:"Sync Snowflake dynamic tables and shares",name:"Engagement Sync",phase:"engagement_sync",subSteps:[{name:"Run Snowflake Dynamic Tables",subStepName:"snowflake_dynamic_tables"}]},{description:"Set up the planner",name:"Planner Setup",phase:"scenario_planner",subSteps:[{name:"Run Prepare Planner Inputs",subStepName:"prep_planner_inputs"},{name:"Run Snowflake Load",subStepName:"snowflake_load"}]}],$_="external_factors",z_="snowflake_dynamic_tables",B_=()=>ea.filter(e=>e.phase!=="engagement_prep").map(e=>e.phase),ffe=e=>e.subStepName!=null,b2=(e,t)=>e.reduce((n,r)=>(!ffe(r)||r.disabled||(!t||t(r))&&n.push(r.subStepName),n),[]),U_=()=>ea.reduce((e,t)=>(e[t.phase]=b2(t.subSteps,n=>n.defaultChecked!==!1),e),{}),mfe=({selectedPhases:e,selectedSubSteps:t})=>{const n=new Set(t.training??[]),r=new Set(t.engagement_sync??[]),s=ea.reduce((i,o)=>{const l=new Set(t[o.phase]??[]),c=b2(o.subSteps,d=>d.subStepName!==$_&&d.subStepName!==z_&&!l.has(d.subStepName));return c.length>0&&(i[o.phase]=c),i},{});return{refreshDynamicTables:r.has(z_),runExternalFactors:n.has($_),runPhases:e,skipSubSteps:s}},gfe=({checked:e,disabled:t,onChange:n,subStep:r})=>{const s=a.jsx(sn,{control:a.jsx(et,{checked:e,disabled:t,onChange:n,size:"small",sx:{py:.25}}),label:a.jsx(I,{sx:{fontSize:14},children:r.name}),sx:{m:0}});return r.disabled?a.jsx(be,{arrow:!0,title:"Coming soon",children:a.jsx(T,{children:s})}):s},xfe=({disabled:e,onToggleSubStep:t,selectedPhases:n,selectedSubSteps:r})=>a.jsxs(T,{sx:{borderLeft:1,borderColor:"border.default",height:"100%",overflowY:"auto",pl:2.5},children:[a.jsx(I,{sx:{fontWeight:600,mb:1.5},children:"Advanced Options"}
198),a.jsx($,{sx:{gap:2},children:ea.map(s=>{const i=n.includes(s.phase),o=new Set(r[s.phase]??[]);return a.jsxs(T,{children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:12,fontWeight:600,mb:.5,textTransform:"uppercase"},children:s.name}),a.jsx($,{sx:{pl:.5},children:s.subSteps.map(l=>a.jsx(gfe,{checked:!!l.subStepName&&o.has(l.subStepName),disabled:!!e||!!l.disabled||!i,onChange:()=>{l.subStepName&&t(s.phase,l.subStepName)},subStep:l},l.name))})]},s.phase)})})]}),bfe=({children:e,expanded:t,loading:n,onClose:r,onRun:s,open:i,runDisabled:o,selectedCount:l,totalCount:c})=>a.jsxs(yt,{fullWidth:!0,maxWidth:t?"md":"sm",onClose:r,open:i,PaperProps:{sx:{borderRadius:2}},children:[a.jsxs(vt,{sx:{alignItems:"center",display:"flex",gap:1,pb:2,pt:2.5,px:3},children:[a.jsx(Gs,{sx:{color:"primary.main",fontSize:28}}),a.jsx(I,{component:"span",sx:{flex:1,fontSize:20,fontWeight:600},children:"Run New Models"}),a.jsx(Ie,{"aria-label":"Close dialog",disabled:n,onClick:r,size:"small",sx:{color:"text.secondary"},children:a.jsx(ji,{})})]}),a.jsx(Ct,{sx:{px:3,py:2},children:e}),a.jsxs(un,{sx:{justifyContent:"space-between",px:3,py:2},children:[a.jsxs(I,{sx:{color:"text.secondary",fontSize:14},children:[l," of ",c," steps selected"]}),a.jsxs(T,{sx:{display:"flex",gap:1.5},children:[a.jsx(re,{disabled:n,onClick:r,sx:{textTransform:"none"},variant:"outlined",children:"Cancel"}),a.jsx(re,{disabled:o,onClick:s,startIcon:a.jsx(Gs,{}),sx:{textTransform:"none"},variant:"contained",children:"Run Models"})]})]})]}),yfe=({activeKpis:e,disabled:t,kpiNameByNiceId:n,onChange:r,selectedKpis:s})=>a.jsxs(Qe,{fullWidth:!0,sx:{mb:2.5},children:[a.jsx(wt,{id:"run-models-kpi-label",children:"KPIs to Run"}),a.jsx(tt,{disabled:t,input:a.jsx(ys,{label:"KPIs to Run"}),labelId:"run-models-kpi-label",multiple:!0,onChange:r,renderValue:i=>a.jsx(T,{sx:{display:"flex",flexWrap:"wrap",gap:.5},children:i.map(o=>a.jsx(ut,{label:n.get(o)??o,size:"small"},o))}),value:s,children:e.length===0?a.jsx(Se,{disabled:!0,value:"",children:"No active KPIs"}):e.map(i=>a.jsxs(Se,{value:i.niceId,children:[a.jsx(et,{checked:s.includes(i.niceId)}),a.jsx(Kt,{primary:i.name})]},i.niceId))})]}),vfe=({disabled:e,endDate:t,setEndDate:n,setStartDate:r,startDate:s})=>a.jsxs(T,{sx:{display:"flex",gap:2,mb:2.5},children:[a.jsx(eo,{disabled:e,format:"YYYY-MM-DD",label:"Start Date",onChange:i=>r(i),slotProps:{textField:{fullWidth:!0,placeholder:"yyyy-mm-dd",required:!0}},value:s}),a.jsx(eo,{disabled:e,format:"YYYY-MM-DD",label:"End Date (Optional)",...s&&{minDate:s},onChange:i=>n(i),slotProps:{textField:{error:!!(t&&s&&t.isBefore(s)),fullWidth:!0,placeholder:"yyyy-mm-dd"}},value:t})]}),Cfe=({checked:e,disabled:t,onChange:n})=>a.jsx(T,{sx:{backgroundColor:"background.neutral.default",border:1,borderColor:"border.default",borderRadius:1.5,mb:2.5,p:2},children:a.jsx(sn,{control:a.jsx(Dn,{checked:e,disabled:t,onChange:r=>n(r.target.checked)}),label:a.jsxs(T,{children:[a.jsx(I,{sx:{color:"text.primary",fontWeight:600},children:"Skip Successfully Completed Steps"}),a.jsx(I,{sx:{color:"text.secondary",fontSize:14},children:"Only re-run steps that previously failed or haven't been executed"})]}),sx:{alignItems:"flex-start",m:0}})});var Tc={},V_;function wfe(){if(V_)return Tc;V_=1;var e=Pt();Object.defineProperty(Tc,"__esModule",{value:!0}),Tc.default=void 0;var t=e(Lt()),n=Ot();return Tc.default=(0,t.default)((0,n.jsx)("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"}),"Tune"),Tc}var Sfe=wfe();const jfe=dt(Sfe),kfe=({checked:e,disabled:t,onToggle:n,step:r})=>a.jsx(T,{sx:{"&:hover":{backgroundColor:"background.input.hovered"},backgroundColor:"background.input.default",border:1,borderColor:"border.input",borderRadius:1,cursor:t?"default":"pointer",px:2,py:1},children:a.jsx(sn,{control:a.jsx(et,{checked:e,disabled:t,onChange:()=>n(r.phase),sx:{py:0}}),label:a.jsxs(T,{children:[a.jsx(I,{sx:{fontWeight:600},children:r.name}),a.jsx(I,{sx:{color:"text.secondary",fontSize:13},children:r.description})]}),sx:{m:0,width:"100%"}})}),Efe=({advancedOpen:e,allPhasesSelected:t,disabled:n,onToggleAdvanced:r,onToggleAllPhases:s,onTogglePhase:i,selectedPhases:o})=>a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between",mb:1.5},children:[a.jsx(I,{sx:{fontWeight:600},children:"Select Steps to Run"}),a.jsxs(T,{sx:{display:"flex",gap:.5},children:[a.jsx(re,{disabled:n,onClick:s,size:"small",sx:{color:"primary.main",fontSize:14,textTransform:"none"},children:t?"Unselect All":"Select All"}),a.jsx(re,{disabled:n,onClick:r,size:"small",startIcon:a.jsx(jfe,{s
198x:{fontSize:18}}),sx:{color:e?"primary.main":"text.secondary",fontSize:14,textTransform:"none"},children:"Advanced"})]})]}),a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:ea.map(l=>a.jsx(kfe,{checked:o.includes(l.phase),disabled:n,onToggle:i,step:l},l.phase))})]}),tm=({activeKpis:e=[],isRunning:t,mode:n="multi",modelDate:r=null,onClose:s,onRun:i,open:o})=>{const{pushNotification:l}=jt(),c=n==="single",d=n==="row",u=c||d,[p,h]=m.useState([]),[f,g]=m.useState(null),[x,b]=m.useState(null),[y,v]=m.useState(!0),[C,w]=m.useState(B_()),[S,E]=m.useState(U_()),[k,j]=m.useState(!1),[_,D]=m.useState("EMRServerless"),M=m.useMemo(()=>new Map(e.map(G=>[G.niceId,G.name])),[e]);m.useEffect(()=>{o&&(h([]),g(null),b(null),v(!0),w(B_()),E(U_()),j(!1),D("EMRServerless"))},[o]);const N=G=>{const{value:X}=G.target;h(typeof X=="string"?X.split(","):X)},O=G=>{w(X=>X.includes(G)?X.filter(K=>K!==G):[...X,G])},R=(G,X)=>{E(K=>{const ie=K[G]??[],le=ie.includes(X)?ie.filter(ce=>ce!==X):[...ie,X];return{...K,[G]:le}})},L=C.length===ea.length,P=()=>{w(L?[]:ea.map(G=>G.phase))},F=()=>{k&&D("EMRServerless"),j(G=>!G)},z=()=>{s()},B=!!f&&(!x||!x.isBefore(f)),W=!u&&p.length===0||C.length===0||!d&&!B||d&&!r||t,H=async()=>{const G=d?r:f?.format("YYYY-MM-DD");if(!G)return;const{refreshDynamicTables:X,runExternalFactors:K,runPhases:ie,skipSubSteps:le}=mfe({selectedPhases:C,selectedSubSteps:S}),ce=await i({emrRuntime:_,endDate:d?void 0:x?.format("YYYY-MM-DD"),executionDate:G,kpiNiceIds:p,refreshDynamicTables:X,runExternalFactors:K,runPhases:ie,skipCompleted:y,skipSubSteps:le,startDate:G});"data"in ce?(l({content:ce.data.message||"Model run started",severity:"success"}),s()):l({content:"Failed to start model run",severity:"error"})},V=d?`Re-run the model for model date ${r??""}.`:c?"Specify the date range to run for this KPI.":"Specify the date range and the KPIs to run.";return a.jsx(xu,{dateAdapter:Cu,children:a.jsx(bfe,{expanded:k,loading:t,onClose:z,onRun:H,open:o,runDisabled:W,selectedCount:C.length,totalCount:ea.length,children:a.jsxs(T,{sx:{display:"flex",gap:3},children:[a.jsxs(T,{sx:{flex:1,minWidth:0},children:[a.jsx(I,{sx:{color:"text.secondary",mb:2},children:V}
198),!d&&a.jsx(vfe,{disabled:t,endDate:x,setEndDate:b,setStartDate:g,startDate:f}),!u&&a.jsx(yfe,{activeKpis:e,disabled:t,kpiNameByNiceId:M,onChange:N,selectedKpis:p}),a.jsx(Cfe,{checked:y,disabled:t,onChange:v}),k&&a.jsxs(De,{disabled:t,fullWidth:!0,label:"Compute Runtime",onChange:G=>{const{value:X}=G.target;(X==="EMRServerless"||X==="Superglue")&&D(X)},select:!0,size:"small",sx:{mb:3},value:_,children:[a.jsx(Se,{value:"EMRServerless",children:"EMR Serverless"}),a.jsx(Se,{value:"Superglue",children:"Superglue (EMR on EC2)"})]}),a.jsx(Efe,{advancedOpen:k,allPhasesSelected:L,disabled:t,onToggleAdvanced:F,onToggleAllPhases:P,onTogglePhase:O,selectedPhases:C})]}),a.jsx(Yt,{in:k,orientation:"horizontal",sx:{flexShrink:0},unmountOnExit:!0,children:a.jsx(T,{sx:{width:280},children:a.jsx(xfe,{disabled:t,onToggleSubStep:R,selectedPhases:C,selectedSubSteps:S})})})]})})})},y2=({apiRef:e,columns:t,columnVisibilityModel:n,loading:r,onColumnVisibilityChange:s,viewControls:i})=>a.jsx(Pu,{left:a.jsxs(a.Fragment,{children:[a.jsx(Ou,{columns:t,columnVisibilityModel:n,disabled:r,onChange:s}),i?a.jsx(cg,{...i}):null]}),right:a.jsx(Lu,{apiRef:e,loading:r})}),_fe=40,Tfe=60,Ife=rt(Mn)(({theme:e})=>{const{palette:t}=e,{background:n,border:r,text:s}=t;return{border:"none",width:"100%",[`& .${xe.main}`]:{borderRadius:"6px"},[`& .${xe.columnHeaders}`]:{backgroundColor:n.tableHeader},[`& .${xe.columnHeader}`]:{fontSize:12,height:18,textTransform:"uppercase",color:s.secondary},[`& .${xe.columnSeparator}`]:{color:r.default,":hover":{color:r.default}},[`& .${xe.row}:nth-of-type(odd)`]:{backgroundColor:n.paper,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.brand.subtlest.default}},[`& .${xe.row}:nth-of-type(even)`]:{backgroundColor:t.surface.tertiary,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.neutral.hovered}},[`& .${xe.cell}`]:{border:"none"},[` 199 & .${xe.cell}:focus-visible, 200 & .${xe.columnHeader}:focus-visible 201 `]:{outline:`2px solid ${t.primary.main}`,outlineOffset:"-2px"},"& .MuiTablePagination-selectLabel":{fontWeight:500,letterSpacing:.5,lineHeight:"20px",fontSize:12,color:s.secondary},"& .MuiTablePagination-input":{fontWeight:500,letterSpacing:.5,lineHeight:"20px",fontSize:12}}}),v2=({containerSx:e,hideFooter:t=!0,slots:n,...r})=>a.jsx(T,{sx:{width:"100%",...e},children:a.jsx(Ife,{autoHeight:!0,columnHeaderHeight:_fe,disableColumnPinning:!0,hideFooter:t,rowHeight:Tfe,slots:{noRowsOverlay:hfe,...n},...r})}),Dfe=()=>{const{engagementId:e}=pe(),[t]=mC(),[n]=LA(),[r,s]=m.useReducer(s2,r2),i=es(),{kpiFormMode:o}=i.state??{},{state:{kpiFormOpen:l,kpiFormMode:c,selectedKpiId:d},dispatch:u}=zu(),p=o??c,h=p==="edit",f=Xs({mode:"onChange",resolver:Zs(n2),values:void 0});m.useEffect(()=>{h&&d&&f.reset()},[d,h,f]);const g=m.useMemo(()=>({dispatch:s,formMode:p,onClose:()=>{f.reset(),u({type:"kpiFormOpen",value:!1})},onSubmit:async x=>{try{h&&d?await n({engagementId:e,objectives:[{id:d,edits:{objective_name:x.objective_name,value_per_conversion:x.value_per_conversion,kpi_scalar:x.kpi_scalar,algorithm_config:x.algorithm_config||"{}",model_config:x.model_config||"{}",step_functions_config:x.step_functions_config||"{}",reporting_config:x.reporting_config||"{}",planner_config:x.planner_config||"{}",kpi_config:x.kpi_config||"{}",notes:x.notes}}]}):await t({engagementId:e,objectives:[{name:x.objective_name,value_per_conversion:x.value_per_conversion,kpi_scalar:x.kpi_scalar,algorithm_config:x.algorithm_config||"{}",model_config:x.model_config||"{}",step_functions_config:x.step_functions_config||"{}",reporting_config:x.reporting_config||"{}",planner_config:x.planner_config||"{}",kpi_config:x.kpi_config||"{}",notes:x.notes}]}),f.reset(),u({type:"kpiFormOpen",value:!1})}catch{}},open:l,state:r}),[n,t,e,f,h,s,u,l,r,d,p]);return a.jsx(cw.Provider,{value:g,children:a.jsx(Js,{...f,children:a.jsx(t2,{})})})},Afe=({row:e})=>{const[t,n]=m.useState(null),r=!!t,s=en(),i=()=>{n(null)},o=()=>{s("/data-pipeline/machine-learning/objective/:objective_id",{pathParams:{objective_id:e.objective_id.toString()},state:{openKpiFormFromDetail:!0,kpiFormMode:"edit",kpiFormOpen:!0}}),i()};return a.jsxs(T,{children:[a.jsx(Ie,{onClick:l=>{n(l.currentTarget)},sx:{p:.5},children:a.jsx(vl,{size:16})}),a.jsx(dr,{id:"simple-menu",anchorEl:t,open:r,onClose:i,sx:{"> .MuiPaper-root":{width:"120px",borderRadius:"6px"}},children:a.jsx(T,{children:a.jsx(Se,{onClick:o,children:"Edit"})})})]})},Mfe=({value:e})=>e===null?null:a.jsx(ft,{value:e}),Rfe=({value:e})=>
201{if(e==null)return a.jsx(I,{children:"N/A"});const t=new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return a.jsx(I,{children:t})},Nfe=({status:e})=>a.jsx(ut,{label:e,color:e==="Active"?"success":"default"}),Ofe=({value:e})=>e===null?null:a.jsx(ft,{value:e,isCurrency:!0}),ka={resizable:!0,flex:1,minWidth:110},W_=[{...ka,field:"objective_name",headerName:"KPI Name"},{...ka,field:"objective_id",headerName:"KPI Id",minWidth:80},{...ka,field:"value_per_conversion",headerName:"Value per conversion",minWidth:180,renderCell:({row:{value_per_conversion:e}})=>a.jsx(Ofe,{value:e})},{...ka,field:"kpi_scalar",headerName:"KPI Scalar",minWidth:110,renderCell:({row:{kpi_scalar:e}})=>a.jsx(Mfe,{value:e})},{...ka,field:"status",headerName:"Status",minWidth:138,renderCell:({row:{status:e}})=>a.jsx(Nfe,{status:e})},{...ka,field:"last_run_at",headerName:"Last run",minWidth:160,renderCell:({row:{last_run_at:e}})=>a.jsx(Rfe,{value:e})},{...ka,field:"actions",headerName:"Actions",minWidth:90,sortable:!1,filterable:!1,resizable:!1,disableColumnMenu:!0,hideable:!1,renderCell:({row:e})=>a.jsx(Afe,{row:e})}],Pfe=({apiRef:e,columns:t,columnVisibilityModel:n,loading:r,onActiveFilterChange:s,onColumnVisibilityChange:i,showActiveOnly:o,viewControls:l})=>a.jsx(Pu,{left:a.jsxs(a.Fragment,{children:[a.jsx(Ou,{columns:t,columnVisibilityModel:n,disabled:r,onChange:i}),a.jsx(cg,{...l}),a.jsx(OL,{checked:o,onChange:s})]}),right:a.jsx(Lu,{apiRef:e,loading:r})}),Lfe=10,Ffe=15,$fe=40,uw=58,zfe=$fe+uw*Lfe+Ffe,tv=bs(Mn)(({theme:e})=>{const{text:t,background:n,border:r}=e.palette,{spacing:s}=e,i={backgroundColor:n.paper,color:t.default,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.brand.subtlest.default}};return{border:"none",minHeight:uw*2.5,[`.${xe.main}`]:{maxHeight:zfe,height:"100%",borderRadius:"6px",border:"1px solid",borderColor:r.default,boxSizing:"border-box"},[`.${xe.cell}`]:{border:"none",paddingLeft:s(2),paddingRight:s(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1)}},[`.${xe.columnHeader}`]:{paddingLeft:s(2.5),paddingRight:s(1),":focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1.5)}},[`.${xe.columnHeaders}`]:{backgroundColor:n.tableHeader,border:"none"},[`.${xe.columnHeaderTitleContainerContent}`]:{textTransform:"uppercase",fontSize:12},[`.${xe.columnSeparator}`]:{color:r.default,opacity:0},[`.${xe.columnHeader}:hover .${xe["columnSeparator--resizable"]}`]:{opacity:1},[`.${xe["columnSeparator--resizing"]}`]:{opacity:1},[`.${xe.iconButtonContainer}`]:{paddingLeft:s(1.5)},[`.${xe.row}`]:{...i,cursor:"pointer"},[`.${xe.virtualScroller}`]:{width:"calc(100% + 2px)"}}});tv.defaultProps={...tv.defaultProps,columnHeaderHeight:40,disableRowSelectionOnClick:!0,pagination:!0,rowHeight:uw};const H_={items:[{field:"status",operator:"equals",value:"Active"}]},Bfe=()=>{const{objectivesRowsLoading:e,objectivesRows:t}=zu(),n=en(),r=e2(),s=zn(),[i,o]=m.useState({}),[l,c]=m.useState(H_),d=Fu({apiRef:s,onApplyState:f=>{o(f.columns?.columnVisibilityModel??{}),c(f.filter?.filterModel??{items:[]})},storageKey:"machineLearning:views:kpiConfig"}),u=m.useMemo(()=>l.items.some(f=>f.field==="status"&&f.operator==="equals"&&f.value==="Active"),[l]),p=f=>{c(g=>{const x=g.items.filter(b=>b.field!=="status");return f?{...g,items:[...x,...H_.items]}:{...g,items:x}})},h=(f,g)=>{["__check__","actions"].includes(g)||(r("viewKpiSummary"),n("/data-pipeline/machine-learning/objective/:objective_id",{pathParams:{objective_id:f}}))};return a.jsx(T,{sx:{display:"grid",maxWidth:"2000px",pt:2,width:"100%"},children:a.jsx(tv,{apiRef:s,autoHeight:!e,columns:W_,columnVisibilityModel:i,filterModel:l,getRowId:f=>f.objective_id,loading:e,onColumnVisibilityModelChange:o,onFilterModelChange:c,pagination:!1,rows:t,slots:{loadingOverlay:Cs,noRowsOverlay:ng,toolbar:Pfe},slotProps:{toolbar:{apiRef:s,columns:W_,columnVisibilityModel:i,loading:e,onActiveFilterChange:p,onColumnVisibilityChange:o,showActiveOnly:u,viewControls:{disabled:e,onApplyDefault:d.applyDefault,onApplyView:d.applyView,onDeleteView:d.deleteView,onSaveView:d.saveView,selectedViewName:d.selectedViewName,views:d.views}}},onCellClick:({row:f,field:g})=>h(f.objective_id,g)})})},Ufe=()=>{const{dispatch:e,objectivesRows:t}=zu(),{engagementKpiLicense:n}=pe(),r=()=>{e({type:"kpiFormMode",value:"create"}),e({type:"kpiFormOpen",value:!0})},s=t.filter(o=>o.active).length,i=n>-1&&s>=n;return a.jsxs(T,{children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",pb:1},children:[a.jsx(I,{variant:"h6",children:"KPI Configuration"}),a.jsx(T,{sx:{display:"flex",gap:2,height:36},children:a.jsx(re,{variant:"contained",onClick:r,sx:{py:.75,px:2},disabled:i,children:"Create New KPI"})})]}),i&&a.jsx(vn,{severity:"warning",sx:{bgcolor:"background.warning.default",mb:2,color:"text.primary","& .MuiAlert-icon":{color:"text.primary"},display:"flex",alignItems:"center"},children:"KPI limit reached. Please deactivate existing KPIs or contact support to increase your limit."}),a.jsx(Bfe,{}),a.jsx(Dfe,{})]})},Vfe=25,Wfe=25,Hfe=()=>{const[e,t]=m.useState(null),[n,r]=m.useState(null),s=zn(),[i,o]=m.useState({}),l=Fu({apiRef:s,onApplyState:L=>o(L.columns?.columnVisibilityModel??{}),storageKey:"machineLearning:views:mlProcessing"}),c=yn({authorized:"DataPipeline.MachineLearning.Edit"}),{objectivesRows:d}=zu(),{executions:u,executionsError:p,executionsLoading:h,handleStopExecution:f,handleUpdateExecution:g,refetchExecutions:x,stoppingExecution:b}=i2(),{handleRunModels:y,isRunning:v}=lfe(),{handleRunRow:C,isRunningRow:w}=a2(),S=m.useMemo(()=>d.some(L=>L.active),[d]),E=m.useMemo(()=>d.filter(L=>L.active).map(L=>({name:L.objective_name,niceId:L.nice_id})),[d]),k=m.useMemo(()=>f2(),[]),j=m.useCallback((L,P)=>{r(P),t(L)},[]),_=m.useMemo(()=>({editEnabled:c,executions:u,handleStopExecution:f,handleUpdateExecution:g,openDialog:j,stoppingExecution:b}),[c,u,f,g,j,b]),D=m.useCallback(()=>{t("runModels")},[]),M=m.useCallback(()=>{t(null),r(null)},[]),N=m.useCallback(L=>{const P=n?.kpiId;return P?C(P,L):Promise.resolve({error:"Missing KPI"})},[C,n]),O=!c||!S,R=c?S?"":"This action is currently unavailable. There are no active KPIs.":"You do not have permission to run models.";return a.jsxs(dw.Provider,{value:_,children:[a.jsxs($,{sx:{alignItems:"center",flexDirection:"row",gap:1,justifyContent:"space-between",mb:2},children:[a.jsx(m2,{editEnabled:c}),a.jsxs($,{sx:{alignItems:"center",flexDirection:"row",gap:1},children:[a.jsx(be,{title:"Refresh",children:a.jsx("span",{children:a.jsx(Ie,{"aria-label":"Refresh model executions",disabled:h,onClick:()=>x(),children:a.jsx(rw,{})})})}),a.jsx(be,{title:R,children:a.jsx(T,{children:a.jsx(re,{disabled:O,onClick:D,startIcon:a.jsx(Gs,{}),sx:{height:em,textTransform:"none"},variant:"contained",children:"Run New Models"})})})]})]}),a.jsx(T,{children:a.jsx(v2,{apiRef:s,columns:k,disableRowSelectionOnClick:!0,getRowId:L=>L.id,hideFooter:u.length<Wfe,hideFooterSelectedRowCount:!0,initialState:{pagination:{paginationModel:{pageSize:Vfe}}},loading:h,onColumnVisibilityModelChange:o,pageSizeOptions:[10,25,50,100],pagination:!0,rows:u,columnVisibilityModel:i,slots:{toolbar:y2,...p?{noRowsOverlay:pfe}:{}},slotProps:{toolbar:{apiRef:s,columns:k,columnVisibilityModel:i,loading:h,onColumnVisibilityChange:o,viewControl
201s:{disabled:h,onApplyDefault:l.applyDefault,onApplyView:l.applyView,onDeleteView:l.deleteView,onSaveView:l.saveView,selectedViewName:l.selectedViewName,views:l.views}}}})}),a.jsx(x2,{editEnabled:c,onClose:M,open:e==="notes",row:n},n?.id),a.jsx(g2,{onClose:M,open:e==="jobDetails",row:n}),a.jsx(sw,{handleClose:M,handleStop:()=>n?.kpiId?f({kpiId:n.kpiId,partitionId:n.id}):Promise.resolve({error:!0}),jobLabel:n?.kpiName||n?.kpiNiceId||"this KPI",open:e==="stop"}),a.jsx(tm,{activeKpis:E,isRunning:v,mode:"multi",onClose:M,onRun:y,open:e==="runModels"}),a.jsx(tm,{isRunning:w,mode:"row",modelDate:n?.modelDate??null,onClose:M,onRun:N,open:e==="runRowModels"})]})},qfe=()=>{const[e,t]=m.useState("0"),n=(r,s)=>{t(s)};return a.jsxs(co,{value:e,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default",mb:2},children:a.jsxs(uo,{onChange:n,"aria-label":"machine-learning-tabs",children:[a.jsx(_n,{label:"KPIs",value:"0"}),a.jsx(_n,{label:"ML Processing",value:"1"})]})}),a.jsx(xt,{sx:{p:0},value:"0",children:a.jsx(Ufe,{})}),a.jsx(xt,{sx:{p:0},value:"1",children:a.jsx(Hfe,{})})]})},Gfe=()=>{const{openKpiForm:e}=zu(),{state:t}=es(),n=t?.openKpiFormFromDetail,r=t?.kpiData;return m.useEffect(()=>{n&&r&&e("edit",r.objective_id)},[e,n,r]),a.jsxs(T,{sx:{display:"flex",flexDirection:"column",width:ks,minWidth:600},children:[a.jsx(Xt,{title:"Machine Learning"}),a.jsx(qfe,{})]})},Yfe={kpiFormOpen:!1,kpiFormMode:"create",selectedKpiId:null},Kfe=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,Qfe=({children:e})=>{const[t,n]=m.useReducer(Kfe,Yfe),{engagementId:r}=pe(),{data:s,isLoading:i}=MV(r),o=m.useMemo(()=>!s||!Array.isArray(s)?[]:s.map(d=>({objective_id:d.objective_id,objective_name:d.objective_name,nice_id:d.objective_nice_id,value_per_conversion:d.value_per_conversion,kpi_scalar:d.kpi_scalar,active:d.active,last_run_at:d.updated_at,status:d.active?"Active":"Inactive"})),[s]),l=m.useCallback((d,u)=>{n({type:"selectedKpiId",value:d==="edit"&&u?u:null}),n({type:"kpiFormMode",value:d}),n({type:"kpiFormOpen",value:!0})},[n]),c=m.useMemo(()=>({state:t,dispatch:n,objectivesRows:o,objectivesRowsLoading:i,openKpiForm:l}),[t,o,i,l]);return a.jsx(ZL.Provider,{value:c,children:e})},Jfe=()=>a.jsx(Qfe,{children:a.jsx(Gfe,{})}),C2=m.createContext(null),vo=()=>m.useContext(C2),Xfe=()=>{const{data:e,dispatch:t}=vo(),n=()=>{e?.objective_id&&(t({type:"kpiFormOpen",value:!0}),t({type:"kpiFormMode",value:"edit"}))};return a.jsxs($,{direction:"row",justifyContent:"space-between",children:[a.jsx(I,{variant:"h5",children:"KPI Configuration"}),a.jsx(re,{sx:{padding:"4px 10px 4px 15px"},color:"secondary",startIcon:a.jsx(ou,{size:14}),onClick:n,children:"Edit"})]})},Zfe=25,eme=25,tme=()=>{const{data:e}=vo(),[t,n]=m.useState(null),[r,s]=m.useState(null),i=zn(),[o,l]=m.useState({}),c=Fu({apiRef:i,onApplyState:P=>l(P.columns?.columnVisibilityModel??{}),storageKey:"machineLearning:views:mlProcessingObjective"}),d=yn({authorized:"DataPipeline.MachineLearning.Edit"}),u=e?.objective_id,p=e?.objective_nice_id,h=e?.active??!1,{executions:f,executionsLoading:g,handleStopExecution:x,handleUpdateExecution:b,refetchExecutions:y,stoppingExecution:v}=i2(),{handleRunModels:C,isRunning:w}=cfe(u??0),{handleRunRow:S,isRunningRow:E}=a2(),k=m.useMemo(()=>p?f.filter(P=>P.kpiNiceId===p):[],[f,p]),j=m.useMemo(()=>f2({includeKpiColumn:!1}),[]),_=m.useCallback((P,F)=>{s(F),n(P)},[]),D=m.useMemo(()=>({editEnabled:d,executions:k,handleStopExecution:x,handleUpdateExecution:b,openDialog:_,stoppingExecution:v}),[d,k,x,b,_,v]),M=m.useCallback(()=>{n("runModels")},[]),N=m.useCallback(()=>{n(null),s(null)},[]),O=m.useCallback(P=>{const F=r?.kpiId;return F?S(F,P):Promise.resolve({error:"Missing KPI"})},[S,r]),R=!d||!h||!u,L=d?h?u?"":"This action is currently unavailable. KPI details are not loaded yet.":"This action is currently unavailable. This KPI is not active.":"You do not have permission to run models.";return a.jsxs(dw.Provider,{value:D,children:[a.jsxs($,{sx:{alignItems:"center",flexDirection:"row",gap:1,justifyContent:"space-between",mb:2},children:[a.jsx(m2,{editEnabled:d}),a.jsxs($,{sx:{alignItems:"center",flexDirection:"row",gap:1},children:[a.jsx(be,{title:"Refresh",children:a.jsx("span",{children:a.jsx(Ie,{"aria-label":"Refresh model executions",disabled:g,onClick:()=>y(),children:a.jsx(rw,{})})})}),a.jsx(be,{title:L,children:a.jsx(T,{children:a.jsx(re,{disabled:R,onClick:M,startIcon:a.jsx(Gs,{}),sx:{height:em,textTransform:"none"},variant:"contained",children:"Run New Models"})})})]})]}),a.jsx(T,{children:a.jsx(v2,{apiRef:i,columns:j,disableRowSelectionOnClick:!0,getRowId:P=>P.id,hideFooter:k.length<eme,hideFooterSelectedRowCount:!0,initialState:{pagination:{paginationModel:{pageSize:Zfe}}},loading:g,onColumnVisibilityModelChange:l,pageSizeOptions:[10,25,50,100],pagination:!0,rows:k,columnVisibilityModel:o,slots:{toolbar:y2},slotProps:{toolbar:{apiRef:i,columns:j,columnVisibilityModel:o,loading:g,onColumnVisibilityChange:l,viewControl
201s:{disabled:g,onApplyDefault:c.applyDefault,onApplyView:c.applyView,onDeleteView:c.deleteView,onSaveView:c.saveView,selectedViewName:c.selectedViewName,views:c.views}}}})}),a.jsx(x2,{editEnabled:d,onClose:N,open:t==="notes",row:r},r?.id),a.jsx(g2,{onClose:N,open:t==="jobDetails",row:r}),a.jsx(sw,{handleClose:N,handleStop:()=>r?.kpiId?x({kpiId:r.kpiId,partitionId:r.id}):Promise.resolve({error:!0}),jobLabel:r?.kpiName||r?.kpiNiceId||"this KPI",open:t==="stop"}),a.jsx(tm,{isRunning:w,mode:"single",onClose:N,onRun:C,open:t==="runModels"}),a.jsx(tm,{isRunning:E,mode:"row",modelDate:r?.modelDate??null,onClose:N,onRun:O,open:t==="runRowModels"})]})},No=({data:e,title:t,loading:n,sectionName:r})=>{const s=e&&Object.keys(e).length;return a.jsx(Zt,{title:r,children:n?a.jsx(fe,{animation:"pulse",height:42}):a.jsx(oo,{title:t,data:s?[e]:void 0})})},nme=()=>{const{data:e,loading:t}=vo();return a.jsx(Zt,{title:"Settings",children:a.jsxs($,{direction:"row",sx:{gap:2,alignItems:"center",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:"Active "}),t?a.jsx(fe,{width:"100%",height:"22px"}):a.jsx(Dn,{checked:e?.active})]})})},rme=()=>{const{data:e,loading:t}=vo();return a.jsx(Zt,{title:"KPI Performance Indicators",children:a.jsxs($,{gap:2,children:[a.jsxs($,{direction:"row",gap:2,alignItems:"center",children:[a.jsx(I,{variant:"body2",children:"KPI: "}),t?a.jsx(fe,{width:"100%",height:"22px"}):a.jsx(I,{children:e?.objective_name})]}),a.jsxs($,{direction:{xs:"column",sm:"row"},gap:2,alignItems:"center",children:[a.jsxs($,{direction:"row",gap:2,alignItems:"center",flex:1,minWidth:{xs:"100%",sm:"200px"},children:[a.jsx(I,{variant:"body2",children:"Revenue per conversion:"}),t?a.jsx(fe,{width:"100%",height:"22px"}):a.jsx(I,{children:e?.value_per_conversion??"N/A"})]}),a.jsxs($,{direction:"row",gap:2,alignItems:"center",flex:1,minWidth:{xs:"100%",sm:"200px"},children:[a.jsx(I,{variant:"body2",children:"KPI Scalar:"}),t?a.jsx(fe,{width:"100%",height:"22px"}):a.jsx(I,{children:e?.kpi_scalar??"N/A"})]})]})]})})},sme=()=>{const{data:e,loading:t}=vo();return a.jsx(Zt,{title:"Notes",children:a.jsx($,{direction:"row",sx:{gap:2,justifyContent:{xs:"space-between",md:"left"},overflow:"auto",maxHeight:"1050px"},children:t?a.jsx(fe,{width:"100%",height:"32px"}):a.jsx(ms,{markdownText:e?.notes})})})},ime=()=>{const{data:e,loading:t}=vo();return a.jsxs($,{sx:{flexDirection:{md:"row-reverse",s:"column"},gap:3},children:[a.jsxs($,{gap:3,flex:1,children:[a.jsx(nme,{}),a.jsx(sme,{})]}),a.jsxs($,{gap:3,flex:2,children:[a.jsx(rme,{}),a.jsx(No,{sectionName:"Model Configuration",title:"external_factors",data:e?.model_config,loading:t}),a.jsx(No,{sectionName:"Algorithm Configuration",title:"prior_defaults",data:e?.algorithm_config,loading:t}),a.jsx(No,{sectionName:"Step Function Configuration",title:"steps",data:e?.step_functions_config,loading:t}),a.jsx(No,{sectionName:"Reporting Configuration",title:"connections",data:e?.reporting_config,loading:t}),a.jsx(No,{sectionName:"Planner Configuration",title:"num_sim_draw",data:e?.planner_config,loading:t}),a.jsx(No,{sectionName:"KPI Configuration",title:"sot_kpi",data:e?.kpi_config,loading:t})]})]})},ame=()=>{const[e,t]=m.useState("overview"),n=(r,s)=>{t(s)};return a.jsxs(co,{value:e,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default",mb:2},children:a.jsxs(uo,{onChange:n,"aria-label":"kpi-configuration-tabs",children:[a.jsx(_n,{label:"Overview",value:"overview"}),a.jsx(_n,{label:"ML Processing",value:"ml-processing"})]})}),a.jsx(xt,{value:"overview",children:a.jsx(ime,{})}),a.jsx(xt,{sx:{p:0},value:"ml-processing",children:a.jsx(tme,{})})]})},ome=()=>{const{data:e,loading:t,handleNavigateToParent:n,state:{kpiFormOpen:r,kpiFormMode:s},dispatch:i}=vo(),{engagementId:o}=pe(),[l]=mC(),[c]=LA(),[d,u]=m.useReducer(s2,r2),p=es(),h=en(),{openKpiFormFromDetail:f,kpiFormMode:g}=p.state||{},x=g||s,b=x==="edit";m.useEffect(()=>{f&&!r&&h("/data-pipeline/machine-learning",{replace:!0})},[f,r,h]),m.useEffect(()=>{f&&e&&window.history.replaceState({},"",window.location.pathname)},[f,x,e,i]);const y=()=>{const w={objective_name:"",value_per_conversion:0,kpi_scalar:null,algorithm_config:"{}",active:!0,model_config:"{}",step_functions_config:"{}",reporting_config:"{}",planner_config:"{}",kpi_config:"{}",notes:""};if(b&&e){const S=E=>typeof E=="string"?E:JSON.stringify(E||{});return{objective_name:e.objective_name||"",value_per_conversion:e.value_per_conversion||0,kpi_scalar:e.kpi_scalar??null,active:e.active??!0,notes:e.notes||"",algorithm_config:S(e.algorithm_config),model_config:S(e.model_config),step_functions_config:S(e.step_functions_config),reporting_config:S(e.reporting_config),planner_config:S(e.planner_config),kpi_config:S(e.kpi_config)}}return w},v=Xs({mode:"onChange",resolver:Zs(n2),values:y()}),C=m.useMemo(()=>({dispatch:u,formMode:x,onClose:()=>{v.reset(),i({type:"kpiFormOpen",value:!1})},onSubmit:async w=>{try{const S={objective_name:w.objective_name,value_per_conversion:w.value_per_conversion,kpi_scalar:w.kpi_scalar,algorithm_config:w.algorithm_config||"{}",model_config:w.model_config||"{}",step_functions_config:w.step_functions_config||"{}",reporting_config:w.reporting_config||"{}",planner_config:w.planner_config||"{}",kpi_config:w.kpi_config||"{}",active:w.active,notes:w.notes};b&&e?await c({engagementId:o,objectives:[{id:e.objective_id,edits:S}]}):await l({engagementId:o,objectives:[{name:w.objective_name,...S}]}),v.reset(),i({type:"kpiFormOpen",value:!1})}catch{i({type:"kpiFormOpen",value:!1})}},open:r,state:d}),[u,v,r,d,i,b,e,o,c,l,x]);return a.jsxs(T,{children:[!r&&a.jsxs(a.Fragment,{children:[a.jsx(vu,{handleNavigateHome:n,pageName:e?.objective_name??"...",parentConfig:{handleNavigateToParent:n,parentName:"Machine Learning"}}),a.jsx(Xfe,{}),a.jsx(ame,{})]}),a.jsx(cw.Provider,{value:C,children:a.jsx(Js,{...v,children:a.jsx(t2,{isLoading:t})})})]})},lme=(e,t)=>
201{switch(t.type){case"kpiFormOpen":return{...e,kpiFormOpen:t.value};case"kpiFormMode":return{...e,kpiFormMode:t.value};default:return e}},cme=({loading:e,data:t})=>{const n=en(),r=es(),{kpiFormMode:s,kpiFormOpen:i}=r.state||{},o={kpiFormOpen:i||!1,kpiFormMode:s||"create"},[l,c]=m.useReducer(lme,o),d=m.useCallback(()=>n("/data-pipeline/machine-learning"),[n]),u=m.useMemo(()=>({loading:e,data:t,handleNavigateToParent:d,state:l,dispatch:c}),[t,d,e,l,c]);return a.jsx(C2.Provider,{value:u,children:a.jsx(ome,{})})},dme=()=>{const e=en(),{objective_id:t=""}=Cm(),{engagementNiceId:n}=pe(),{data:r,isLoading:s,isSuccess:i,isError:o}=RV(t),{engagement_nice_id:l}=r??{};return m.useEffect(()=>{!s&&o&&e("/data-pipeline/machine-learning")},[o,s,i,e]),m.useEffect(()=>{l&&n&&l!==n&&e("/data-pipeline/machine-learning")},[e,l,n]),a.jsx(cme,{loading:s,data:r})},w2=m.createContext(null),Ei=()=>m.useContext(w2),ume=["id","name","connectorName","status","isExport","lastAuthenticatedAt","updatedAt","createdAt"],Ms={id:"Id",name:"Name",connectorName:"Connector",status:"Status",isExport:"Mode",lastAuthenticatedAt:"Last Authorized",updatedAt:"Updated",createdAt:"Created",actions:"Actions"},pme={id:!0,name:!0,connectorName:!0,status:!0,isExport:!0,lastAuthenticatedAt:!0,updatedAt:!1,createdAt:!1},hme={visibilityModel:pme,dataConnectionFormMode:"closed",connectionToDelete:null,connectionToAuthorize:null,connectionToEdit:null},fme=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,q_=e=>typeof e=="object"&&e!==null,mme=e=>q_(e)&&"errorResponse"in e&&q_(e.errorResponse),gme=({children:e,dataConnectionsRows:t,isLoadingDataConnections:n})=>{const r=yn({authorized:"DataSources.Connections.Create"}),s=yn({authorized:"DataSources.Connections.Delete"}),i=yn({authorized:"DataSources.Connections.Edit"}),[o]=NV(),[l]=OV(),{data:c=[],isLoading:d,isError:u}=mu(),p=m.useMemo(()=>c.reduce((w,S)=>({...w,[S.name]:S}),{}),[c]),h=m.useMemo(()=>c.reduce((w,S)=>({...w,[S.id]:S}),{}),[c]),[f,g]=m.useReducer(fme,hme),x=zn(),b=m.useCallback(async w=>o(w),[o]),y=m.useCallback(async({connection_type:w,credentials:S})=>{if(!S)return{is_valid:!1,message:"Missing credentials"};try{return await l({connection_type:w,credentials:S}).unwrap()}catch(E){return mme(E)?{is_valid:!1,message:E.message||"Connection Failed"}:{is_valid:!1,message:"Connection Failed"}}},[l]),v=m.useCallback(w=>{g({type:"dataConnectionFormMode",value:w})},[g]),C=m.useMemo(()=>({canCreateConnection:r,canDeleteConnection:s,canEditConnection:i,connectorsByName:p,connectorsById:h,dataConnectionsRows:t,dispatch:g,handleDelete:b,handleTestConnection:y,gridApiRef:x,isErrorConnectors:u,isLoadingConnectors:d,isLoadingDataConnections:n,openDataConnectionForm:v,state:f}),[r,s,i,h,p,t,b,y,x,u,d,n,v,f]);return a.jsx(w2.Provider,{value:C,children:e})},xme={createConnection:"Create Connection",authenticate:"Authenticate Connection",edit:"Edit Connection",delete:"Delete Connection",copyUrl:"Copy Connection URL"},ug=()=>pr({actionMap:xme,eventName:"dataConnections"}),S2=m.createContext(null),pg=()=>m.useContext(S2),Bu=()=>on(),bme=(e,t,n)=>{if(e==="create"||t===null)return{apiConnectorId:"",dataConnectionName:"",isExport:!1};const s=n[t.connectorName]?.id.toString()??"",{name:i,authConfig:o}=t;return{apiConnectorId:s,dataConnectionName:i,authConfig:o,isExport:!1}},Jx=e=>e!=null&&e!=="",yme=({allowTestConnection:e,authConfigValues:t,selectedConnector:n,deliveryMethod:r,authConfigString:s})=>{if(!e||!t||!n?.authConfig||s==="{}"||!n.authConfig.filter(l=>l.required).map(l=>l.name).every(l=>Jx(t[l])))return!1;if(r==="sftp"){const l=Jx(t.password),c=Jx(t.private_key);return l||c}return!0},nv=e=>{const t={...e};return typeof t.private_key=="string"&&t.private_key.includes("\\n")&&(t.private_key=t.private_key.replace(/\\n
201/g,` 202`)),t},vme=({connectorId:e,deliveryMethod:t,engagementId:n,engagementNiceId:r,isExport:s,normalizedAuthConfig:i,dataConnectionName:o})=>{const l={delivery_method:t,engagement_id:String(n),engagement_nice_id:r,connector_id:String(e),is_export:s,connection_name:o};return i?{...l,...i}:l},j2=({handleSuccess:e,setProcessing:t,setError:n})=>{const{engagementId:r,engagementNiceId:s}=pe(),i=yn({authorized:"DataSources.Connections.Create"}),o=yn({authorized:"DataSources.Connections.Edit"}),[l]=PV(),[c]=LV(),[d]=FV(),[u]=$V(),p=ug(),h=async({connectionId:y,deliveryMethod:v})=>{try{const{consent_url:C}=await l({connection_id:y,engagement_id:String(r),engagement_nice_id:s,delivery_method:v}).unwrap();return C}catch{return null}},f=async({authenticateAccessMode:y,connectionId:v,deliveryMethod:C})=>{const w=await h({connectionId:v,deliveryMethod:C});if(!w){n("Failed to generate oauth url"),t(!1);return}if(y==="CopyLink"){t(!1),await navigator.clipboard.writeText(w),e?.();return}window.open(w,"_blank","width=1200,height=800,noopener,noreferrer"),setTimeout(()=>{t(!1),e?.()},2e3)};return{handleGenerateOauthLink:async({connectionId:y,deliveryMethod:v})=>{t(!0),n("");const C=await h({connectionId:y,deliveryMethod:v});return t(!1),C||(n("Failed to generate Oauth URL"),null)},handleCreateConnection:async({data:y,authenticateAccessMode:v,selectedConnector:C})=>{if(i){t(!0),n("");try{const{apiConnectorId:w,dataConnectionName:S,authConfig:E,isExport:k}=y,j=Number(w),{name:_,niceId:D}=C,M=E?nv({...E}):void 0;if(C.authType==="credentials"){const O=await d(vme({connectorId:j,deliveryMethod:D,engagementId:r,engagementNiceId:s,isExport:k,normalizedAuthConfig:M,dataConnectionName:S})).unwrap();if(typeof O=="object"&&O!==null){const{success:R,message:L}=O;if(!R){n(L||"Failed to create connection"),t(!1);return}}p("createConnection",{connectionName:S,connectorName:_,authenticateAccessMode:v,authConfig:M}),t(!1),e?.();return}const N=await c({auth_status:"pending",name:S,engagement_id:r,engagement_nice_id:s,connector_id:j,auth_config:M}).unwrap();if(p("createConnection",{connectionId:N,connectionName:S,connectorName:_,authenticateAccessMode:v,authConfig:M}),!v){e?.();return}await f({authenticateAccessMode:v,connectionId:String(N),deliveryMethod:D})}catch{n("Something went wrong while creating the connection. Please try again later or contact support."),t(!1);return}t(!1),e?.()}},handleUpdateConnection:async({data:y,connectionId:v,authenticateAccessMode:C,selectedConnector:w,isDirty:S})=>{if(!o)return;if(t(!0),n(""),p("edit",{connectionId:v,connectionName:y.dataConnectionName,authConfig:y.authConfig,authenticateAccessMode:C}),S){const k=await u({body:{name:y.dataConnectionName,auth_config:y.authConfig},pathParameters:{id:v}});if(t(!1),"error"in k){n("The connection could not be updated. Please try again later");return}}if(!C){e?.();return}const{niceId:E}=w;await f({authenticateAccessMode:C,connectionId:String(v),deliveryMethod:E})}}},Cme=()=>{const{state:{connectionToAuthorize:e},dispatch:t}=Ei(),{data:n=[]}=mu(),r=ug(),[s,i]=m.useState(!1),[o,l]=m.useState(!1),[c,d]=m.useState(""),{handleGenerateOauthLink:u}=j2({setProcessing:i,setError:d}),p=()=>{t({type:"connectionToAuthorize",value:null})},h=n?.find(v=>v.name===e?.connectorName),f=h?.niceId||"",g=h?.authButton,x=async()=>{const v=await u({connectionId:String(e?.id),deliveryMethod:f});return v||(setTimeout(()=>{d("")},5e3),null)},b=async()=>{const v=await x();v&&(window.open(v,"_blank","width=1200,height=800,noopener,noreferrer"),e&&r("authenticate",{connectionId:e.id,connectionName:e.name,connectorName:e.connectorName}),setTimeout(p,2e3))},y=async()=>{const v=await x();v&&(l(!0),await navigator.clipboard.writeText(v),e&&r("copyUrl",{connectionId:e.id,connectionName:e.name,connectorName:e.connectorName}),setTimeout(()=>{l(!1)},5e3))};return a.jsxs(yt,{open:!!e,children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"row",justifyContent:"space-between",paddingRight:1},children:[a.jsx(vt,{children:"Authorize Connection"}),a.jsx(Ie,{"aria-label":"close",disableRipple:!0,onClick:p,children:a.jsx(Jt,{})})]}),a.jsx(Ct,{sx:{display:"flex",gap:2,flexDirection:"column",width:540},children:a.jsxs(T,{sx:{display:"flex",gap:2,flexDirection:"column",alignItems:"center"},children:[a.jsxs(I,{children:["Connect ",a.jsx("b",{children:e?.name})," to ",a.jsx("b",{children:e?.connectorName})]}),a.jsxs(T,{display:"flex",flexDirection:"column",gap:1,children:[a.jsx(iA,{brand:g,onClick:b,loading:s}),a.jsx(Dt,{startIcon:a.jsx(Zv,{}),onClick:y,loading:s,variant:"contained",children:"Copy link"})]}),a.jsx(Yt,{in:o,children:a.jsx(vn,{severity:"success",sx:{mb:2,bgcolor:"background.success.default",color:"text.primary","& .MuiAlert-icon":{color:"text.primary"}},children:"OAuth link successfully generated and copied to your clipboard"})}),a.jsx(Yt,{in:!!c,children:a.jsx(vn,{severity:"error",sx:{mb:2,bgcolor:"background.error.default",color:"text.primary","& .MuiAlert-icon":{color:"text.primary"}},children:c})})]})})]})},wme=({error:e,setError:t})=>a.jsx(DD,{open:!!e,onClose:()=>t(""),anchorOrigin:{horizontal:"center",vertical:"top"},autoHideDuration:5e3,message:"This Snackbar will be dismissed in 5 seconds.",children:a.jsx(vn,{severity:"error",sx:{mb:2,bgcolor:"background.error.default",color:"text.primary","& .MuiAlert-icon":{color:"text.primary"}},children:e})}),Sme=({control:e,errors:t,register:n,setValue:r,isLoadingConnectors:s,isErrorConnectors:i,sortedConnectorsData:o,editing:l})=>a.jsx(Zt,{title:"Data Connection",children:a.jsxs($,{gap:2,children:[i&&a.jsx(I,{color:"error",children:"Failed to load data connectors."}),a.jsx(Et,{name:"apiConnectorId",control:e,render:({field:c})=>a.jsx(Nt,{isLoading:s,width:"100%",children:a.jsxs(Qe,{fullWidth:!0,error:!!t.apiConnectorId,children:[a.jsx(wt,{id:"api-connector-label",sx:{"&.MuiInputLabel-shrink":{bgcolor:"background.paper",px:1,ml:-.5}},children:"Select API Connector"}),a.jsx(tt,{labelId:"api-connector-label",label:"Select API Connector",value:c.value!==void 0&&c.value!==null?String(c.value):"",onCh
202ange:d=>{c.onChange(String(d.target.value)),r("authConfig",void 0)},renderValue:d=>{const u=o.find(p=>String(p.id)===d);return u?a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[u.logoUrl&&a.jsx(T,{sx:{mr:1},children:a.jsx(sa,{src:u.logoUrl})}),a.jsx("span",{children:u.name})]}):""},disabled:s||i||o.length===0||l,children:o.map(d=>a.jsx(Se,{value:String(d.id),children:a.jsxs(T,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(sa,{src:d.logoUrl}),a.jsx("span",{children:d.name})]})},d.id))})]})})}),a.jsx(De,{label:"Data Connection Name",fullWidth:!0,...n("dataConnectionName"),error:!!t.dataConnectionName,helperText:t.dataConnectionName?.message})]})}),jme=()=>{const{watch:e}=Bu(),t=e("apiConnectorId"),{connectorsByIdData:n}=pg(),r=n[t];return!r?.authConfig||r.authConfig.length===0?null:a.jsx(Zt,{title:"Configuration",children:a.jsx(FC,{parentField:"authConfig",fields:r.authConfig})})},kme=()=>{const{control:e}=Bu();return a.jsx(Zt,{title:"Connection Type",children:a.jsx(Et,{name:"isExport",control:e,defaultValue:!1,render:({field:t})=>a.jsxs(ml,{color:"primary",exclusive:!0,fullWidth:!0,value:t.value?"export":"import",onChange:(n,r)=>{r!==null&&t.onChange(r==="export")},children:[a.jsx(yi,{value:"import",children:"Import"}),a.jsx(yi,{value:"export",children:"Export"})]})})})},Eme=()=>{const{control:e,formState:{errors:t},register:n,setValue:r,watch:s}=Bu(),{setRaiseConversationIcon:i}=jt(),{connectorsByNameData:o,connectorsByIdData:l,isLoadingConnectors:c,isErrorConnectors:d,formMode:u}=pg(),p=s("apiConnectorId"),f=l[p]?.authType==="credentials",g=m.useMemo(()=>{const x=Object.values(o);return x?[...x].filter(b=>b.active&&(b.diProcess==="connector"||b.diProcess==="glue")).sort((b,y)=>b.name.toLocaleLowerCase().localeCompare(y.name.toLocaleLowerCase())):[]},[o]);return m.useEffect(()=>(i(!0),()=>{i(!1)}),[i]),a.jsx(T,{component:"form",id:"kpi-form",children:a.jsxs($,{sx:{py:2,px:{xs:8,lg:30},minWidth:400,gap:3,justifyContent:"center",flexDirection:{xs:"column",lg:"column"}},children:[a.jsx(Sme,{editing:u==="edit",control:e,errors:t,register:n,setValue:r,isLoadingConnectors:c,isErrorConnectors:d,sortedConnectorsData:g}),a.jsx(jme,{}),f&&a.jsx(kme,{})]})})},_me=({onClick:e=()=>{},disabled:t=!1,loading:n=!1,status:r,errorMessage:s,sx:i})=>a.jsx(tR,{status:r,statusText:"Connection",buttonText:"Test Connection",errorMessage:s,onClick:e,disabled:t,loading:n,sx:i}),Tme=({handleClickClose:e})=>{const{connectorsByIdData:t,onSubmit:n,submittingForm:r,formMode:s}=pg(),{handleTestConnection:i}=Ei(),{formState:{isValid:o,isDirty:l},watch:c,getValues:d,clearErrors:u,trigger:p}=Bu(),{pushNotification:h}=jt(),f=c("apiConnectorId"),g=m.useMemo(()=>t[f],[t,f]),x=g?.niceId||"",b=g?.authType||"",y=g?.authButton,v=!!y,C=b==="credentials",w=c("authConfig"),S=JSON.stringify(w),E=m.useMemo(()=>yme({allowTestConnection:C,authConfigValues:w,selectedConnector:g,deliveryMethod:x,authConfigString:S}),[C,w,g,x,S]),k=P=>{const F=d(),z={...F,authConfig:F.authConfig?nv(F.authConfig):void 0};n({data:z,authenticateAccessMode:P,isDirty:l})},[j,_]=m.useState({status:null,testedConfigString:""}),[D,M]=m.useState(!1),N=m.useMemo(()=>!C||j.testedConfigString!==S?null:j.status,[C,j,S]),O=(P,F)=>{_({status:"error",testedConfigString:P,errorMessage:F})},R=!o||s==="edit"&&!l||C&&N!=="success",L=async()=>{const{authConfig:P}=d();if(!P||!x)return;const F=nv({...P});u(),M(!0);const z=await i({connection_type:x,credentials:F});z.is_valid?(u(),await p(),h({content:"Connection Succeeded",severity:"success",timeout:1e4}),_({status:"success",testedConfigString:S})):(h({content:z.message||"Connection Failed",severity:"error",timeout:1e4}),O(S,z.message)),M(!1)};return a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(re,{onClick:e,sx:{maxWidth:200,m:2},variant:"outlined",color:"secondary",children:"Cancel"}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",gap:2,pr:2,alignItems:"center"},children:[C&&a.jsx(_me,{loading:D,onClick:L,disabled:!E||D,status:N,errorMessage:j.errorMessage,sx:{my:2,px:2.5,width:200,height:45}}),v&&a.jsx(iA,{brand:y,loading:r,onClick:()=>k("SignIn"),disabled:!o,sx:{my:2,px:2.5,width:200,height:45}}),v&&a.jsx(Dt,{loading:r,onClick:()=>k("CopyLink"),disabled:!o,sx:{my:2,height:45},variant:"contained",startIcon:a.jsx(Zv,{}),children:"Copy Link"}),a.jsx(Dt,{loading:r,onClick:()=>k(),disabled:R,sx:{my:2,px:2.5,width:200,height:45},variant:"contained",children:s==="create"?"Create Data Connection":"Update Connection"})]})]})},Ime=()=>{const{dispatch:e,onClose:t,open:n,state:r}=pg(),{exitDialogOpen:s}=r,{formState:{isDirty:i},reset:o}=Bu(),l=()=>{if(i){e({type:"exitDialogOpen",value:!0});return}t()},c=()=>{e({type:"exitDialogOpen",value:!1})},d=()=>{o(),e({type:"exitDialogOpen",value:!1}),t()};return a.jsxs(yt,{fullScreen:!0,open:n,children:[a.jsxs(vt,{variant:"h6",sx:{p:3,pt:4,"&.MuiTypography-h6":{fontSize:18,lineHeight:"22px"}},children:["Add Data Connection",a.jsx(Ie,{onClick:l,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})})]}),a.jsx(Ct,{sx:{pb:6.5,display:"flex",flexDirection:"column"},children:a.jsx(Eme,{})}),a.jsx(Tme,{handleClickClose:l}),a.jsx(mt,{bodyText:"You have unsaved data. If you leave the page, these changes will be lost.",handleClose:c,handleAccept:d,open:s,title:"Cancel New Data Connection",acceptLabel:"Yes, Cancel"})]})},Dme=U.object({apiConnectorId:U.string().min(1,"API Connector is required"),dataConnectionName:U.string().min(1,"Data Connection Name is required"),authConfig:U.record(U.unknown()).optional(),isExport:U.boolean().optional()}),Ame={exitDialogOpen:!1},Mme=(e,t)=>
202t.type in e?{...e,[t.type]:t.value}:e,Rme=({connectorsByNameData:e,connectorsByIdData:t,isErrorConnectors:n,isLoadingConnectors:r})=>{const[s,i]=m.useReducer(Mme,Ame),[o,l]=m.useState(""),[c,d]=m.useState(!1),{state:{dataConnectionFormMode:u,connectionToEdit:p},dispatch:h,canCreateConnection:f,canEditConnection:g}=Ei(),x=m.useCallback(()=>{h({type:"dataConnectionFormMode",value:"closed"}),i({type:"exitDialogOpen",value:!1})},[h,i]),{handleCreateConnection:b,handleUpdateConnection:y}=j2({setError:l,setProcessing:d,handleSuccess:x}),v=Xs({mode:"onChange",resolver:Zs(Dme)});m.useEffect(()=>{if(u==="closed")return;const E=bme(u,p,e);v.reset(E,{keepDirty:!1,keepTouched:!1})},[p,e,u,v]);const C=m.useCallback(({data:E,authenticateAccessMode:k,isDirty:j})=>{if(u==="create")b({data:E,authenticateAccessMode:k,selectedConnector:t[E.apiConnectorId]});else if(u==="edit"&&p?.id){const{apiConnectorId:_,...D}=E;y({connectionId:p.id,data:D,authenticateAccessMode:k,selectedConnector:t[E.apiConnectorId],isDirty:j})}},[p,t,u,b,y]),w=m.useMemo(()=>({state:s,dispatch:i,open:u!=="closed",formMode:u,onClose:x,onSubmit:C,connectorsByNameData:e,connectorsByIdData:t,isLoadingConnectors:r,isErrorConnectors:n,canCreateConnection:f,canEditConnection:g,submitError:o,submittingForm:c}),[s,u,x,C,e,t,r,n,f,g,o,c]);return(u==="create"?f:u==="edit"?g:!1)?a.jsx(S2.Provider,{value:w,children:a.jsxs(Js,{...v,children:[a.jsx(Ime,{}),a.jsx(wme,{error:o,setError:l})]})}):null},Nme=()=>{const{state:{connectionToDelete:e},dispatch:t,handleDelete:n}=Ei(),[r,s]=m.useState(""),[i,o]=m.useState(!1),l=ug(),c=()=>{t({type:"connectionToDelete",value:null}),s("")},d=async()=>{if(!e)return;o(!0),l("delete",{connectionId:e.id,connectionName:e.name});const u=await n(e.id);if(o(!1),"error"in u){s("An error occurred while trying to delete this connection");return}c()};return a.jsx(eg,{captchaText:"DELETE",deleting:i,errorMessage:r,onClose:c,onDelete:d,open:!!e,resourceName:e?.name??"",resourceType:"Connection"})},Ome=({row:e})=>{const[t,n]=m.useState(null),r=!!t,s=ug(),i=()=>{n(null)},{canDeleteConnection:o,canEditConnection:l,connectorsByName:c,dispatch:d,isLoadingConnectors:u}=Ei(),p=m.useMemo(()=>u?!1:c[e.connectorName]?.authType==="oauth2.0",[c,u,e.connectorName]),h=()=>{s("edit",{connectionId:e.id,connectionName:e.name}),d({type:"dataConnectionFormMode",value:"edit"}),d({type:"connectionToEdit",value:e}),i()},f=()=>{d({type:"connectionToAuthorize",value:e}),i()},g=()=>{d({type:"connectionToDelete",value:e}),i()};return a.jsxs(T,{children:[a.jsx(Ie,{onClick:x=>{n(x.currentTarget)},sx:{p:.5},children:a.jsx(vl,{size:16})}),a.jsx(dr,{id:"simple-menu",anchorEl:t,open:r,onClose:i,sx:{"> .MuiPaper-root":{width:"120px",borderRadius:"6px"}},children:a.jsxs(T,{children:[l&&a.jsx(Se,{onClick:h,children:"Edit"}),p&&a.jsx(Se,{onClick:f,children:"Authorize"}),o&&a.jsx(Se,{onClick:g,children:"Delete"})]})})]})},Xx=({value:e})=>
202{if(e==null)return a.jsx(I,{children:"N/A"});const t=new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return a.jsx(I,{sx:{whiteSpace:"normal",wordBreak:"break-word"},children:t})},Pme={PENDING:"Waiting for user to complete authorization",DENIED:"User denied access during authorization.",REVOKED:"Access previously granted has been removed",EXPIRED:"Authorization has expired. Please reauthorize",ERROR:"An error occurred during authorization. Please try again or contact support"},Lme=({row:e})=>{const{dispatch:t,connectorsByName:n,isLoadingConnectors:r}=Ei(),{status:s}=e,i=s.toUpperCase()==="AUTHORIZED",o=m.useMemo(()=>r?!1:n[e.connectorName]?.authType==="oauth2.0",[n,r,e.connectorName]),l=!i&&o,c=()=>{switch(s.toUpperCase()){case"ACTIVE":case"AUTHORIZED":return"success";case"PENDING":return"warning";case"REVOKED":case"ERROR":case"EXPIRED":case"DENIED":return"error";default:return"default"}},d=()=>{t({type:"connectionToAuthorize",value:e})},u=Pme[s.toUpperCase()]??"";return a.jsx(be,{title:u,arrow:!0,placement:"right",children:a.jsx(ut,{label:Im(s),color:c(),onClick:l?d:void 0,sx:{...l&&{cursor:"pointer","&:hover":{opacity:.8}}}})})},ci={sortable:!0,type:"action",resizable:!0,flex:1,minWidth:110},Fme=[{...ci,field:"name",headerName:Ms.name,minWidth:250},{...ci,field:"id",headerName:Ms.id,type:"number",valueFormatter:({value:e})=>e,maxWidth:80},{...ci,field:"connectorName",headerName:Ms.connectorName},{...ci,field:"status",headerName:Ms.status,renderCell:({row:e})=>a.jsx(Lme,{row:e})},{...ci,field:"isExport",headerName:Ms.isExport,valueGetter:({value:e})=>e===!0?"Export":"Import"},{...ci,field:"lastAuthenticatedAt",headerName:Ms.lastAuthenticatedAt,type:"dateTime",valueGetter:({value:e})=>e?new Date(e):null,renderCell:({row:{lastAuthenticatedAt:e}})=>a.jsx(Xx,{value:e})},{...ci,field:"createdAt",headerName:Ms.createdAt,type:"dateTime",valueGetter:({value:e})=>e?new Date(e):null,renderCell:({row:{createdAt:e}})=>a.jsx(Xx,{value:e})},{...ci,field:"updatedAt",headerName:Ms.updatedAt,type:"dateTime",valueGetter:({value:e})=>e?new Date(e):null,renderCell:({row:{updatedAt:e}})=>a.jsx(Xx,{value:e})},{...ci,field:"actions",headerName:Ms.actions,sortable:!1,renderCell:({row:e})=>a.jsx(Ome,{row:e}),maxWidth:120}],$me=100,zme={pagination:{paginationModel:{pageSize:$me}}},Bme=58,rv=rt(Mn)(({theme:e})=>{const{palette:t}=e,{background:n,border:r,surface:s,text:i}=t,o=t.mode==="dark";return{border:"none",width:"100%",[`& .${xe.main}`]:{borderRadius:"6px"},[`& .${xe.columnHeaders}`]:{backgroundColor:n.tableHeader},[`& .${xe.columnHeader}`]:{color:i.secondary,fontSize:12,textTransform:"uppercase"},[`& .${xe.columnSeparator}`]:{color:r.default,":hover":{color:r.default}},[`& .${xe.row}:nth-of-type(odd)`]:{backgroundColor:n.paper,":hover":{backgroundColor:o?n.brand.subtle.hovered:n.brand.subtlest.default}},[`& .${xe.row}:nth-of-type(even)`]:{backgroundColor:s.tertiary,":hover":{backgroundColor:o?n.brand.subtle.hovered:n.neutral.hovered}},[`& .${xe.cell}`]:{border:"none"},[` 203 & .${xe.cell}:focus, 204 & .${xe.cell}:focus-within, 205 & .${xe.columnHeader}:focus, 206 & .${xe.columnHeader}:focus-within 207 `]:{outline:"none"}}});rv.defaultProps={...rv.defaultProps,columnHeaderHeight:40,disableColumnMenu:!1,disableColumnFilter:!1,disableRowSelectionOnClick:!0,pagination:!0,rowHeight:Bme};const Ume=()=>ume.map(e=>({field:e,label:Ms[e]})),Vme=()=>{const{state:{visibilityModel:e},dispatch:t,gridApiRef:n,isLoadingDataConnections:r}=Ei(),s=m.useMemo(()=>Ume().map(({field:i,label:o})=>({field:i,headerName:o})),[]);return a.jsx(Pu,{left:a.jsx(Ou,{columns:s,columnVisibilityModel:e,disabled:r,onChange:i=>t({type:"visibilityModel",value:i})}),right:a.jsx(Lu,{apiRef:n,loading:r})})},Wme=()=>{const{dataConnectionsRows:e,isLoadingDataConnections:t,state:{visibilityModel:n},gridApiRef:r}=Ei(),s=m.useMemo(()=>a.jsx(rv,{apiRef:r,loading:t,autoHeight:!t,columnVisibilityModel:n,columns:Fme,initialState:zme,pageSizeOptions:[100],rows:e,getRowId:i=>i.id,disableColumnPinning:!0,disableColumnSelector:!0,slots:{loadingOverlay:Cs,noRowsOverlay:ng,toolbar:Vme}}),[e,r,t,n]);return a.jsx(T,{sx:{width:"100%",maxWidth:"2000px",display:"grid"},children:s})},Hme=()=>{const{openDataConnectionForm:e,isLoadingConnectors:t,isErrorConnectors:n,connectorsByName:r,connectorsById:s}=Ei();return a.jsxs(T,{children:[a.jsxs(T,{mb:4,display:"flex",alignItems:"center",justifyContent:"space-between",children:[a.jsx(Xt,{title:"Data Connections"}),a.jsx(ar,{authorized:"DataSources.Connections.Create",children:a.jsx(re,{variant:"contained",color:"primary",onClick:()=>e("create"),children:"Create New Data Connection"})})]}),a.jsx(Wme,{}),a.jsx(Rme,{connectorsByNameData:r,connectorsByIdData:s,isLoadingConnectors:t,isErrorConnectors:n}),a.jsx(Cme,{}),a.jsx(Nme,{})]})},qme=()=>{const{engagementId:e}=pe(),{isLoading:t,data:n=[]}=fC({engagement_id:e},{pollingInterval:3e4});return a.jsx(gme,{dataConnectionsRows:n,isLoadingDataConnections:t,children:a.jsx(Hme,{})})},k2=m.createContext(null),zl=()=>m.useContext(k2),Gme={approveAlert:"Approve Alert",changeTab:"Change Tab",confirmEdits:"Confirm Edits",createAlert:"Create Alert",deleteAlert:"Delete Alert",download:"Download CSV",submit:"Submit",toggleAdjustValues:"Toggle Adjust Values",updateNotes:"Update Notes"},Bl=()=>pr({actionMap:Gme,eventName:"dataVerification"}),E2=e=>`${e.id} - ${e.vendor_nice_id}_${e.content_type}_${e.feed_nice_id}`.toLocaleLowerCase(),Zx=e=>
207e===null?"0":e.toLocaleString("en-US"),_2=["=","!=",">",">=","<","<="],Yme=_2,Kme=e=>Yme.includes(e),Qme=e=>{if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=Number(t);return Number.isFinite(n)?n:null},T2=e=>{const t={columns:e.columns},{filterModel:n,searchText:r,sortModel:s}=e;if(n?.items?.length&&n.logicOperator){const i=n.items.map(({field:o,operator:l,value:c})=>{if(!Kme(l))return null;const d=Qme(c);if(d===null)return null;const u=[o,d];return{[l]:u}}).filter(o=>o!==null);i.length&&(t.having={[n.logicOperator]:i})}return r&&(t.search=r),s.length&&(t.sort=s.map(({field:i,sort:o})=>({ascending:o==="asc",column:i}))),t},G_="YYYY-MM-DD",Jme=({dataSource:e,endDate:t,engagementNiceId:n,exportColumns:r,gridParams:s,startDate:i})=>({...T2(s),datasource_id:e,end_date:t.format(G_),engagement_nice_id:n,export_columns:r,start_date:i.format(G_)}),Xme=({loading:e,onClose:t,onConfirm:n,open:r})=>{const{metadataByDatasource:s,metadataList:i,metadataLoading:o,validationDataSources:l}=zl(),{engagementCountry:c,engagementId:d}=pe(),{data:u=[],isLoading:p}=MA(d,{skip:!r||!d}),[[h,f],g]=m.useState([null,null]),[x,b]=m.useState(),[y,v]=m.useState(),C=m.useMemo(()=>i.length?l.filter(R=>i.some(L=>L.datasource_id===R.id)):l,[i,l]),w=m.useMemo(()=>u.filter(R=>!R.is_internal),[u]),S=m.useMemo(()=>w.map(R=>({label:`${R.name} (${R.email})`,value:R.id})),[w]),[E,k]=m.useMemo(()=>{if(!x)return[null,null];const R=s.get(x);return R?[R.min_date?Z(R.min_date):null,R.max_date?Z(R.max_date):null]:[null,null]},[x,s]);m.useEffect(()=>{if(x&&E&&k){const R=k.subtract(3,"month");g([E>R?E:R,k])}else x&&g([null,null])},[x,E,k]);const _=h&&f&&h.isValid()&&f.isValid()&&f>=h&&x&&!e,D=C.map(R=>({label:E2(R),value:R.id})),M=m.useCallback(()=>{t(),g([null,null]),b(void 0),v(void 0)},[t]),N=m.useCallback(()=>{if(!h||!f||!x)return;const R=y?w.find(L=>L.id===y):void 0;n(h.format("YYYY-MM-DD"),f.format("YYYY-MM-DD"),x,R?{email:R.email,name:R.name}:void 0),g([null,null]),b(void 0),v(void 0)},[h,f,x,y,w,n]),O=m.useCallback(R=>{b(R),g([null,null])},[]);return a.jsxs(yt,{BackdropProps:{id:"create-alert-dialog-backdrop"},"data-testid":"data-verification:create-alert-dialog",id:"create-alert-dialog",onClose:M,open:r,PaperProps:{sx:{width:560}},children:[a.jsxs(vt,{sx:{p:3.125,pb:3},children:[a.jsx("span",{children:"Create an alert"}),a.jsx(Ie,{"aria-label":"Close dialog","data-testid":"data-verification:create-alert-dialog:close",id:"create-alert-dialog-title-close-button",onClick:M,sx:{position:"absolute",right:25,top:25},children:a.jsx(Jt,{size:24})})]}),a.jsxs(Ct,{sx:{p:"0 25px 0"},children:[a.jsx(I,{sx:{mb:3.125},children:"Select a data source and start/end date to send an email data verification alert."}),e||o?a.jsx(T,{sx:{display:"flex",justifyContent:"center",mb:3.75},children:a.jsx(Ze,{})}):a.jsxs(a.Fragment,{children:[a.jsxs(Qe,{fullWidth:!0,size:"small",sx:{mb:3.75},variant:"outlined",children:[a.jsx(wt,{id:"create-alert-datasource-label",sx:{backgroundColor:"background.paper",px:.5},children:"Data Source"}),a.jsx(tt,{"data-testid":"data-verification:create-alert-dialog:datasource",id:"create-alert-data-source-input",label:"Data Source",labelId:"create-alert-datasource-label",onChange:R=>O(Number(R.target.value)),value:x??"",children:D.map(R=>a.jsx(Se,{value:R.value,children:R.label},R.value))})]}),a.jsxs(Qe,{fullWidth:!0,size:"small",sx:{mb:3.75},variant:"outlined",children:[a.jsx(wt,{id:"create-alert-contact-label",sx:{backgroundColor:"background.paper",px:.5},children:"Contact (Optional)"}),a.jsxs(tt,{"data-testid":"data-verification:create-alert-dialog:contact",disabled:p,id:"create-alert-contact-input",label:"Contact (Optional)",labelId:"create-alert-contact-label",onChange:R=>v(R.target.value?Number(R.target.value):void 0),value:y??"",children:[a.jsx(Se,{value:"",children:a.jsx("em",{children:"None"})}),S.map(R=>a.jsx(Se,{value:R.value,children:R.label},R.value))]})]})]}),a.jsx(T,{children:a.jsx(ts,{disabled:!x||o,fullWidth:!0,locale:c,maxDate:k||void 0,minDate:E||void 0,setValue:g,value:[h,f]})})]}),a.jsxs(un,{sx:{m:"40px 25px 55px"},children:[a.jsx(re,{color:"primary","data-testid":"data-verification:create-alert-dialog:cancel",id:"create-alert-cancel-button",onClick:M,variant:"outlined",children:"Cancel"}),a.jsx(re,{color:"primary","data-testid":"data-verification:create-alert-dialog:confirm",disabled:!_,id:"create-alert-confirm-button",onClick:N,sx:{ml:5},variant:"contained",children:"Create Alert"})]})]})},Zme=({dataSource:e,loadingDataSources:t,setDataSource:n})=>{const{metadataList:r,validationDataSources:s}=zl(),i=r.length?s.filter(o=>r.some(l=>l.datasource_id===o.id)):s;return t?a.jsx(fe,{height:40,sx:{minWidth:200,width:300},variant:"rounded"}):a.jsxs(Qe,{size:"small",sx:{minWidth:200,width:300},variant:"outlined",children:[a.jsx(wt,{id:"verification-datasource-label",sx:{backgroundColor:"background.paper",px:.5},children:"Data Source"}),a.jsx(tt,{"data-testid":"data-verification:datasource:select",disabled:i.length<=1,id:"verification-table-datasource-select",label:"Data Source",labelId:"verification-datasource-label",onCh
207ange:o=>n(Number(o.target.value)),value:e??"",children:i.map(o=>a.jsx(Se,{value:o.id,children:E2(o)},o.id))})]})},ege=({conversions:e,impressions:t,investment:n,valuePerConversion:r,valueToShow:s})=>{switch(s){case"conversions":return e;case"impressions":return t/e;case"investment":return n/e;case"roas":return r?e*r/n:0;default:return 0}},hg="en-US",tge=new Intl.NumberFormat(hg,{notation:"compact"}),I2=new Intl.NumberFormat(hg,{style:"percent",minimumFractionDigits:2,maximumFractionDigits:2}),pw=(e,{locale:t=hg,options:n}={})=>e!==null?new Intl.NumberFormat(t,{...n,maximumFractionDigits:0}).format(e):"",Ci=(e,{locale:t=hg,options:n={}}={})=>{const{currency:r="USD",maximumFractionDigits:s=0,style:i="currency",...o}=n;return e!==null?new Intl.NumberFormat(t,{currency:r,maximumFractionDigits:s,style:i,...o}).format(e):""},fg=e=>pw(e),D2=e=>pw(e),A2=e=>e!==null?new Intl.NumberFormat("en-US",{style:"percent"}).format(e):"",nge=({value:e,valueToShow:t,currency:n="USD"})=>{if(!t)return"";switch(t){case"conversions":return fg(e);case"impressions":return D2(e);case"investment":return Ci(e,{options:{currency:n,maximumFractionDigits:2,minimumFractionDigits:2}});case"roas":return A2(e);default:return""}},Y_=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none !important"> 208 <path d="M17.5 12.5V15.8333C17.5 16.2754 17.3244 16.6993 17.0118 17.0118C16.6993 17.3244 16.2754 17.5 15.8333 17.5H4.16667C3.72464 17.5 3.30072 17.3244 2.98816 17.0118C2.67559 16.6993 2.5 16.2754 2.5 15.8333V12.5" stroke="${e}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 209 <path d="M5.8335 8.33337L10.0002 12.5L14.1668 8.33337" stroke="${e}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 210 <path d="M10 12.5V2.5" stroke="${e}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 211</svg>`,K_=rt(ua)(({theme:e})=>({".apexcharts-menu-icon svg":{fill:"none !important"},".apexcharts-menu-icon svg path":{stroke:`${e.palette.icon.default} !important`},".apexcharts-menu-icon":{transform:"none"},".apexcharts-svg":{overflow:"visible"},".apexcharts-menu":{backgroundColor:`${e.palette.background.paper} !important`,border:`1px solid ${e.palette.border.default} !important`},".apexcharts-menu-item":{color:`${e.palette.text.primary} !important`},".apexcharts-menu-item:hover":{backgroundColor:`${e.palette.background.secondary.hovered} !important`}})),rge=({data:e,loading:t=!1})=>{const n=Re(),{palette:{chartBrand:r}}=n,{engagementCurrency:s}=pe(),i=m.useMemo(()=>{const c=[...e].sort((d,u)=>Z(d.date).diff(Z(u.date)));return{dates:c.map(d=>Z(d.date).format("MMM D, YYYY")),spend:c.map(d=>d.spend),impressions:c.map(d=>d.impressions)}},[e]),o=m.useMemo(()=>{const c=u=>new Intl.NumberFormat("en",{currency:s,notation:"compact",style:"currency"}).format(u),d=u=>Ci(u,{options:{currency:s,maximumFractionDigits:0}});return{chart:{type:"line",toolbar:{show:!0,tools:{download:Y_(n.palette.icon.default),selection:!1,zoom:!1,zoomin:!1,zoomout:!1,pan:!1,reset:!1}}},stroke:{curve:"smooth",width:2},xaxis:{categories:i.dates,labels:{rotate:-45,rotateAlways:!1,showDuplicates:!1,hideOverlappingLabels:!0,maxHeight:120},tickAmount:10},yaxis:{labels:{formatter:c}},tooltip:{y:{formatter:d}},colors:[r.secondary.bold]}},[i.dates,r.secondary.bold,s,n.palette.icon.default]),l=m.useMemo(()=>({chart:{type:"line",toolbar:{show:!0,tools:{download:Y_(n.palette.icon.default),selection:!1,zoom:!1,zoomin:!1,zoomout:!1,pan:!1,reset:!1}}},stroke:{curve:"smooth",width:2},xaxis:{categories:i.dates,labels:{rotate:-45,rotateAlways:!1,showDuplicates:!1,hideOverlappingLabels:!0,maxHeight:120},tickAmount:10},yaxis:{labels:{formatter:c=>new Intl.NumberFormat("en",{notation:"compact"}).format(c)}},tooltip:{y:{formatter:c=>c.toLocaleString("en-US")}},colors:[r.tertiary.bold]}),[i.dates,r.tertiary.bold,n.palette.icon.default]);return t||e.length===0?a.jsxs(T,{sx:{display:"flex",gap:2,mb:3,width:"100%"},children:[a.jsx(Ve,{sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontSize:14,fontWeight:600,mb:2},children:"Total Spend by Day"}),a.jsx(T,{sx:{height:250},children:a.jsx(fe,{height:"100%",variant:"rectangular"})})]})}),a.jsx(Ve,{sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontSize:14,fontWeight:600,mb:2},children:"Total Impressions by Day"}),a.jsx(T,{sx:{height:250},children:a.jsx(fe,{height:"100%",variant:"rectangular"})})]})})]}):a.jsxs(T,{sx:{display:"flex",gap:2,mb:3,width:"100%"},children:[a.jsx(Ve,{sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontSize:14,fontWeight:600,mb:2},children:"Total Spend by Day"}),a.jsx(K_,{options:o,series:[{name:"Spend",data:i.spend}],type:"line",height:250})]})}),a.jsx(Ve,{sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontSize:14,fontWeight:600,mb:2},children:"Total Impressions by Day"}),a.jsx(K_,{options:l,series:[{name:"Impressions",data:i.impressions}],type:"line",height:250})]})})]})},sge=[5,10,25,50],ige=25;rl.And,rl.And;const age={account_id:!1,account_name:!1,adgroup_id:!1,adgroup_name:!1,adjusted_impressions:!1,adjusted_investment:!1,brand:!1,campaign_id:!1,campaign_name:!1,clicks:!0,creative_attribute_1:!1,creative_attribute_2:!1,creative_attribute_3:!1,creative_attribute_4:!1,creative_attribute_5:!1,creative_attribute_6:!1,creative_attribute_7:!1,creative_attribute_8:!1,creative_id:!1,creative_name:!1,gl_market_name:!1,gl_platform_name:!1,gl_program_name:!1,gl_tactic_name:!1,gl_type_name:!0,gl_vehicle_name:!0,initial_impressions:!1,initial_investment:!1,kpi_attribute_1:!1,kpi_attribute_2:!1,kpi_attribute_3:!1,kpi_attribute_4:!1,kpi_attribute_5:!1,kpi_attribute_6:!1,kpi_attribute_7:!1,kpi_attribute_8:!1,max_date:!0,media_attribute_1:!1,media_attribute_2:!1,media_attribute_3:!1,media_attribute_4:!1,media_attribute_5:!1,media_attribute_6:!1,media_attribute_7:!1,media_attribute_8:!1,message:!1,min_date:!0,placement_id:!1,placement_name:!1,row_access:!1,start_date:!1,total_impressions:!0,total_investment:!0,vendor_nice_id:!1},M2=["min_date","max_date","initial_investment","adjusted_investment","total_investment","initial_impressions","adjusted_impressions","total_impressions","clicks","i
211d"],oge=_m().filter(({value:e})=>_2.some(t=>t===e)),lge=e=>e.type==="number"?{...e,filterOperators:oge}:{...e,filterable:!1},cge=e=>[{align:"left",field:"account_id",flex:1,headerAlign:"left",headerName:"Account ID",minWidth:150},{align:"left",field:"account_name",flex:1,headerAlign:"left",headerName:"Account Name",minWidth:200},{align:"left",field:"adgroup_id",flex:1,headerAlign:"left",headerName:"Adgroup ID",minWidth:150},{align:"left",field:"adgroup_name",flex:1,headerAlign:"left",headerName:"Adgroup Name",minWidth:200},{align:"left",field:"brand",flex:1,headerAlign:"left",headerName:"Brand",minWidth:150},{align:"left",field:"campaign_id",flex:1,headerAlign:"left",headerName:"Campaign ID",minWidth:150},{align:"left",field:"campaign_name",flex:1,headerAlign:"left",headerName:"Campaign Name",minWidth:200},{align:"left",field:"creative_id",flex:1,headerAlign:"left",headerName:"Creative ID",minWidth:150},{align:"left",field:"creative_name",flex:1,headerAlign:"left",headerName:"Creative Name",minWidth:200},{align:"left",field:"message",flex:1,headerAlign:"left",headerName:"Creative Message",minWidth:200},{align:"left",field:"creative_attribute_1",flex:1,headerAlign:"left",headerName:"Creative Attribute 1",minWidth:180},{align:"left",field:"creative_attribute_2",flex:1,headerAlign:"left",headerName:"Creative Attribute 2",minWidth:180},{align:"left",field:"creative_attribute_3",flex:1,headerAlign:"left",headerName:"Creative Attribute 3",minWidth:180},{align:"left",field:"creative_attribute_4",flex:1,headerAlign:"left",headerName:"Creative Attribute 4",minWidth:180},{align:"left",field:"creative_attribute_5",flex:1,headerAlign:"left",headerName:"Creative Attribute 5",minWidth:180},{align:"left",field:"creative_attribute_6",flex:1,headerAlign:"left",headerName:"Creative Attribute 6",minWidth:180},{align:"left",field:"creative_attribute_7",flex:1,headerAlign:"left",headerName:"Creative Attribute 7",minWidth:180},{align:"left",field:"creative_attribute_8",flex:1,headerAlign:"left",headerName:"Creative Attribute 8",minWidth:180},{align:"left",field:"gl_market_name",flex:1,headerAlign:"left",headerName:"Market",minWidth:150},{align:"left",field:"kpi_attribute_1",flex:1,headerAlign:"left",headerName:"KPI Attribute 1",minWidth:180},{align:"left",field:"kpi_attribute_2",flex:1,headerAlign:"left",headerName:"KPI Attribute 2",minWidth:180},{align:"left",field:"kpi_attribute_3",flex:1,headerAlign:"left",headerName:"KPI Attribute 3",minWidth:180},{align:"left",field:"kpi_attribute_4",flex:1,headerAlign:"left",headerName:"KPI Attribute 4",minWidth:180},{align:"left",field:"kpi_attribute_5",flex:1,headerAlign:"left",headerName:"KPI Attribute 5",minWidth:180},{align:"left",field:"kpi_attribute_6",flex:1,headerAlign:"left",headerName:"KPI Attribute 6",minWidth:180},{align:"left",field:"kpi_attribute_7",flex:1,headerAlign:"left",headerName:"KPI Attribute 7",minWidth:180},{align:"left",field:"kpi_attribute_8",flex:1,headerAlign:"left",headerName:"KPI Attribute 8",minWidth:180},{align:"left",field:"media_attribute_1",flex:1,headerAlign:"left",headerName:"Media Attribute 1",minWidth:180},{align:"left",field:"media_attribute_2",flex:1,headerAlign:"left",headerName:"Media Attribute 2",minWidth:180},{align:"left",field:"media_attribute_3",flex:1,headerAlign:"left",headerName:"Media Attribute 3",minWidth:180},{align:"left",field:"media_attribute_4",flex:1,headerAlign:"left",headerName:"Media Attribute 4",minWidth:180},{align:"left",field:"media_attribute_5",flex:1,headerAlign:"left",headerName:"Media Attribute 5",minWidth:180},{align:"left",field:"media_attribute_6",flex:1,headerAlign:"left",headerName:"Media Attribute 6",minWidth:180},{align:"left",field:"media_attribute_7",flex:1,headerAlign:"left",headerName:"Media Attribute 7",minWidth:180},{align:"left",field:"media_attribute_8",flex:1,headerAlign:"left",headerName:"Media Attribute 8",minWidth:180},{align:"left",field:"gl_type_name",flex:1,headerAlign:"left",headerName:"Media Type",minWidth:150},{align:"left",field:"placement_id",flex:1,headerAlign:"left",headerName:"Placement ID",minWidth:150},{align:"left",field:"placement_name",flex:1,headerAlign:"left",headerName:"Placement Name",minWidth:200},{align:"left",field:"gl_platform_name",flex:1,headerAlign:"left",headerName:"Platform",minWidth:150},{align:"left",field:"gl_program_name",flex:1,headerAlign:"left",headerName:"Program",minWidth:150},{align:"left",field:"row_access",flex:1,headerAlign:"left",headerName:"Row Access",minWidth:150},{align:"left",field:"start_date",flex:1,headerAlign:"left",headerName:"Date",minWidth:120},{align:"left",field:"gl_tactic_name",flex:1,headerAlign:"left",headerName:"Tactic",minWidth:150},{align:"left",field:"gl_vehicle_name",flex:1,headerAlign:"left",headerName:"Vehicle",minWidth:150},{align:"left",field:"vendor_nice_id",flex:1,headerAlign:"left",headerName:"Vendor",minWidth:150},{align:"left",field:"min_date",flex:1,headerAlign:"left",headerName:"Min Date",minWidth:120},{align:"left",field:"max_date",flex:1,headerAlign:"left",headerName:"Max Date",minWidth:120},{align:"left",field:"initial_investment",headerAlign:"left",headerName:"Spend",renderCell:({value:t})=>a.jsx(ft,{isCurrency:!0,value:typeof t=="number"?t:0}),type:"number",width:150},{align:"left",editable:!e,field:"adjusted_investment",headerAlign:"left",headerName:"Adjusted Spend",renderCell:({value:t})=>a.jsx(ft,{isCurrency:!0,value:typeof t=="number"?t:0}),type:"number",width:150},{align:"left",field:"total_investment",headerAlign:"left",headerName:"Total Spend",renderCell:({value:t})=>a.jsx(ft,{isCurrency:!0,value:typeof t=="number"?t:0}),type:"number",width:150},{align:"left",field:"initial_impressions",headerAlign:"left",headerName:"Impressions",type:"number",valueFormatter:t=>Zx(typeof t.value=="number"||t.value===null?t.value:null),width:150},{align:"left",editable:!e,field:"adjusted_impressions",headerAlign:"left",headerName:"Adjusted Impressions",type:"number",valueFormatter:t=>Zx(typeof t.value=="number"||t.value===null?t.value:null),width:180},{align:"left",field:"total_impressions",headerAlign:"left",headerName:"Total Impressions",type:"number",valueFormatter:t=>Zx(typeof t.value=="number"||t.value===null?t.value:null),width:180},{align:"left",field:"clicks",headerAlign:"left",headerName:"Clicks",type:"number",width:150}],dge=e=>cge(e).map(lge),R2=rt(Mn)(({theme:e})=>{const{palette:t,spacing:n}=e,{background:r,border:s,text:i}=t;return{border:"none",[`& .${xe.main}`]:{borderRadius:n(2)},[`& .${xe.columnHeaders}`]:{backgroundColor:r.tableHeader},[`& .${xe.columnHeader}`]:{fontSize:12,height:18,textTransform:"uppercase",color:i.secondary},[`& .${xe.columnHeaderCheckbox}`]:{paddingLeft:0,paddingRight:0},[`& .${xe.columnSeparator}`]:{color:s.default,":hover":{color:s.default}},[`& .${xe.row}:nth-of-type(n)`]:{backgroundColor:r.paper,":hover":{backgroundColor:e.palette.mode==="dark"?r.brand.subtle.hovered:r.brand.subtlest.default},"&.edited-row":{backgroundColor:e.palette.mode==="dark"?t.info.dark:t.
211info.light,":hover":{backgroundColor:e.palette.mode==="dark"?t.info.dark:t.info.light}},"&.hide-row":{display:"none"}},[`& .${xe.cell}`]:{border:"none"},[` 212 & .${xe.cell}:focus-visible, 213 & .${xe.cell}:focus-within:has(:focus-visible), 214 & .${xe.columnHeader}:focus-visible, 215 & .${xe.columnHeader}:focus-within:has(:focus-visible) 216 `]:{outline:`2px solid ${t.primary.main}`,outlineOffset:"-2px"}}}),uge=({columnDefinitions:e,columnVisibilityModel:t,disabled:n=!1,onSelect:r})=>{const[s,i]=m.useState(t),o=m.useCallback(()=>{i(t)},[t]),l=e.filter(f=>!f.alwaysOn&&f.field!=="initial_impressions"&&f.field!=="initial_investment"),c=l.filter(f=>f.type!=="number").sort((f,g)=>{const x=f.headerName||"",b=g.headerName||"";return x.localeCompare(b)}),d=l.filter(f=>f.type==="number").sort((f,g)=>{const x=f.headerName||"",b=g.headerName||"";return x.localeCompare(b)}),u=m.useCallback(f=>{const{value:g}=f.target,x=typeof g=="string"?g.split(","):g,b={...s,...l.reduce((y,v)=>({...y,[v.field]:x.includes(v.field)}),{})};i(b)},[l,s]),p=m.useCallback(()=>{Kn(t,s)||r(s)},[t,s,r]),h=l.filter(f=>s[f.field]).map(f=>f.field);return a.jsx(Qe,{children:a.jsxs(tt,{"data-testid":"data-verification:column:select",disabled:n,id:"data-verification-column-selector",multiple:!0,onChange:u,onClose:p,onOpen:o,renderValue:()=>a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center",color:n?"text.disabled":"text.secondary"},children:[a.jsx(po,{size:19}),a.jsx(I,{component:"span",sx:{height:24,lineHeight:"24px"},children:"Columns"})]}),sx:{height:38,width:142},value:h,children:[a.jsx(Se,{disabled:!0,sx:{opacity:1},children:a.jsx(I,{sx:{color:"text.primary",fontWeight:600},children:"Dimensions"})}),c.map(({field:f,headerName:g})=>a.jsxs(Se,{value:f,children:[a.jsx(et,{checked:s[f]}),a.jsx(Kt,{primary:g})]},f)),a.jsx(Se,{disabled:!0,sx:{mt:1,opacity:1},children:a.jsx(I,{sx:{color:"text.primary",fontWeight:600},children:"Totals"})}),d.map(({field:f,headerName:g})=>a.jsxs(Se,{value:f,children:[a.jsx(et,{checked:s[f]}),a.jsx(Kt,{primary:g})]},f))]})})},pge=1e3,hge=({disabled:e=!1,onSearchSubmit:t})=>{const[n,r]=m.useState(""),s=m.useRef(null);m.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]);const i=m.useCallback(o=>{const l=o.target.value||"";r(l),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{t(l),s.current=null},pge)},[t]);return a.jsx(Qe,{children:a.jsx(ys,{"aria-label":"Search verification data",disabled:e,id:"data-verification-search-input",inputProps:{"data-testid":"data-verification:search:input"},onChange:i,placeholder:"Search",startAdornment:a.jsx(Bn,{position:"start",sx:{color:"text.disabled"},children:a.jsx(er,{})}),sx:{height:38,width:300},value:n})})},fge=e=>Object.entries(e).filter(([t,n])=>n&&!M2.includes(t)).map(([t])=>t),mge=(e,t)=>e.filter(n=>t[n.field]!==!1).map(n=>n.field),gge=({canExport:e,columns:t,dataSource:n,effectiveColumnVisibility:r,hasEdits:s,isLoading:i,isSubmittingExport:o,onColumnVisibilityChange:l,onSaveEdits:c,onSearchSubmit:d,onToggleChange:u,rows:p,savingEdits:h,submitExportRequest:f,toggleEnabled:g,userCanEdit:x})=>{const b=Bl(),{pushNotification:y}=jt(),v=m.useMemo(()=>mge(t,r),[t,r]),C=i||o||!e||!p.length||!v.length,w=m.useCallback(async()=>{if(!C)try{if(!await f(v))return;b("download",{datasourceId:n??void 0}),y({content:"You will receive an email with a link to a CSV file when your file is completed.",severity:"success",timeout:1e4})}catch(E){We(E),y({content:"Failed to start the data export. Please try again.",severity:"error"})}},[n,C,v,b,y,f]),S=a.jsx(T,{sx:{display:"flex",justifyContent:"center",mt:.5},children:a.jsx(Ze,{color:"inherit",size:30})});return a.jsxs(T,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between",mb:2},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:2},children:[a.jsx(uge,{columnDefinitions:t,columnVisibilityModel:r,disabled:i||!e,onSelect:l}),x&&a.jsx(sn,{control:a.jsx(Dn,{checked:g,"data-testid":"data-verification:adjust-toggle:switch",id:"data-verification-adjust-toggle",onCh
216ange:E=>{b("toggleAdjustValues",{enabled:E.target.checked}),u(E.target.checked)},size:"small"}),label:"Adjust Values",sx:{ml:1}}),(s||h)&&a.jsx(re,{"data-testid":"data-verification:confirm-edits:button",id:"data-verification-confirm-edits-button",onClick:c,sx:{height:38,width:96},variant:"contained",children:h?S:"CONFIRM"})]}),a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:2},children:[a.jsx(re,{color:"secondary","data-testid":"data-verification:download:button",disabled:C,id:"data-verification-download-button",onClick:w,startIcon:o?a.jsx(Ze,{color:"inherit",size:16}):a.jsx(SR,{}),variant:"outlined",children:"Download"}),a.jsx(hge,{disabled:i,onSearchSubmit:d})]})]})},xge=({dataSource:e,endDate:t,startDate:n,userCanEdit:r})=>{const{alerts:s,fetchVerificationData:i,setVerificationTableState:o,validationDataSources:l,verificationTableState:c}=zl(),{editedRows:d,gridParams:u,hasLoaded:p,isLoadingTable:h,rowCount:f,rows:g}=c,{engagementNiceId:x}=pe(),{userIsInternal:b}=gt(),[y]=gu(),[v]=zV(),C=Bl(),[w,S]=m.useState(age),[E,k]=m.useState(!1),[j,_]=m.useState(!1),[D,M]=m.useState(!1),N=m.useMemo(()=>({...w,adjusted_impressions:j,adjusted_investment:j}),[w,j]),O=m.useMemo(()=>{if(!r)return!0;if(b||!g.length||!e||!n||!t)return!1;const K=s.filter(({datasource_id:le,type:ce,approved:J,start_date:he,end_date:ne})=>e===le&&ce==="verification"&&J!==!0&&Z(he)<=n&&n<=Z(ne)).map(({end_date:le})=>Z(le));if(!K.length)return!0;const ie=K.reduce((le,ce)=>ce.isAfter(le)?ce:le);return t.isAfter(ie)},[s,e,t,g.length,n,r,b]),R=m.useCallback(()=>{!e||!n||!t||i(e,n.format("YYYY-MM-DD"),t.format("YYYY-MM-DD"),u)},[e,t,i,u,n]),L=m.useCallback(K=>{if(S(K),p&&e&&n&&t){const ie={...K,adjusted_impressions:j,adjusted_investment:j},le=fge(ie),ce={...u,columns:le,currentPage:0};o({gridParams:ce}),i(e,n.format("YYYY-MM-DD"),t.format("YYYY-MM-DD"),ce)}},[e,t,i,u,p,o,n,j]),P=m.useCallback(K=>{const ie={...u,sortModel:K};o({gridParams:ie}),p&&e&&n&&t&&i(e,n.format("YYYY-MM-DD"),t.format("YYYY-MM-DD"),ie)},[e,t,i,u,p,o,n]),F=m.useCallback(K=>{const ie={...u,currentPage:0,filterModel:K};o({gridParams:ie}),p&&e&&n&&t&&i(e,n.format("YYYY-MM-DD"),t.format("YYYY-MM-DD"),ie)},[e,t,i,u,p,o,n]),z=m.useCallback(K=>{const ie=K.page!==u.currentPage,le=K.pageSize!==u.rowLimit;if(ie||le){const ce={...u,currentPage:K.page,rowLimit:K.pageSize};o({gridParams:ce}),p&&e&&n&&t&&i(e,n.format("YYYY-MM-DD"),t.format("YYYY-MM-DD"),ce)}},[e,t,i,u,p,o,n]),B=m.useCallback(K=>{const ie={...u,currentPage:0,searchText:K};o({gridParams:ie}),p&&e&&n&&t&&i(e,n.format("YYYY-MM-DD"),t.format("YYYY-MM-DD"),ie)},[e,t,i,u,p,o,n]),W=Object.keys(d).length>0,H=!!(p&&e&&n&&t&&!W),V=m.useCallback(async K=>{if(!H||!e||!n||!t||!K.length)return!1;M(!0);try{return await v(Jme({dataSource:e,endDate:t,engagementNiceId:x,exportColumns:K,gridParams:u,startDate:n})).unwrap(),!0}finally{M(!1)}},[H,e,t,x,v,u,n]),G=m.useCallback((K,ie)=>{const le=he=>"adjusted_investment"in he&&"adjusted_impressions"in he&&"id"in he;if(!le(K)||!le(ie)||!(K.adjusted_investment!==ie.adjusted_investment||K.adjusted_impressions!==ie.adjusted_impressions))return ie;const J={...K};return(typeof K.adjusted_investment!="number"||K.adjusted_investment<0)&&(J.adjusted_investment=ie.adjusted_investment),(typeof K.adjusted_impressions!="number"||K.adjusted_impressions<0)&&(J.adjusted_impressions=ie.adjusted_impressions),o({editedRows:{...d,[J.id]:J}}),J},[d,o]),X=m.useCallback(async()=>{C("confirmEdits",{datasourceId:e??void 0,editCount:Object.keys(d).length}),k(!0);try{const K=l.find(({id:ne})=>ne===e);if(!K||!n||!t)return;const ie=`${K.vendor_nice_id}_${K.content_type}_${K.feed_nice_id}`.toLowerCase(),le=Object.values(d).map(async ne=>{const Y={},ae=g.find(me=>me.id===ne.id);if(ne.adjusted_impressions!==ae?.adjusted_impressions&&typeof ne.adjusted_impressions=="number"&&(Y.impressions=ne.adjusted_impressions),ne.adjusted_investment!==ae?.adjusted_investment&&typeof ne.adjusted_investment=="number"&&(Y.cost=ne.adjusted_investment),Object.keys(Y).length===0)return Promise.resolve();const je=Object.entries(ne).reduce((me,[ve,Me])=>(!M2.includes(ve)&&N[ve]&&(me[ve]=Me),me),{});return y({apiName:"reporting",endpoint:"verificationAdjustment",parameters:{body:{conditions:je,datasource_id:e,datasource_name:ie,end_date:t.format("YYYY-MM-DD"),start_date:n.format("YYYY-MM-DD"),values:Y},pathParameters:x}}).unwrap()}),ce=await Promise.allSettled(le),J=new Set;let he=0;if(ce.forEach((ne,Y)=>{const ae=Object.values(d)[Y];ne.status==="fulfilled"?ae&&J.add(ae.id):(he+=1,We(ne.reason))}),J.size>0){const ne=Object.fromEntries(Object.entries(d).filter(([,Y])=>!J.has(Y.id)));o({editedRows:ne}),R()}he>0&&We(`${he} row(s) failed to save in verificationAdjustment`)}finally{k(!1)}},[y,e,R,d,N,t,x,C,g,o,n,l]);return{columnVisibilityModel:w,canExport:H,editDisabled:O,editedRows:d,effectiveColumnVisibility:N,gridParams:u,handleColumnVisibilityChange:L,handleFilterModelChange:F,handlePaginationModelChange:z,handleSaveEdits:X,handleSearchSubmit:B,handleSortModelChange:P,hasEdits:W,isLoading:h,isSubmittingExport:D,processRowUpdate:G,rowCount:f,rows:g,savingEdits:E,setToggleEnabled:_,submitExportRequest:V,toggleEnabled:j,validationDataSources:l}},bge=({dataSource:e,endDate:t,startDate:n,userCanEdit:r})=>{const s=zn(),{canExport:i,editDisabled:o,editedRows:l,effectiveColumnVisibility:c,gridParams:d,handleColumnVisibilityChange:u,handleFilterModelChange:p,handlePaginationModelChange:h,handleSaveEdits:f,handleSearchSubmit:g,handleSortModelChange:x,hasEdits:b,isLoading:y,isSubmittingExport:v,processRowUpdate:C,rowCount:w,rows:S,savingEdits:E,setToggleEnabled:k,submitExportRequest:j,toggleEnabled:_}=xge({dataSource:e,endDate:t,startDate:n,userCanEdit:r}),D=m.useMemo(()=>dge(o),[o]),M=m.useCallback(N=>{if(y)return"hide-row";const O=String(N.row.id);return l[O]?"edited-row":""},[l,y]);return a.jsxs(a.Fragment,{children:[a.jsx(gge,{canExport:i,columns:D,dataSource:e,effectiveColumnVisibility:c,hasEdits:b,isLoading:y,isSubmittingExport:v,onColumnVisibilityChange:u,onSaveEdits:f,onSearchSubmit:g,onToggleChange:k,rows:S,savingEdits:E,submitExportRequest:j,toggleEnabled:_,userCanEdit:r}),a.jsx(T,{sx:{height:800,width:"100%"},children:a.jsx(R2,{apiRef:s,columnHeaderHeight:40,columns:D,columnVisibilityModel:c,disableColumnPinning:!0,disableColumnSelector:!0,editMode:"row",filterModel:d.filterModel,filterMode:"server",getRowClassName:M,loading:y,onFilterModelChange:p,onPaginationModelChange:h,onSortModelChange:x,pageSizeOptions:sge,pagination:!0,paginationModel:{page:d.currentPage,pageSize:d.rowLimit},paginationMode:"server",processRowUpdate:C,rowCount:w,rowHeight:40,rows:S,sortingMode:"server",sortModel:d.sortModel})})]})},yge=({clicks:e,impressions:t,loading:n=!1,spend:r})=>{const s=i=>
216i.toLocaleString("en-US",{maximumFractionDigits:0,minimumFractionDigits:0});return n?a.jsx(T,{sx:{display:"flex",gap:2,mb:3,width:"100%"},children:[1,2,3].map(i=>a.jsx(Ve,{sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(fe,{height:20,width:"60%"}),a.jsx(fe,{height:32,width:"80%",sx:{mt:1}})]})},i))}):a.jsxs(T,{sx:{display:"flex",gap:2,mb:3,width:"100%"},children:[a.jsx(Ve,{"data-testid":"data-verification:kpi:spend",sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:14,fontWeight:500},children:"Total Spend"}),a.jsxs($,{direction:"row",sx:{alignItems:"center",mt:.5},children:[a.jsx(Dl,{sx:{color:"text.primary",fontSize:28}}),a.jsx(I,{sx:{fontSize:28,fontWeight:600},children:s(r)})]})]})}),a.jsx(Ve,{"data-testid":"data-verification:kpi:impressions",sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:14,fontWeight:500},children:"Total Impressions"}),a.jsx(I,{sx:{fontSize:28,fontWeight:600,mt:.5},children:s(t)})]})}),a.jsx(Ve,{"data-testid":"data-verification:kpi:clicks",sx:{flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:14,fontWeight:500},children:"Total Clicks"}),a.jsx(I,{sx:{fontSize:28,fontWeight:600,mt:.5},children:s(e)})]})})]})},Q_=(e,t)=>{const n=e?Z(e):Z(),r=t?Z(t):Z(),s=r.subtract(3,"month");return[n>s?n:s,r]},vge=()=>{const{dataSourcesLoading:e,fetchChartData:t,fetchVerificationData:n,metadataByDatasource:r,metadataList:s,metadataLoading:i,setVerificationTableState:o,verificationTableState:l}=zl(),{engagementCountry:c}=pe(),d=yn({authorized:"DataPipeline.DataValidation.EditData"}),u=Bl(),{chartData:p,dataSource:h,endDate:f,gridParams:g,hasLoaded:x,isLoadingChart:b,kpiData:y,startDate:v}=l,C=m.useRef(null),[w,S]=m.useMemo(()=>{if(!h)return[null,null];const O=r.get(h);return O?[O.min_date?Z(O.min_date):null,O.max_date?Z(O.max_date):null]:[null,null]},[h,r]),E=v&&f&&v.isValid()&&f.isValid()&&f>=v,k=x,j=m.useRef(!1);m.useEffect(()=>{if(j.current||i||!s.length||x||h!==null)return;const O=s[0];if(!O)return;j.current=!0;const[R,L]=Q_(O.min_date,O.max_date),P=R.format("YYYY-MM-DD"),F=L.format("YYYY-MM-DD");o({dataSource:O.datasource_id,endDate:L,startDate:R}),C.current={dsId:O.datasource_id,end:F,start:P},t(O.datasource_id,P,F),n(O.datasource_id,P,F,g)},[h,t,n,g,x,s,i,o]);const _=m.useCallback(O=>{const R=O?r.get(O):void 0,L=R?Q_(R.min_date,R.max_date):[null,null];
216o({dataSource:O,endDate:L[1],hasLoaded:!1,startDate:L[0]}),C.current=null},[r,o]),D=m.useCallback(O=>{o({endDate:O[1],hasLoaded:!1,startDate:O[0]}),C.current=null},[o]),M=m.useCallback(()=>{if(!h||!E||!v||!f)return;const O=v.format("YYYY-MM-DD"),R=f.format("YYYY-MM-DD");u("submit",{datasourceId:h,endDate:R,startDate:O});const L={dsId:h,end:R,start:O},P=C.current;(!P||P.dsId!==L.dsId||P.start!==L.start||P.end!==L.end)&&(C.current=L,t(h,O,R)),n(h,O,R,g)},[h,f,t,n,g,E,u,v]),N=e||i;return a.jsxs(T,{sx:{mb:7.5},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",mb:3.125,mt:4.375},children:[a.jsx(Zme,{dataSource:h,loadingDataSources:N,setDataSource:_}),a.jsx(T,{sx:{ml:2.5},children:N?a.jsx(fe,{height:40,sx:{width:260},variant:"rounded"}):a.jsx(ts,{disabled:!h,locale:c,maxDate:S??void 0,minDate:w??void 0,setValue:D,value:[v,f]})}),a.jsx(Dt,{color:"primary","data-testid":"data-verification:submit:button",disabled:!h||!E||k,id:"data-verification-table-submit",loading:b,onClick:M,sx:{height:40,ml:5,width:84},variant:"contained",children:"Submit"})]}),a.jsx(yge,{clicks:y.clicks,impressions:y.impressions,loading:b,spend:y.spend}),a.jsx(rge,{data:p,loading:b}),a.jsx(bge,{dataSource:h,endDate:f,startDate:v,userCanEdit:d}),a.jsx(mt,{acceptLabel:"Abandon Edits",bodyText:"This will refresh the table and lose any unsaved edits.",handleAccept:()=>{},handleClose:()=>{},open:!1,title:"Are you sure?"})]})},Cge=()=>a.jsx(T,{children:a.jsx(vge,{})}),wge=({alert:e,value:t})=>{const{palette:n}=Re(),[r]=FA(),s=Bl(),[i,o]=m.useState(null),l=m.useRef(!1),c=l.current?i??"":t||"",d=fs(r,500),u=m.useCallback(()=>{l.current=!0,o(t||"")},[t]),p=m.useCallback(()=>{if(l.current=!1,i!==null&&i!==(e.notes??"")){s("updateNotes",{datasourceId:e.datasource_id,timestamp:e.timestamp});const f={client_nice_id:e.client_nice_id,datasource:e.datasource,engagement_nice_id:e.engagement_nice_id,id:e.id,notes:i,timestamp:e.timestamp};d(f)}o(null)},[e.client_nice_id,e.datasource,e.datasource_id,e.engagement_nice_id,e.id,e.notes,e.timestamp,d,i,s]),h=m.useCallback(f=>{o(f.target.value)},[]);return a.jsx(Uv,{disableUnderline:!0,fullWidth:!0,multiline:!0,name:"notes-input",onBlur:p,onChange:h,onFocus:u,placeholder:"Notes",rows:2,sx:{border:`solid 1px ${n.divider}`,fontSize:12,height:"calc(100% - 5px)",overflow:"hidden",padding:0},title:t||"",value:c})},eb={alignItems:"center",display:"flex",height:24,justifyContent:"center",width:24},Sge=({alerts:e,loading:t,onAlertClick:n})=>{const r=zn(),s=ct(),i=m.useMemo(()=>t?[]:e.toSorted((L,P)=>P.timestamp.localeCompare(L.timestamp)),[e,t]),{clientNiceId:o}=pe(),{userEmail:l,userFamilyName:c,userGivenName:d,userIsInternal:u}=gt(),p=yn({authorized:"DataPipeline.DataValidation.ApproveAlert"}),[h]=FA(),[f]=BV(),g=Bl(),[x,b]=m.useState(null),[y,v]=m.useState(null),[C,w]=m.useState(null),[S,E]=m.useState(""),k=m.useCallback(async L=>{try{await h(L)}finally{s()&&b(null)}},[h,s]),j=m.useCallback(async()=>{if(C){g("deleteAlert",{timestamp:C.timestamp}),v(C.timestamp),E("");try{await f(C),w(null)}catch{E("Failed to delete alert. Please try again.")}finally{s()&&v(null)}}},[f,s,g,C]),_=fs(j,500),D=fs(k,500),M=m.useMemo(()=>a.jsx(T,{sx:eb,children:a.jsx(Ze,{size:20,sx:{mt:.625}})}),[]),N=m.useMemo(()=>[{align:"left",field:"timestamp",headerAlign:"left",headerName:"Alert Sent On",type:"dateTime",valueFormatter:L=>typeof L.value=="string"?Z(L.value).format("M/D/YY h:mm A"):"",width:140},{align:"left",field:"datasource_id",headerAlign:"left",headerName:"Data Source ID",type:"number",width:68},{align:"left",field:"datasource",headerAlign:"left",headerName:"Data Source Name",type:"string",width:255},{align:"left",field:"start_date",headerAlign:"left",headerName:"Start Date",type:"date",valueFormatter:L=>typeof L.value=="string"?Z(L.value).format("M/D/YY"):"",width:97},{align:"left",field:"end_date",headerAlign:"left",headerName:"End Date",type:"date",valueFormatter:L=>typeof L.value=="string"?Z(L.value).format("M/D/YY"):"",width:90},{align:"left",field:"approver_name",headerAlign:"left",headerName:"Approver",type:"string",width:200},{align:"left",field:"notes",headerAlign:"left",headerName:"Notes (Optional)",renderCell:L=>a.jsx(wge,{alert:L.row,value:L.value||null}),type:"string",width:320},{align:"left",field:"approved_on",headerAlign:"left",headerName:"Approved On",type:"dateTime",valueFormatter:L=>L.value&&typeof L.value=="string"?Z(L.value).format("M/D/YY h:mm A"):"",width:160},{field:"actions",getActions:({row:L})=>{const{approved:P,approver_email:F,datasource:z,engagement_nice_id:B,id:W,timestamp:H}=L,V=p||F===l,G=!!P,X=[],K=a.jsx(Dj,{disabled:!V||G||!!x||!!y,icon:x===H?M:a.jsx(T,{sx:eb,children:a.jsx(et,{checked:G,disabled:!V||G})}),label:"Approve alert",onClick:()=>{b(H),g("approveAlert",{datasourceId:L.datasource_id,timestamp:H});const le={approved:!0,approver_email:l,approver_name:`${d} ${c}`,client_nice_id:o,datasource:z,engagement_nice_id:B,id:W,timestamp:H};D(le)}}),ie=a.jsx(Dj,{disabled:!!x||!!y,icon:y===H?M:a.jsx(T,{sx:eb,children:a.jsx(Xr,{size:20})}),label:"Delete alert",onClick:()=>{w({client_nice_id:o,timestamp:H})}});return X.push(K),u&&X.push(ie),X},headerName:"Actions",type:"actions"}],[x,y,p,l,d,c,o,u,D,g,M]),O=m.useCallback(()=>a.jsx(Cs,{rowHeight:40}),[]),R=m.useCallback(L=>{if(L.row.approved)return;const{datasource_id:P,start_date:F,end_date:z}=L.row;n(P,F,z)},[n]);return a.jsxs(a.Fragment,{children:[a.jsx(T,{sx:{width:"100%"},children:a.jsx(R2,{apiRef:r,autoHeight:!0,columnHeaderHeight:40,columns:N,disableColumnPinning:!0,disableColumnSelector:!0,getRowId:L=>L.timestamp,hideFooter:!0,loading:t,onCellKeyDown:(L,P)=>{Object.defineProperty(P,"defaultMuiPrevented",{value:!0,writable:!1})},onRowClick:R,rowHeight:40,rows:i,getRowClassName:L=>L.row.approved?"row-approved":"row-clickable",slots:{loadingOverlay:O},sx:{"& .row-clickable":{cursor:"pointer"},"& .row-approved":{cursor:"default"}}})}),a.jsx(eg,{deleting:!!y,errorMessage:S,onClose:()=>{w(null),E("")},onDelete:_,open:!!C,resourceName:"this alert",resourceType:"Alert"})]})},jge=({onAlertClick:e})=>{const{alerts:t,alertsLoading:n}=zl();return a.jsx(T,{children:a.jsx(Sge,{alerts:t,loading:n,onAlertClick:e})})}
216,cd={data:{label:"Data",value:"0",authorized:"DataPipeline.DataValidation"},alerts:{label:"Alerts",value:"1",authorized:"DataPipeline.DataValidation"}},kge=Object.values(cd),Ege=()=>{const{alertsLoading:e,loadDataForAlert:t,onCreateAlert:n}=zl(),r=Bl(),[s,i]=m.useState(cd.data.value),[o,l]=m.useState(!1),c=m.useCallback(p=>{r("changeTab",{tab:p}),i(p)},[r]),d=m.useCallback((p,h,f,g)=>{r("createAlert",{datasourceId:f,endDate:h,hasContact:!!g,startDate:p}),l(!1),n(p,h,f,g)},[r,n]),u=m.useCallback((p,h,f)=>{t(p,h,f),i(cd.data.value)},[t]);return a.jsxs($,{"data-testid":"data-verification:page:container",sx:{minWidth:600,rowGap:4,width:"100%"},children:[a.jsxs(T,{sx:{alignItems:"flex-start",display:"flex",justifyContent:"space-between"},children:[a.jsxs($,{sx:{rowGap:1},children:[a.jsx(Xt,{title:"Data Validation"}),a.jsx(I,{sx:{color:"text.secondary",fontSize:14},children:"Review, adjust, and send alerts for your data verification"})]}),a.jsx(ar,{authorized:"DataPipeline.DataValidation.CreateAlert",children:a.jsx(re,{color:"primary","data-testid":"data-verification:create-alert:button",id:"create-alert-button",onClick:()=>l(!0),variant:"contained",children:"Create Alert"})})]}),a.jsxs(fo,{onChange:c,tabs:kge,testId:"data-verification:tab",value:s,children:[a.jsx(xt,{sx:{p:0,pt:4},value:cd.data.value,children:a.jsx(Cge,{})}),a.jsx(xt,{sx:{p:0,pt:4},value:cd.alerts.value,children:a.jsx(jge,{onAlertClick:u})})]}),a.jsx(Xme,{loading:e,onClose:()=>l(!1),onConfirm:d,open:o})]})},_ge=["gl_type_name","gl_vehicle_name"],Tge={columns:_ge,currentPage:0,filterModel:{items:[]},rowLimit:ige,searchText:"",sortModel:[]},N2={clicks:0,impressions:0,spend:0},Ige={chartData:[],dataSource:null,editedRows:{},endDate:null,gridParams:Tge,hasLoaded:!1,isLoadingChart:!1,isLoadingTable:!1,kpiData:N2,rowCount:0,rows:[],startDate:null},Dge=({alerts:e,alertsLoading:t,dataSources:n,dataSourcesLoading:r,metadataList:s,metadataLoading:i,onCreateAlert:o})=>{const{engagementNiceId:l}=pe(),[c]=gu(),[d,u]=m.useState(Ige),p=m.useRef(d);p.current=d;const h=m.useRef(null),f=m.useRef(null),g=m.useMemo(()=>n.filter(({active:S})=>S).sort((S,E)=>S.id-E.id),[n]),x=m.useMemo(()=>{const S=new Map;return s.forEach(E=>{S.set(E.datasource_id,E)}),S},[s]),b=m.useCallback(S=>{u(E=>{const k={...E,...S};return p.current=k,k})},[]),y=m.useCallback(async(S,E,k)=>{const j=`${S}-${E}-${k}`;h.current=j,b({isLoadingChart:!0});try{const _={columns:["start_date"],datasource_id:S,end_date:k,limit:1e4,offset:0,start_date:E},{rows:D}=await c({apiName:"reporting",endpoint:"getVerificationData",parameters:{body:_,pathParameters:l}}).unwrap();if(h.current!==j)return;let M=0,N=0,O=0;const R={};(D||[]).forEach(P=>{const F=P.start_date;if(!F)return;R[F]||(R[F]={impressions:0,spend:0});const z=Number(P.total_investment)||0,B=Number(P.total_impressions)||0,W=Number(P.clicks)||0;R[F].spend+=z,R[F].impressions+=B,M+=z,N+=B,O+=W});const L=Object.entries(R).map(([P,F])=>({date:P,impressions:F.impressions,spend:F.spend}));b({chartData:L,isLoadingChart:!1,kpiData:{clicks:O,impressions:N,spend:M}})}catch{h.current===j&&b({isLoadingChart:!1})}},[c,l,b]),v=m.useCallback(async(S,E,k,j)=>{const _=`${S}-${E}-${k}-${j.currentPage}-${j.rowLimit}-${j.searchText}-${JSON.stringify(j.sortModel)}-${JSON.stringify(j.filterModel)}`;f.current=_,b({isLoadingTable:!0});try{const D={...T2(j),datasource_id:S,end_date:k,limit:j.rowLimit,offset:j.currentPage*j.rowLimit,start_date:E},{rows:M,total:N}=await c({apiName:"reporting",endpoint:"getVerificationData",parameters:{body:D,pathParameters:l}}).unwrap();f.current===_&&b({editedRows:{},hasLoaded:!0,isLoadingTable:!1,rowCount:N||0,rows:M||[]})}catch{f.current===_&&b({hasLoaded:!1,isLoadingTable:!1})}},[c,l,b]),C=m.useCallback((S,E,k)=>{const j=Number(S);u(_=>{const D={..._,chartData:[],dataSource:j,editedRows:{},endDate:Z(k),hasLoaded:!1,isLoadingChart:!0,isLoadingTable:!0,kpiData:N2,rowCount:0,rows:[],startDate:Z(E)};return p.current=D,D}),y(j,E,k),v(j,E,k,p.current.gridParams)},[y,v]),w=m.useMemo(()=>({alerts:e,alertsLoading:t,dataSources:n,dataSourcesLoading:r,fetchChartData:y,fetchVerificationData:v,loadDataForAlert:C,metadataByDatasource:x,metadataList:s,metadataLoading:i,onCreateAlert:o,setVerificationTableState:b,validationDataSources:g,verificationTableState:d}),[e,t,n,r,y,v,C,x,s,i,o,b,d,g]);return a.jsx(k2.Provider,{value:w,children:a.jsx(Ege,{})})},Age=()=>{const{userIsInternal:e}=gt(),{clientNiceId:t,engagementNiceId:n}=pe(),[r]=UV(),{verificationAlerts:s,alertsLoading:i,dataSources:o,dataSourcesFetching:l}=MC({clientNiceId:t,engagementNiceId:n,userIsInternal:e}),{data:c=[],isFetching:d}=$A({engagementNiceId:n},{skip:!n}),u=o.filter(({active:h})=>h).sort((h,f)=>h.id-f.id),p=m.useCallback((h,f,g,x)=>{const b=u.find(({id:C})=>C===g);if(!b)return;
216const y=`${b.vendor_nice_id}_${b.content_type}_${b.feed_nice_id}`.toLowerCase(),v={client_nice_id:t,datasource:y,datasource_id:g,end_date:f,engagement_nice_id:n,notes:null,start_date:h,type:"verification"};x&&(v.recipient_email=x.email,v.recipient_name=x.name),r(v)},[t,r,n,u]);return a.jsx(Dge,{alerts:s,alertsLoading:i,dataSources:o,dataSourcesLoading:l,metadataList:c,metadataLoading:d,onCreateAlert:p})},Mge=(e,t)=>{switch(t.type){case"addFile":return{...e,uploadedFiles:[...e.uploadedFiles,t.value]};case"clearFiles":return{...e,uploadedFiles:[]};case"setActiveTab":return{...e,activeTab:t.value};case"setUploadingFileName":return{...e,uploadingFileName:t.value};case"setDownloadingFileId":return{...e,downloadingFileId:t.value};case"setIsConfirming":return{...e,isConfirming:t.value};case"setDeletingFileId":return{...e,deletingFileId:t.value};case"setDeleteModalOpen":return{...e,deleteModalOpen:t.value};case"setDeleteError":return{...e,deleteError:t.value};case"setFileToDelete":return{...e,fileToDelete:t.value};default:return e}},O2=m.createContext(void 0),Rge={activeTab:0,deleteError:null,deleteModalOpen:!1,deletingFileId:null,downloadingFileId:null,fileToDelete:null,isConfirming:!1,uploadedFiles:[],uploadingFileName:""},Nge=({children:e,clientNiceId:t,dataSourceOptions:n,engagementId:r,engagementNiceId:s,fileMetadataResponse:i,isLoadingMetadata:o,previewData:l,refetchMetadata:c,onGetS3DownloadUrl:d,onGetS3FileMetadataByInputUri:u,onTriggerPreview:p})=>{const[h,f]=m.useReducer(Mge,Rge),g=m.useMemo(()=>({clientNiceId:t,dataSourceOptions:n,dispatch:f,engagementId:r,engagementNiceId:s,fileMetadataResponse:i,isLoadingMetadata:o,onGetS3DownloadUrl:d,onGetS3FileMetadataByInputUri:u,onTriggerPreview:p,previewData:l,refetchMetadata:c,state:h}),[t,n,r,s,i,o,d,u,p,l,c,h]);return a.jsx(O2.Provider,{value:g,children:e})},mg=()=>{const e=m.useContext(O2);if(!e)throw new Error("useFileUploadUIContext must be used within FileUploadUIProvider");return e},Oge=({children:e,clientNiceId:t,dataSourceOptions:n,engagementId:r,engagementNiceId:s,fileMetadataResponse:i,isLoadingMetadata:o,previewData:l,refetchMetadata:c,onGetS3DownloadUrl:d,onGetS3FileMetadataByInputUri:u,onTriggerPreview:p})=>a.jsx(Nge,{clientNiceId:t,dataSourceOptions:n,engagementId:r,engagementNiceId:s,fileMetadataResponse:i,isLoadingMetadata:o,previewData:l,refetchMetadata:c,onGetS3DownloadUrl:d,onGetS3FileMetadataByInputUri:u,onTriggerPreview:p,children:e});var Pge=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Uu(e,t){var n=Lge(e);if(typeof n.path!="string"){var r=e.webkitRelativePath;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof r=="string"&&r.length>
2160?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function Lge(e){var t=e.name,n=t&&t.lastIndexOf(".")!==-1;if(n&&!e.type){var r=t.split(".").pop().toLowerCase(),s=Pge.get(r);s&&Object.defineProperty(e,"type",{value:s,writable:!1,configurable:!1,enumerable:!0})}return e}var Fge=[".DS_Store","Thumbs.db"];function $ge(e){return jl(this,void 0,void 0,function(){return kl(this,function(t){return nm(e)&&zge(e.dataTransfer)?[2,Wge(e.dataTransfer,e.type)]:Bge(e)?[2,Uge(e)]:Array.isArray(e)&&e.every(function(n){return"getFile"in n&&typeof n.getFile=="function"})?[2,Vge(e)]:[2,[]]})})}function zge(e){return nm(e)}function Bge(e){return nm(e)&&nm(e.target)}function nm(e){return typeof e=="object"&&e!==null}function Uge(e){return sv(e.target.files).map(function(t){return Uu(t)})}function Vge(e){return jl(this,void 0,void 0,function(){var t;return kl(this,function(n){switch(n.label){case 0:return[4,Promise.all(e.map(function(r){return r.getFile()}))];case 1:return t=n.sent(),[2,t.map(function(r){return Uu(r)})]}})})}function Wge(e,t){return jl(this,void 0,void 0,function(){var n,r;return kl(this,function(s){switch(s.label){case 0:return e.items?(n=sv(e.items).filter(function(i){return i.kind==="file"}),t!=="drop"?[2,n]:[4,Promise.all(n.map(Hge))]):[3,2];case 1:return r=s.sent(),[2,J_(P2(r))];case 2:return[2,J_(sv(e.files).map(function(i){return Uu(i)}))]}})})}function J_(e){return e.filter(function(t){return Fge.indexOf(t.name)===-1})}function sv(e){if(e===null)return[];for(var t=[],n=0;n<e.length;n++){var r=e[n];t.push(r)}return t}function Hge(e){if(typeof e.webkitGetAsEntry!="function")return X_(e);var t=e.webkitGetAsEntry();return t&&t.isDirectory?L2(t):X_(e)}function P2(e){return e.reduce(function(t,n){return Ej(Ej([],_j(t),!1),_j(Array.isArray(n)?P2(n):[n]),!1)},[])}function X_(e){var t=e.getAsFile();if(!t)return Promise.reject("".concat(e," is not a File"));var n=Uu(t);return Promise.resolve(n)}function qge(e){return jl(this,void 0,void 0,function(){return kl(this,function(t){return[2,e.isDirectory?L2(e):Gge(e)]})})}function L2(e){var t=e.createReader();return new Promise(function(n,r){var s=[];function i(){var o=this;t.readEntries(function(l){return jl(o,void 0,void 0,function(){var c,d,u;return kl(this,function(p){switch(p.label){case 0:if(l.length)return[3,5];p.label=1;case 1:return p.trys.push([1,3,,4]),[4,Promise.all(s)];case 2:return c=p.sent(),n(c),[3,4];case 3:return d=p.sent(),r(d),[3,4];case 4:return[3,6];case 5:u=Promise.all(l.map(qge)),s.push(u),i(),p.label=6;case 6:return[2]}})})},function(l){r(l)})}i()})}function Gge(e){return jl(this,void 0,void 0,function(){return kl(this,function(t){return[2,new Promise(function(n,r){e.file(function(s){var i=Uu(s,e.fullPath);n(i)},function(s){r(s)})})]})})}var Mp={},Z_;function Yge(){return Z_||(Z_=1,Mp.__esModule=!0,Mp.default=function(e,t){if(e&&t){var n=Array.isArray(t)?t:t.split(","),r=e.name||"",s=(e.type||"").toLowerCase(),i=s.replace(/\/.*$/,"");return n.some(function(o){var l=o.trim().toLowerCase();return l.charAt(0)==="."?r.toLowerCase().endsWith(l):l.endsWith("/*")?i===l.replace(/\/.*$/,""):s===l})}return!0}),Mp}var Kge=Yge();const Qge=dt(Kge);function eT(e){return Zge(e)||Xge(e)||$2(e)||Jge()}function Jge(){throw new TypeError(`Invalid attempt to spread non-iterable instance. 217In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Xge(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Zge(e){if(Array.isArray(e))return iv(e)}function tT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function nT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?tT(Object(n),!0).forEach(function(r){F2(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):tT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function F2(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zd(e,t){return nxe(e)||txe(e,t)||$2(e,t)||exe()}
217function exe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 218In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function $2(e,t){if(e){if(typeof e=="string")return iv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return iv(e,t)}}function iv(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function txe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r=[],s=!0,i=!1,o,l;try{for(n=n.call(e);!(s=(o=n.next()).done)&&(r.push(o.value),!(t&&r.length===t));s=!0);}catch(c){i=!0,l=c}finally{try{!s&&n.return!=null&&n.return()}finally{if(i)throw l}}return r}}function nxe(e){if(Array.isArray(e))return e}var rxe="file-invalid-type",sxe="file-too-large",ixe="file-too-small",axe="too-many-files",oxe=function(t){t=Array.isArray(t)&&t.length===1?t[0]:t;var n=Array.isArray(t)?"one of ".concat(t.join(", ")):t;return{code:rxe,message:"File type must be ".concat(n)}},rT=function(t){return{code:sxe,message:"File is larger than ".concat(t," ").concat(t===1?"byte":"bytes")}},sT=function(t){return{code:ixe,message:"File is smaller than ".concat(t," ").concat(t===1?"byte":"bytes")}},lxe={code:axe,message:"Too many files"};function z2(e,t){var n=e.type==="application/x-moz-file"||Qge(e,t);return[n,n?null:oxe(t)]}function B2(e,t,n){if(Ma(e.size))if(Ma(t)&&Ma(n)){if(e.size>n)return[!1,rT(n)];if(e.size<t)return[!1,sT(t)]}else{if(Ma(t)&&e.size<t)return[!1,sT(t)];if(Ma(n)&&e.size>n)return[!1,rT(n)]}return[!0,null]}function Ma(e){return e!=null}function cxe(e){var t=e.files,n=e.accept,r=e.minSize,s=e.maxSize,i=e.multiple,o=e.maxFiles,l=e.validator;return!i&&t.length>1||i&&o>=1&&t.length>o?!1:t.every(function(c){var d=z2(c,n),u=Zd(d,1),p=u[0],h=B2(c,r,s),f=Zd(h,1),g=f[0],x=l?l(c):null;return p&&g&&!x})}function rm(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function Rp(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,function(t){return t==="Files"||t==="application/x-moz-file"}):!!e.target&&!!e.target.files}function iT(e){e.preventDefault()}function dxe(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function uxe(e){return e.indexOf("Edge/")!==-1}function pxe(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return dxe(e)||uxe(e)}function Is(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){for(var s=arguments.length,i=new Array(s>1?s-1:0),o=1;o<s;o++)i[o-1]=arguments[o];return t.some(function(l){return!rm(r)&&l&&l.apply(void 0,[r].concat(i)),rm(r)})}}function hxe(){return"showOpenFilePicker"in window}function fxe(e){if(Ma(e)){var t=Object.entries(e).filter(function(n){var r=Zd(n,2),s=r[0],i=r[1],o=!0;return U2(s)||(console.warn('Skipped "'.concat(s,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),o=!1),(!Array.isArray(i)||!i.every(V2))&&(console.warn('Skipped "'.concat(s,'" because an invalid file extension was provided.')),o=!1),o}).reduce(function(n,r){var s=Zd(r,2),i=s[0],o=s[1];return nT(nT({},n),{},F2({},i,o))},{});return[{description:"Files",accept:t}]}return e}function mxe(e){if(Ma(e))return Object.entries(e).reduce(function(t,n){var r=Zd(n,2),s=r[0],i=r[1];return[].concat(eT(t),[s],eT(i))},[]).filter(function(t){return U2(t)||V2(t)}).join(",")}function gxe(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function xxe(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function U2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function V2(e){return/^.*\.[\w]+$/.test(e)}var bxe=["children"],yxe=["open"],vxe=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],Cxe=["refKey","onChange","onClick"];function wxe(e){return kxe(e)||jxe(e)||W2(e)||Sxe()}function Sxe(){throw new TypeError(`Invalid attempt to spread non-iterable instance. 219In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jxe(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function kxe(e){if(Array.isArray(e))return av(e)}function tb(e,t){return Txe(e)||_xe(e,t)||W2(e,t)||Exe()}
219function Exe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 220In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function W2(e,t){if(e){if(typeof e=="string")return av(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return av(e,t)}}function av(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function _xe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r=[],s=!0,i=!1,o,l;try{for(n=n.call(e);!(s=(o=n.next()).done)&&(r.push(o.value),!(t&&r.length===t));s=!0);}catch(c){i=!0,l=c}finally{try{!s&&n.return!=null&&n.return()}finally{if(i)throw l}}return r}}function Txe(e){if(Array.isArray(e))return e}function aT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function fn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?aT(Object(n),!0).forEach(function(r){ov(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):aT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ov(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sm(e,t){if(e==null)return{};var n=Ixe(e,t),r,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)r=i[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Ixe(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,i;for(i=0;i<r.length;i++)s=r[i],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}var hw=m.forwardRef(function(e,t){var n=e.children,r=sm(e,bxe),s=fw(r),i=s.open,o=sm(s,yxe);return m.useImperativeHandle(t,function(){return{open:i}},[i]),Ne.createElement(m.Fragment,null,n(fn(fn({},o),{},{open:i})))});hw.displayName="Dropzone";var H2={disabled:!1,getFilesFromEvent:$ge,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};hw.defaultProps=H2;hw.propTypes={children:A.func,accept:A.objectOf(A.arrayOf(A.string)),multiple:A.bool,preventDropOnDocument:A.bool,noClick:A.bool,noKeyboard:A.bool,noDrag:A.bool,noDragEventsBubbling:A.bool,minSize:A.number,maxSize:A.number,maxFiles:A.number,disabled:A.bool,getFilesFromEvent:A.func,onFileDialogCancel:A.func,onFileDialogOpen:A.func,useFsAccessApi:A.bool,autoFocus:A.bool,onDragEnter:A.func,onDragLeave:A.func,onDragOver:A.func,onDrop:A.func,onDropAccepted:A.func,onDropRejected:A.func,onError:A.func,validator:A.func};var lv={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function fw(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=fn(fn({},H2),e),n=t.accept,r=t.disabled,s=t.getFilesFromEvent,i=t.maxSize,o=t.minSize,l=t.multiple,c=t.maxFiles,d=t.onDragEnter,u=t.onDragLeave,p=t.onDragOver,h=t.onDrop,f=t.onDropAccepted,g=t.onDropRejected,x=t.onFileDialogCancel,b=t.onFileDialogOpen,y=t.useFsAccessApi,v=t.autoFocus,C=t.preventDropOnDocument,w=t.noClick,S=t.noKeyboard,E=t.noDrag,k=t.noDragEventsBubbling,j=t.onError,_=t.validator,D=m.useMemo(function(){return mxe(n)},[n]),M=m.useMemo(function(){return fxe(n)},[n]),N=m.useMemo(function(){return typeof b=="function"?b:oT},[b]),O=m.useMemo(function(){return typeof x=="function"?x:oT},[x]),R=m.useRef(null),L=m.useRef(null),P=m.useReducer(Dxe,lv),F=tb(P,2),z=F[0],B=F[1],W=z.isFocused,H=z.isFileDialogActive,V=m.useRef(typeof window<"u"&&window.isSecureContext&&y&&hxe()),G=function(){!V.current&&H&&setTimeout(function(){if(L.current){var de=L.current.files;de.length||(B({type:"closeDialog"}),O())}},300)};m.useEffect(function(){return window.addEventListener("focus",G,!1),function(){window.removeEventListener("focus",G,!1)}},[L,H,O,V]);var X=m.useRef([]),K=function(de){R.current&&R.current.contains(de.target)||(de.preventDefault(),X.current=[])};m.useEffect(function(){return C&&(document.addEventListener("dragover",iT,!1),document.addEventListener("drop",K,!1)),function(){C&&(document.removeEventListener("dragover",iT),document.removeEventListener("drop",K))}},[R,C]),m.useEffect(function(){return!r&&v&&R.current&&R.current.focus(),function(){}},[R,v,r]);var ie=m.useCallback(function(te){j?j(te):console.error(te)},[j]),le=m.useCallback(function(te){te.preventDefault(),te.persist(),ee(te),X.current=[].concat(wxe(X.current),[te.target]),Rp(te)&&Promise.resolve(s(te)).then(function(de){if(!(rm(te)&&!k)){var ke=de.length,Le=ke>0&&cxe({files:de,accept:D,minSize:o,maxSize:i,multiple:l,maxFiles:c,validator:_}),at=ke>0&&!Le;B({isDragAccept:Le,isDragReject:at,isDragActive:!0,type:"setDraggedFiles"}),d&&d(te)}}).catch(function(de){return ie(de)})},[s,d,ie,k,D,o,i,l,c,_]),ce=m.useCallback(function(te){te.preventDefault(),te.persist(),ee(te);var de=Rp(te);if(de&&te.dataTransfer)try{te.dataTransfer.dropEffect="copy"}catch{}return de&&p&&p(te),!1},[p,k]),J=m.useCallback(function(te){te.preventDefault(),te.persist(),ee(te);var de=X.current.filter(function(Le){return R.current&&R.current.contains(Le)}),ke=de.indexOf(te.target);ke!==-1&&de.splice(ke,1),X.current=de,!(de.length>0)&&(B({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),Rp(te)&&u&&u(te))},[R,u,k]),he=m.useCallback(function(te,de){var ke=[],Le=[];te.forEach(function(at){var Wt=z2(at,D),zt=tb(Wt,2),Ht=zt[0],Oe=zt[1],Pe=B2(at,o,i),Fe=tb(Pe,2),pt=Fe[0],_t=Fe[1],Rn=_?_(at):null;if(Ht&&pt&&!Rn)ke.push(at);else{var ot=[Oe,_t];Rn&&(ot=ot.concat(Rn)),Le.push({file:at,errors:ot.filter(function(Vn){return Vn})})}}),(!l&&ke.length>1||l&&c>=1&&ke.length>c)&&(ke.forEach(function(at){Le.push({file:at,errors:[lxe]}
220)}),ke.splice(0)),B({acceptedFiles:ke,fileRejections:Le,type:"setFiles"}),h&&h(ke,Le,de),Le.length>0&&g&&g(Le,de),ke.length>0&&f&&f(ke,de)},[B,l,D,o,i,c,h,f,g,_]),ne=m.useCallback(function(te){te.preventDefault(),te.persist(),ee(te),X.current=[],Rp(te)&&Promise.resolve(s(te)).then(function(de){rm(te)&&!k||he(de,te)}).catch(function(de){return ie(de)}),B({type:"reset"})},[s,he,ie,k]),Y=m.useCallback(function(){if(V.current){B({type:"openDialog"}),N();var te={multiple:l,types:M};window.showOpenFilePicker(te).then(function(de){return s(de)}).then(function(de){he(de,null),B({type:"closeDialog"})}).catch(function(de){gxe(de)?(O(de),B({type:"closeDialog"})):xxe(de)?(V.current=!1,L.current?(L.current.value=null,L.current.click()):ie(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):ie(de)});return}L.current&&(B({type:"openDialog"}),N(),L.current.value=null,L.current.click())},[B,N,O,y,he,ie,M,l]),ae=m.useCallback(function(te){!R.current||!R.current.isEqualNode(te.target)||(te.key===" "||te.key==="Enter"||te.keyCode===32||te.keyCode===13)&&(te.preventDefault(),Y())},[R,Y]),je=m.useCallback(function(){B({type:"focus"})},[]),me=m.useCallback(function(){B({type:"blur"})},[]),ve=m.useCallback(function(){w||(pxe()?setTimeout(Y,0):Y())},[w,Y]),Me=function(de){return r?null:de},q=function(de){return S?null:Me(de)},Q=function(de){return E?null:Me(de)},ee=function(de){k&&de.stopPropagation()},Ce=m.useMemo(function(){return function(){var te=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},de=te.refKey,ke=de===void 0?"ref":de,Le=te.role,at=te.onKeyDown,Wt=te.onFocus,zt=te.onBlur,Ht=te.onClick,Oe=te.onDragEnter,Pe=te.onDragOver,Fe=te.onDragLeave,pt=te.onDrop,_t=sm(te,vxe);return fn(fn(ov({onKeyDown:q(Is(at,ae)),onFocus:q(Is(Wt,je)),onBlur:q(Is(zt,me)),onClick:Me(Is(Ht,ve)),onDragEnter:Q(Is(Oe,le)),onDragOver:Q(Is(Pe,ce)),onDragLeave:Q(Is(Fe,J)),onDrop:Q(Is(pt,ne)),role:typeof Le=="string"&&Le!==""?Le:"presentation"},ke,R),!r&&!S?{tabIndex:0}:{}),_t)}},[R,ae,je,me,ve,le,ce,J,ne,S,E,r]),se=m.useCallback(function(te){te.stopPropagation()},[]),oe=m.useMemo(function(){return function(){var te=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},de=te.refKey,ke=de===void 0?"ref":de,Le=te.onChange,at=te.onClick,Wt=sm(te,Cxe),zt=ov({accept:D,multiple:l,type:"file",style:{display:"none"},onChange:Me(Is(Le,ne)),onClick:Me(Is(at,se)),tabIndex:-1},ke,L);return fn(fn({},zt),Wt)}},[L,n,l,ne,r]);return fn(fn({},z),{},{isFocused:W&&!r,getRootProps:Ce,getInputProps:oe,rootRef:R,inputRef:L,open:Me(Y)})}function Dxe(e,t){switch(t.type){case"focus":return fn(fn({},e),{},{isFocused:!0});case"blur":return fn(fn({},e),{},{isFocused:!1});case"openDialog":return fn(fn({},lv),{},{isFileDialogActive:!0});case"closeDialog":return fn(fn({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return fn(fn({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return fn(fn({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return fn({},lv);default:return e}}function oT(){}const Tt={CSV:".csv",TSV:".tsv",PSV:".psv",XLS:".xls",XLSX:".xlsx"},Ic=[Tt.CSV,Tt.TSV,Tt.PSV,Tt.XLS,Tt.XLSX],Axe={"text/csv":[Tt.CSV,Tt.PSV],"text/tab-separated-values":[Tt.TSV],"application/vnd.ms-excel":[Tt.XLS],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[Tt.XLSX],"application/gzip":[Tt.CSV,Tt.TSV,Tt.PSV,Tt.XLS,Tt.XLSX],"application/x-gzip":[Tt.CSV,Tt.TSV,Tt.PSV,Tt.XLS,Tt.XLSX],"application/zip":[Tt.CSV,Tt.TSV,Tt.PSV,Tt.XLS,Tt.XLSX],"application/x-zip-compressed":[Tt.CSV,Tt.TSV,Tt.PSV,Tt.XLS,Tt.XLSX]},Mxe=[".gz",".zip"],Rxe=()=>{if(Ic.length<=2)return Ic.join(" and ");const e=Ic[Ic.length-1];return`${Ic.slice(0,-1).join(", ")}, and ${e}`},Nxe=1e8,mw="100MB",gw=Rxe(),Oxe=[`Maximum file size: ${mw}`,`Formats supported: ${gw} (Excel files will default to the first tab)`,"File may be compressed using gzip or zip","File contains a date column and business columns (cost, impressions)","Verify cost values are reported in the appropriate currency"],lT={id:null,active:!1,api_config:null,api_secret:null,contacts:[],delivery_method:"s3",di_config:null,events_json:null,execution_steps:null,file_compression:null,file_config:null,file_delimiter:",",file_extension:".csv",file_filter:"",frequency:"monthly",freq_offset:1,header_json:null,name:null,name_cleaning:[],notes:"Created with File Upload UI",path:"",s3_bucket:"",supervisor_scheduling:!1,validation_active:!1},Pxe=()=>a.jsxs(T,{mt:4,sx:{backgroundColor:"background.paper",border:"1px solid",borderColor:"divider",borderRadius:2,p:3},children:[a.jsxs(T,{display:"flex",alignItems:"center",gap:1,mb:1,children:[a.jsx(Mt,{sx:{color:"primary.main",fontSize:20},children:a.jsx(Si,{})}),a.jsx(I,{variant:"h6",children:"File Guidelines"})]}),a.jsx(I,{variant:"body2",color:"text.secondary",mb:2,children:"Please ensure your files meet the following requirements before uploading:"}),a.jsx(T,{sx:{display:"flex",flexDirection:"column",gap:1},children:Oxe.map(e=>a.jsxs(T,{display:"flex",alignItems:"center",gap:1,children:[a.jsx(Mt,{sx:{color:"success.main",fontSize:18},children:a.jsx(eC,{})}),a.jsx(I,{variant:"body2",color:"text.secondary",children:e})]},e))})]}),Lxe=({fileId:e,fileName:t,isDownloading:n=!1,onDeleteClick:r,onDownloadClick:s,onViewClick:i,s3Key:o})=>{const l=()=>{i(e)},c=()=>{s(e,o)},d=()=>{r&&r(e,t)};return a.jsxs(T,{sx:{display:"flex",gap:.5},children:[a.jsx(be,{title:"View",children:a.jsx(Ie,{onClick:l,size:"small",sx:{p:.5},children:a.jsx(Mt,{sx:{fontSize:18},children:a.jsx(vm,{})})})}),a.jsx(be,{title:"Download",children:a.jsx(Ie,{disabled:n,onClick:c,size:"small",sx:{p:.5},children:n?a.jsx(Ze,{size:18}):a.jsx(Mt,{sx:{fontSize:18},children:a.jsx(bl,{})})})}),r&&a.jsx(be,{title:"Delete",children:a.jsx(Ie,{onClick:d,size:"small",sx:{p:.5},children:a.jsx(Mt,{sx:{fontSize:18},children:a.jsx(Xr,{})})})})]})};function Fxe(e){return typeof e!="number"||e===0?"N/A":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(2)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(2)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}function cT(e){return e.replaceAll(/[^a-zA-Z0-9]/g,"").toLowerCase()}function $xe(e,t){return e.find(n=>{const r=n.input_uri?.startsWith("s3://")?n.input_uri.split("/").pop():void 0,s=n.output_uri?.startsWith("s3://")?n.output_uri.split("/").pop():void 0;return r===t||s===t})}function cv(e){if(!e||typeof e!="string")return"file";const t=e.split("/");return t[t.length-1]||"file"}function zxe(e){if(!e)return"";const t=e.replace(/^s3:\/\//,""),n=t.indexOf("/");return n===-1?"":t.slice(n+1)}function Bxe(e){return zxe(e.output_uri||e.input_uri)}function Uxe(e){const t=cv(e).toLowerCase(),n=Mxe.find(o=>t.endsWith(o))??null,r=n?t.slice(0,-n.length):t,s=r.lastIndexOf("."),i=s>0?r.slice(s):null;return{fileCompression:n,fileExtension:i}}function q2(e){switch(e.toUpperCase()){case"ASSIGNED":case"SUCCESS":return"success";case"WARNING":return"warning";
220case"ERROR":return"error";default:return"default"}}function dT(e,t){const n=document.createElement("a");n.href=e,n.download=t,document.body.appendChild(n);try{n.click()}finally{document.body.removeChild(n)}}function dv(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2")}const Vxe=({status:e,onClick:t})=>{const n=!!t;return a.jsx(ut,{label:Im(e),color:q2(e),onClick:n?t:void 0,sx:{cursor:n?"pointer":"default"}})},Wxe=({downloadingFileId:e,onDeleteClick:t,onDownloadClick:n,onStatusClick:r,onViewClick:s})=>[{field:"input_uri",headerName:"File Name",flex:1,minWidth:200,valueGetter:i=>{const{value:o}=i;return typeof o!="string"?"":cv(o)}},{field:"report",headerName:"Size",width:120,valueGetter:i=>i.value?.file_size_bytes??0,valueFormatter:i=>Fxe(i.value)},{field:"path",headerName:"Path",flex:1,minWidth:200,valueGetter:i=>Bxe(i.row)},{field:"created_at",headerName:"Upload Date",width:180,valueFormatter:i=>{const{value:o}=i;if(typeof o!="string")return"";const l=new Date(o);return Number.isNaN(l.getTime())?o:l.toLocaleString()}},{field:"metadata",headerName:"Uploaded By",width:150,valueGetter:i=>i.value?.user_name??"Unknown"},{field:"status",headerName:"Status",width:120,renderCell:i=>{const o=i.row.status==="unassigned";return a.jsx(Vxe,{status:i.row.status,onClick:o?()=>r(i.row.input_uri):void 0})}},{field:"warning",headerName:"Warning",width:180,valueGetter:i=>i.row.warning?.type??null,renderCell:i=>{const o=i.row.warning?.type;if(!o)return a.jsx(I,{color:"text.secondary",variant:"body2",children:"N/A"});const l=dv(o).replace(/\s*Warning$/i,"");return a.jsx(ut,{color:"warning",label:l})}},{field:"actions",headerName:"Actions",width:120,sortable:!1,filterable:!1,renderCell:i=>{const o=cv(i.row.input_uri);return a.jsx(Lxe,{fileId:i.row.input_uri,fileName:o,isDownloading:e===i.row.input_uri,onDeleteClick:t,onDownloadClick:n,onViewClick:s,s3Key:i.row.input_uri})}}],G2=rt(Mn)(({theme:e})=>{const{palette:t,spacing:n}=e,{background:r,border:s,text:i}=t;return{border:"none",[`& .${xe.main}`]:{borderRadius:n(2)},[`& .${xe.columnHeaders}`]:{backgroundColor:r.tableHeader},[`& .${xe.columnHeader}`]:{fontSize:12,height:18,textTransform:"uppercase",color:i.secondary},[`& .${xe.columnSeparator}`]:{color:s.default,":hover":{color:s.default}},[`& .${xe.row}:nth-of-type(n)`]:{backgroundColor:r.paper,":hover":{backgroundColor:e.palette.mode==="dark"?r.brand.subtle.hovered:r.brand.subtlest.default}},[`& .${xe.cell}`]:{border:"none"},[` 221 & .${xe.cell}:focus-visible, 222 & .${xe.cell}:focus-within 223 `]:{outline:`2px solid ${t.primary.main}`,outlineOffset:"-2px"},[` 224 & .${xe.columnHeader}:focus-visible, 225 & .${xe.columnHeader}:focus-within 226 `]:{outline:`2px solid ${t.primary.main}`,outlineOffset:"-2px"}}}),Hxe=({getRootProps:e,getInputProps:t,isDragActive:n,isUploading:r})=>{const s=Re();return a.jsxs(T,{"data-testid":"file-upload:dropzone",sx:{alignItems:"center",border:1,borderColor:aA.alpha(s.palette.secondary.main,.2),borderRadius:2.5,borderStyle:"dashed",display:"flex",flexWrap:"wrap",justifyContent:"center",outline:"none",px:3,py:4,...n&&{backgroundColor:"background.brand.subtlest.hovered"},"&:hover":{backgroundColor:"background.brand.subtlest.hovered",cursor:"pointer"}},...e(),children:[a.jsx("input",{...t()}),a.jsxs($,{alignItems:"center",direction:"row",sx:{py:3.75},gap:2,children:[a.jsx(as,{sx:{backgroundColor:"background.brand.subtle.default",height:64,width:64},children:r?a.jsx(Ze,{size:32}):a.jsx(Mt,{sx:{color:"icon.brand.main"},children:a.jsx(tC,{})})}),a.jsxs($,{spacing:1,sx:{minWidth:280},children:[a.jsx(I,{sx:{"& span":{textDecoration:"underline"}},variant:"subtitle1",children:r?"Uploading...":a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"Click to upload"})," or drag and drop"]})}),a.jsxs(I,{variant:"body2",color:"text.secondary",children:[gw," files (Max ",mw,")"]})]})]})]})},qxe=e=>{try{const t=new URL(e);return t.protocol!=="s3:"?null:t.hostname||null}catch{return null}},Gxe=({clientNiceId:e,engagementId:t,engagementNiceId:n,inputUri:r,skipMoveFile:s=!1})=>{const[i]=VV(),[o]=NA(),[l]=gC();return{createDataSource:m.useCallback(async d=>{if(!t||!n||!e)return{success:!1,errors:{form:"Missing engagement information"}};if(!r)return{success:!1,errors:{form:"Missing file URI information"}};const u=rg(d.contentType);if(!u)return{success:!1,errors:{contentType:"Select a content type"}};const p=cT(d.vendorName),h=cT(d.mediaType),f=`${u.niceId}_${p}_${h}`,g=`/${n}/${f}`,x=qxe(r);if(!x)return{success:!1,errors:{form:"Invalid S3 file location"}};try{if(await i({dataSourceId:null,engagementId:t,contentType:u.contentType,vendor:p||"",feed:h||""}).unwrap())return{success:!1,errors:{contentType:"This data source already exists",vendorName:"This combination already exists",mediaType:"This combination already exists"}}}catch(w){return We(w),{success:!1,errors:{form:"Failed to check for duplicates"}}}const{fileCompression:b,fileExtension:y}=Uxe(r),v=d.name?.trim(),C={...lT,content_type:u.contentType,measurement_category:[...u.measurementCategory],feed_nice_id:h||"",vendor_nice_id:p||"",client_nice_id:e,engagement_id:t,engagement_nice_id:n,file_compression:b,file_extension:y??lT.file_extension,name:v||null,path:g,s3_bucket:x};try{const w=await o(C).unwrap();if(s)return{success:!0,dataSourceId:w};try{return await l({datasource_id:w,engagement_nice_id:n,input_uri:r}).unwrap(),{success:!0,dataSourceId:w}}catch(S){return We(S),{success:!1,errors:{form:"Data source created, but failed to assign file"}}}}catch(w){return We(w),{success:!1,errors:{form:"Failed to create data source"}}}},[i,e,t,n,l,s,o,r])}},Yxe=({engagementNiceId:e,onDeleteSuccess:t})=>{const[n]=WV(),[r,s]=m.useState(null);return{deleteFile:m.useCallback(async o=>{if(!e){const l="Missing engagement information";return s(l),{success:!1,error:l}}try{return s(null),await n({engagement_nice_id:e,input_uri:o}).unwrap(),t&&t(),{success:!0}}catch(l){const c=l instanceof Error?l.message:"Failed to delete file";return s(c),We(l),{success:!1,error:c}}},[n,e,t]),error:r}},Kxe=e=>{const{engagementNiceId:t}=pe(),[n,r]=m.useState("idle"),[s,i]=m.useState([]),[o,l]=m.useState(null),[c,d]=m.useState(null),[u,p]=m.useState(null),[h]=HV(),[f]=Sm(),g=m.useCallback(async(w,S,E,k,j,_)=>{try{r("uploading"),e?.onUploadStart&&e.onUploadStart(j);const D=new FormData;
226Object.entries(E).forEach(([N,O])=>{D.append(N,O)}),D.append("file",w,w.name);const M=await f({data:D,method:"post",url:S}).unwrap();return i(N=>[...N,w]),r("complete"),p(k),e?.onUploadComplete&&e.onUploadComplete(j,_),d(null),M}catch(D){const M=D instanceof Error?D.message:"S3 upload failed. Please check file size and permissions.";throw l(M),r("error"),d(null),D}},[f,e]),x=m.useCallback(async w=>{if(!t){l("Missing engagement information"),r("error");return}try{r("getting-url"),l(null);const S=await h({engagement_nice_id:t,file_name:w.name}).unwrap();if(!S?.url||!S?.fields)throw new Error("Failed to get upload URL");const{url:E,fields:k,key:j,key_exists:_,input_uri:D}=S,M=_?e?.onFindExistingFile?.(w.name):void 0;if(d({file:w,url:E,fields:k,key:j,inputUri:D,existingFileInputUri:M}),_){r("awaiting-confirmation");return}r("awaiting-datasource")}catch(S){l(S instanceof Error?S.message:"Failed to upload file"),r("error"),d(null)}},[t,h,e]),b=m.useCallback(()=>{if(!c){l("No pending upload to confirm");return}r("awaiting-datasource")},[c]),y=m.useCallback(async w=>{if(!c){l("No pending upload to proceed with");return}d(S=>S?{...S,selectedDataSourceId:w}:null),await g(c.file,c.url,c.fields,c.key,c.inputUri,w).catch(()=>{})},[c,g]),v=m.useCallback(()=>{d(null),r("idle"),l(null)},[]),C=m.useCallback(()=>{r("idle"),i([]),l(null),p(null)},[]);return{cancelUpload:v,confirmOverride:b,error:o,lastUploadedKey:u,pendingUpload:c,proceedWithUpload:y,reset:C,uploadFile:x,uploadState:n,uploadedFiles:s}},Qxe={upload:"File Upload Complete",assignDataSource:"Assign Data Source",createDataSource:"Create Data Source",preview:"Preview File",delete:"Delete File",download:"Download File",override:"Override Existing File",cancel:"Cancel Upload"},Y2=()=>{const{mpTrack:e}=tr();return{fileUploadMpTrack:(n,r)=>{e("MEVO_FILE_UPLOAD",{actionType:Qxe[n],actionData:{...r}})}}},Jxe=24e4;function Xxe(e){const[t,n]=m.useState({isListening:!1,progress:0,message:"",error:null,isComplete:!1,inputUri:null}),{message:r}=fu("FileUpload"),s=m.useRef(null),i=m.useRef(null),o=m.useRef(null),l=m.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),c=m.useCallback(()=>{l(),i.current=setTimeout(()=>{i.current=null,n(g=>({...g,error:"Upload timed out. No progress received within 4 minutes. Please try again or contact support.",isComplete:!0,isListening:!1}))},Jxe)},[l]),d=m.useCallback(()=>{l(),n(g=>({...g,isListening:!1}))},[l]),u=m.useCallback(()=>{l(),d(),n({isListening:!1,progress:0,message:"",error:null,isComplete:!1,inputUri:null}),s.current=null,o.current=null},[l,d]),p=m.useCallback(()=>{n(g=>({...g,isComplete:!1}))},[]),h=m.useCallback((g,x)=>{const b=Math.max(0,Math.min(100,g)),y=b>=100;y?l():c(),n(v=>b<=v.progress?v:{...v,progress:b,message:x,isComplete:y,isListening:y?!1:v.isListening})},[l,c]),f=m.useCallback(g=>{s.current=g,o.current=r?.data||null,n({isListening:!0,progress:0,message:"Uploading and initializing agent...",error:null,isComplete:!1,inputUri:g}),c()},[c,r]);return m.useEffect(()=>()=>{l()},[l]),m.useEffect(()=>{if(!t.isListening||!s.current||!r)return;const{data:g}=r;if(g===o.current||g.taskId!==s.current)return;if(o.current=g,c(),g.error){l(),n(v=>({...v,error:g.message||"Validation failed",isComplete:!0,isListening:!1}));return}const x=Math.max(0,Math.min(100,g.percentComplete)),b=g.message,y=x>=100;y&&l(),n(v=>({...v,progress:x,message:b,isComplete:y,isListening:y?!1:v.isListening}))},[r,t.isListening,e,c,l]),{startProgress:f,updateProgress:h,stopProgress:d,resetProgress:u,clearComplete:p,state:t}}const Zxe=()=>{const[e,t]=m.useState(!1),[n,r]=m.useState("progress"),[s,i]=m.useState(null),[o,l]=m.useState(""),[c,d]=m.useState(!0),[u,p]=m.useState(!1),h=m.useCallback((y,v,C=!0,w=!1)=>{r(y),t(!0),d(C),p(w),v?(l(v.input_uri),v.report&&i({input_uri:v.input_uri,created_at:v.created_at??v.report.created_at,file_type:v.report.file_type,header_row_index:v.report.header_row_index,status:v.status,shape:v.report.shape,columns:v.report.columns,header_mapping:v.report.header_mapping??{},metrics:v.report.metrics??{},notes:v.report.notes??[],error:v.error??null,warning:v.warning??null})):(l(""),i(null))},[]),f=m.useCallback(()=>{t(!1)},[]),g=m.useCallback(()=>{r("progress"),i(null),l(""),d(!0),p(!1)},[]),x=m.useCallback(y=>{r(y)},[]),b=m.useCallback(()=>{t(!0)},[]);
226return{currentStep:n,isOpen:e,isViewOnly:u,showCreateOption:c,summaryData:s,inputUri:o,closeWizard:f,openWizard:h,resetWizardState:g,setStep:x,setSummaryData:i,setInputUri:l,ensureOpen:b}},ebe=({assignError:e,onCreateOpen:t,onDataSourceChange:n,onNoneSelect:r,selectedDataSourceId:s,selectedOption:i,showCreateOption:o})=>{const{dataSourceOptions:l}=mg();return a.jsxs($,{spacing:2,sx:{pt:2},children:[e&&a.jsx(I,{color:"error",sx:{bgcolor:"error.light",borderRadius:1,fontSize:14,p:2},children:e}),o&&a.jsxs(a.Fragment,{children:[a.jsx(Ve,{elevation:0,onClick:t,sx:{border:"2px solid",borderColor:i==="create"?"primary.main":"border.input",borderRadius:2,cursor:"pointer",transition:"all 0.2s","&:hover":{borderColor:"primary.main",backgroundColor:"action.hover"}},children:a.jsx(Ue,{sx:{p:2},children:a.jsxs($,{alignItems:"center",direction:"row",spacing:2,children:[a.jsx(Mt,{sx:{color:"primary.main",fontSize:24},children:a.jsx(ca,{})}),a.jsxs(T,{sx:{flex:1},children:[a.jsx(I,{sx:{fontSize:16,fontWeight:600,mb:.5},children:"Create New Data Source"}),a.jsx(I,{color:"text.secondary",sx:{fontSize:14},variant:"body2",children:"This file will be added to a new data source"})]})]})})}),a.jsx(Ve,{elevation:0,onClick:r,sx:{border:"2px solid",borderColor:i==="none"?"primary.main":"border.input",borderRadius:2,cursor:"pointer",transition:"all 0.2s","&:hover":{borderColor:"primary.main",backgroundColor:"action.hover"}},children:a.jsx(Ue,{sx:{p:2},children:a.jsxs($,{alignItems:"center",direction:"row",spacing:2,children:[a.jsx(Mt,{sx:{color:"text.secondary",fontSize:24},children:a.jsx(CU,{})}),a.jsxs(T,{sx:{flex:1},children:[a.jsx(I,{sx:{fontSize:16,fontWeight:600,mb:.5},children:"None"}),a.jsx(I,{color:"text.secondary",sx:{fontSize:14},variant:"body2",children:"Skip data source assignment, file will not be selected for data ingestion"})]})]})})}),a.jsxs(T,{sx:{position:"relative",py:1},children:[a.jsx(T,{sx:{borderBottom:"1px solid",borderColor:"divider",position:"absolute",top:"50%",width:"100%"}}),a.jsx(I,{color:"text.secondary",sx:{backgroundColor:"background.paper",fontSize:14,mx:"auto",px:2,position:"relative",textAlign:"center",width:"fit-content"},variant:"body2",children:"Or assign to existing"})]})]}),a.jsxs(Qe,{fullWidth:!0,variant:"outlined",sx:{mt:1},children:[a.jsx(wt,{id:"data-source-select-label",sx:{"&.MuiInputLabel-shrink":{bgcolor:"background.paper",ml:-.5,px:1,transform:"translate(14px, -9px) scale(0.75)"}},children:"Select Data Source"}),a.jsx(tt,{labelId:"data-source-select-label",id:"data-source-select",value:s,label:"Select Data Source",onChange:n,disabled:l.length===0,MenuProps:{PaperProps:{sx:{maxHeight:300}}},children:l.length===0?a.jsx(Se,{value:"",disabled:!0,children:"No data sources available"}):l.map(c=>a.jsx(Se,{value:String(c.id),children:c.name},c.id))}),l.length===0&&a.jsx(Zn,{children:"No data sources are available. Please create a new data source."})]})]})},tbe=()=>{const e=on(),t=e.watch("contentType"),n=m.useMemo(()=>rg(t)??ul[0],[t]);return a.jsxs($,{spacing:3,sx:{pt:2},children:[a.jsxs($,{alignItems:"center",direction:"row",spacing:1,children:[a.jsx(Mt,{sx:{color:"primary.main",fontSize:20},children:a.jsx(du,{})}),a.jsx(I,{color:"primary",sx:{fontSize:14,fontWeight:500},children:"AI Powered Values"})]}),e.formState.errors.root&&a.jsx(I,{color:"error",sx:{bgcolor:"error.light",borderRadius:1,fontSize:14,p:2},children:e.formState.errors.root.message}),a.jsx(De,{fullWidth:!0,label:"Data Source Name",placeholder:"Enter a descriptive name for your data source",...e.register("name"),error:!!e.formState.errors.name,helperText:e.formState.errors.name?.message,variant:"outlined",InputLabelProps:{sx:{"&.MuiInputLabel-shrink":{bgcolor:"background.paper",ml:-.5,px:1}}}}),a.jsxs(Qe,{fullWidth:!0,variant:"outlined",children:[a.jsx(wt,{id:"content-type-label",sx:{"&.MuiInputLabel-shrink":{bgcolor:"background.paper",ml:-.5,px:1,transform:"translate(14px, -9px) scale(0.75)"}},children:"Content Type"}),a.jsx(tt,{labelId:"content-type-label",id:"content-type-select",value:e.watch("contentType"),label:"Content Type",onChange:r=>
226{e.setValue("contentType",r.target.value,{shouldValidate:!0})},error:!!e.formState.errors.contentType,children:ul.map(r=>a.jsx(Se,{value:r.label,children:r.label},r.label))}),e.formState.errors.contentType&&a.jsx(I,{color:"error",sx:{fontSize:12,mt:.5,mx:1.75},children:e.formState.errors.contentType.message})]}),a.jsx(De,{fullWidth:!0,label:"Vendor Name",...e.register("vendorName"),error:!!e.formState.errors.vendorName,helperText:e.formState.errors.vendorName?.message,variant:"outlined",InputLabelProps:{sx:{"&.MuiInputLabel-shrink":{bgcolor:"background.paper",ml:-.5,px:1}}}}),a.jsx(De,{fullWidth:!0,label:n.feedLabel,placeholder:`Enter ${n.feedLabel.toLowerCase()}`,...e.register("mediaType"),error:!!e.formState.errors.mediaType,helperText:e.formState.errors.mediaType?.message,variant:"outlined",InputLabelProps:{sx:{"&.MuiInputLabel-shrink":{bgcolor:"background.paper",ml:-.5,px:1}}}})]})},nbe=({methods:e})=>a.jsx(Js,{...e,children:a.jsx(tbe,{})}),rbe=({error:e,filename:t,message:n,percentage:r})=>{const s=Math.max(0,Math.min(100,Math.round(r||0))),i=r>=100;return a.jsxs($,{spacing:3,children:[a.jsxs($,{direction:"row",spacing:2,alignItems:"flex-start",children:[a.jsx(T,{sx:{alignItems:"center",backgroundColor:e?"error.light":"background.paper",borderRadius:2,display:"flex",height:64,justifyContent:"center",width:64},children:a.jsx(Mt,{sx:{color:e?"error.main":"primary.main",fontSize:32},children:e?a.jsx(wl,{}):a.jsx(du,{})})}),a.jsxs(T,{sx:{flex:1,pt:.5},children:[a.jsx(I,{variant:"h6",sx:{fontWeight:700,mb:.5},children:e?"Validation Failed":"AI Validation in Progress"}),a.jsx(I,{variant:"body2",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),!e&&a.jsxs(I,{variant:"h5",sx:{color:"primary.main",fontWeight:600,pt:.5},children:[s,"%"]})]}),e&&a.jsx(vn,{severity:"error",children:e}),!e&&a.jsx(lo,{variant:"determinate",value:s,sx:{backgroundColor:"action.hover",borderRadius:1,height:8,"& .MuiLinearProgress-bar":{backgroundColor:"primary.main",borderRadius:1}}}),!e&&a.jsxs($,{direction:"row",spacing:1.5,alignItems:"center",children:[!i&&a.jsx(Ze,{size:20,thickness:4}),a.jsx(I,{variant:"body2",color:"text.secondary",children:n})]})]})},sbe=({summaryData:e})=>{const{previewData:t}=mg(),{engagementCurrency:n}=pe(),r=m.useMemo(()=>e?.metrics?.spend?Ci(e.metrics.spend.sum,{options:{currency:n,maximumFractionDigits:2,minimumFractionDigits:2}}):null,[e?.metrics?.spend,n]),s=m.useMemo(()=>t?.headers?t.headers.map(l=>({field:l,headerName:l,flex:1,minWidth:150})):[],[t?.headers]),i=m.useMemo(()=>t?.rows?t.rows.map((l,c)=>({id:c,...l})):[],[t?.rows]);if(!e)return null;const o=e.input_uri.split("/").pop()||e.input_uri;return a.jsxs($,{spacing:2,children:[e.error&&a.jsxs(vn,{severity:"error",children:[a.jsx(xj,{children:dv(e.error.type)}),e.error.message,e.error.suggestions&&a.jsx(I,{sx:{mt:1},variant:"body2",children:e.error.suggestions}),e.error.markdown&&a.jsxs(Ka,{disableGutters:!0,elevation:0,sx:{backgroundColor:"transparent",mt:1,"&::before":{display:"none"}},children:[a.jsx(Qa,{expandIcon:a.jsx(Gh,{}),sx:{minHeight:0,p:0},children:a.jsx(I,{variant:"body2",children:"Show all details"})}),a.jsx(Ja,{sx:{p:0},children:a.jsx(ms,{markdownText:e.error.markdown})})]})]}),e.warning&&a.jsxs(vn,{severity:"warning",children:[a.jsx(xj,{children:dv(e.warning.type)}),e.warning.message,e.warning.suggestions&&a.jsx(I,{sx:{mt:1},variant:"body2",children:e.warning.suggestions}),e.warning.markdown&&a.jsxs(Ka,{disableGutters:!0,elevation:0,sx:{backgroundColor:"transparent",mt:1,"&::before":{display:"none"}},children:[a.jsx(Qa,{expandIcon:a.jsx(Gh,{}),sx:{minHeight:0,p:0},children:a.jsx(I,{variant:"body2",children:"Show all details"})}),a.jsx(Ja,{sx:{p:0},children:a.jsx(ms,{markdownText:e.warning.markdown})})]})]}),e.metrics.start_date&&a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:2},children:a.jsxs(Ue,{sx:{p:2},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,mb:2},children:[a.jsx(as,{sx:{backgroundColor:"background.paper",height:28,width:28},children:a.jsx(Mt,{sx:{color:"primary.main",fontSize:16},children:a.jsx(au,{})})}),a.jsx(I,{sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:"Date Range"})]}),a.jsxs(T,{sx:{display:"flex",gap:4},children:[a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:12,mb:.5},variant:"body2",children:"Start Date"}),a.jsx(I,{sx:{fontSize:20,fontWeight:600},children:Z(e.metrics.start_date.min_date).format("MMM D, YYYY")})]}),a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:12,mb:.5},variant:"body2",children:"End Date"}),a.jsx(I,{sx:{fontSize:20,fontWeight:600},children:Z(e.metrics.start_date.max_date).format("MMM D, YYYY")})]})]})]})}),a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,mb:2},children:[a.jsx(as,{sx:{backgroundColor:"background.paper",height:28,width:28},children:a.jsx(Mt,{sx:{color:"primary.main",fontSize:16},children:a.jsx(uu,{})})}),a.jsx(I,{sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:"Business Metrics Summary"})]}),a.jsxs(T,{sx:{display:"flex",gap:2},children:[e.metrics.spend&&a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:2,flex:1},children:a.jsxs(Ue,{sx:{p:2},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:12,mb:1},variant:"body2",children:"Spend"}),a.jsx(I,{sx:{fontSize:24,fontWeight:600,mb:.5},children:r}),a.jsxs(I,{color:"text.secondary",variant:"caption",children:[e.metrics.spend.empty_rows.toLocaleStr
226ing()," empty rows"]})]})}),e.metrics.impressions&&a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:2,flex:1},children:a.jsxs(Ue,{sx:{p:2},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:12,mb:1},variant:"body2",children:"Impressions"}),a.jsx(I,{sx:{fontSize:24,fontWeight:600,mb:.5},children:e.metrics.impressions.sum.toLocaleString()}),a.jsxs(I,{color:"text.secondary",variant:"caption",children:[e.metrics.impressions.empty_rows.toLocaleString()," empty rows"]})]})}),e.metrics.clicks&&a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:2,flex:1},children:a.jsxs(Ue,{sx:{p:2},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:12,mb:1},variant:"body2",children:"Clicks"}),a.jsx(I,{sx:{fontSize:24,fontWeight:600,mb:.5},children:e.metrics.clicks.sum.toLocaleString()}),a.jsxs(I,{color:"text.secondary",variant:"caption",children:[e.metrics.clicks.empty_rows.toLocaleString()," empty rows"]})]})})]})]})}),a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,mb:2},children:[a.jsx(as,{sx:{backgroundColor:"background.paper",height:28,width:28},children:a.jsx(Mt,{sx:{color:"primary.main",fontSize:16},children:a.jsx(wU,{})})}),a.jsx(I,{sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:"File Information"})]}),a.jsxs($,{spacing:1.5,children:[a.jsxs(T,{sx:{display:"flex",gap:1},children:[a.jsx(I,{color:"text.secondary",sx:{minWidth:100},variant:"body2",children:"Name:"}),a.jsx(I,{variant:"body2",children:o})]}),a.jsxs(T,{sx:{display:"flex",gap:1},children:[a.jsx(I,{color:"text.secondary",sx:{minWidth:100},variant:"body2",children:"Type:"}),a.jsx(ut,{label:e.file_type.toUpperCase(),size:"small"})]}),a.jsxs(T,{sx:{display:"flex",gap:1},children:[a.jsx(I,{color:"text.secondary",sx:{minWidth:100},variant:"body2",children:"Created:"}),a.jsx(I,{variant:"body2",children:Z(e.created_at).format("MMM D, YYYY h:mm A")})]}),a.jsxs(T,{sx:{display:"flex",gap:1},children:[a.jsx(I,{color:"text.secondary",sx:{minWidth:100},variant:"body2",children:"Columns:"}),a.jsx(I,{variant:"body2",children:e.shape.input.columns})]}),a.jsxs(T,{sx:{display:"flex",gap:1},children:[a.jsx(I,{color:"text.secondary",sx:{minWidth:100},variant:"body2",children:"Rows:"}),a.jsx(I,{variant:"body2",children:e.shape.input.rows.toLocaleString()})]})]})]})}),a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,mb:2},children:[a.jsx(as,{sx:{backgroundColor:"background.paper",height:28,width:28},children:a.jsx(Mt,{sx:{color:"primary.main",fontSize:16},children:a.jsx(po,{})})}),a.jsxs(I,{sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:["Columns (",e.columns.length,")"]})]}),a.jsx(T,{sx:{display:"flex",flexWrap:"wrap",gap:.5},children:e.columns.map(l=>a.jsx(ut,{label:l,size:"small",variant:"outlined"},l))})]})}),e.notes.length>0&&a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,mb:2},children:[a.jsx(as,{sx:{backgroundColor:"background.paper",height:28,width:28},children:a.jsx(Mt,{sx:{color:"primary.main",fontSize:16},children:a.jsx(du,{})})}),a.jsx(I,{sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:"Notes"})]}),a.jsx($,{spacing:.5,children:e.notes.map(l=>a.jsxs(I,{variant:"body2",children:["⢠",l]},l))})]})}),a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"border.input",borderRadius:3.5},children:a.jsxs(Ue,{sx:{p:3,".MuiCardContent-root&:last-child":{pb:3}},children:[a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:1,mb:2},children:[a.jsx(as,{sx:{backgroundColor:"background.paper",height:28,width:28},children:a.jsx(Mt,{sx:{color:"primary.main",fontSize:16},children:a.jsx(vm,{})})}),a.jsx(I,{sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:"File Preview"})]}),i.length>0&&a.jsx(T,{sx:{height:400,width:"100%"},children:a.jsx(G2,{columns:s,rows:i,disableColumnMenu:!0,disableRowSelectionOnClick:!0,hideFooter:!0})}),i.length===0&&a.jsx(I,{color:"text.secondary",variant:"body2",children:"No data to preview"})]})})]})},uT=e=>U.string().min(1,`${e} is required`).regex(tw,{message:"Alphanumeric characters only"}),ibe=U.object({contentType:U.string().min(1,"Content type is required"),mediaType:uT("Media type"),name:U.string().optional(),vendorName:uT("Vendor name")}
226),abe={contentType:"Media",mediaType:"",name:"",vendorName:""},obe=({error:e,canRetryOnError:t=!1,message:n,isLoadingContinue:r=!1,isPreUploadAssign:s=!1,onAssignSuccess:i,onBackToAssign:o,onCancelUpload:l,onClose:c,onCreateDataSource:d,onCreateOpen:u,onDataSourceSelected:p,onExited:h,onProgressContinue:f,onSummaryConfirm:g,open:x,percentage:b,showCreateOption:y=!0,step:v,summaryData:C,inputUri:w})=>{const{dataSourceOptions:S,dispatch:E,engagementNiceId:k,state:j}=mg(),{fileUploadMpTrack:_}=Y2(),D=j.uploadingFileName,M=j.deletingFileId===w,[N,O]=m.useState(""),[R,L]=m.useState(""),[P,F]=m.useState(!1),[z,B]=m.useState(""),[W]=gC(),H=Xs({defaultValues:abe,mode:"all",resolver:Zs(ibe)}),V=m.useCallback(Q=>{L(Q.target.value),O("existing"),B("")},[]),G=m.useCallback(()=>{O(""),L(""),F(!1),B(""),H.reset(),c(),E({type:"setActiveTab",value:1})},[H,c,E]),X=m.useCallback(()=>{f&&f()},[f]),K=m.useCallback(()=>{g&&g()},[g]),ie=m.useCallback(()=>{u&&u()},[u]),le=m.useCallback(()=>{s&&p?p(null):G()},[G,s,p]),ce=m.useCallback(()=>{H.reset(),o&&o()},[H,o]),J=m.useCallback(async()=>{if(B(""),N==="create"){ie();return}if(N==="none"){if(s&&p){p(null);return}G();return}if(N==="existing"&&R){if(s&&p){p(Number(R));return}try{F(!0),await W({datasource_id:Number(R),engagement_nice_id:k,input_uri:w}).unwrap();const Q=S.find(ee=>ee.id===Number(R));_("assignDataSource",{datasourceId:Number(R),inputUri:w,dataSourceName:Q?.name}),i&&i(),G()}catch(Q){We(Q);let ee="Failed to assign file to data source. Please try again.";if(Q&&typeof Q=="object"&&"data"in Q){const Ce=Q.data;Ce&&typeof Ce=="object"&&"message"in Ce&&typeof Ce.message=="string"&&(ee=Ce.message)}B(ee),F(!1)}}},[S,k,_,G,ie,s,W,i,p,R,N,w]),he=m.useCallback(async Q=>{if(!d){We("onCreateDataSource handler not provided");return}try{F(!0);const ee=await d(Q);if(ee.success){if(ee.dataSourceId&&_("createDataSource",{datasourceId:ee.dataSourceId,contentType:Q.contentType,vendor:Q.vendorName,mediaType:Q.mediaType,inputUri:w}),s&&p&&ee.dataSourceId){p(ee.dataSourceId);return}i&&i(),G()}else ee.errors&&(Object.entries(ee.errors).forEach(([Ce,se])=>{(Ce==="contentType"||Ce==="vendorName"||Ce==="mediaType")&&H.setError(Ce,{type:"manual",message:se})}),F(!1))}catch(ee){We(ee),H.setError("root",{type:"manual",message:"An unexpected error occurred. Please try again."}),F(!1)}},[_,G,w,s,H,i,d,p]),ne=C?q2(C.status):"default",Y=b>=100,ae=N!=="existing"||!R||S.length===0,je=m.useMemo(()=>{switch(v){case"progress":return null;case"summary":return a.jsxs(T,{sx:{alignItems:"center",display:"flex",gap:2},children:[a.jsx(I,{sx:{fontSize:24,fontWeight:600},children:"File Summary"}),C&&a.jsx(ut,{color:ne,label:C.status.charAt(0).toUpperCase()+C.status.slice(1),size:"small"})]});case"assign":return a.jsxs($,{alignItems:"center",direction:"row",spacing:1,children:[a.jsx(Mt,{sx:{color:"primary.main",fontSize:24},children:a.jsx(qD,{})}),a.jsx(I,{sx:{fontSize:24,fontWeight:600},children:"Assign to a Data Source"})]});case"create":return a.jsxs($,{alignItems:"center",direction:"row",spacing:1,children:[a.jsx(Ie,{onClick:ce,size:"small",children:a.jsx(Mt,{children:a.jsx(oA,{})})}),a.jsx(I,{sx:{fontSize:24,fontWeight:600},children:"Configure New Data Source"})]});default:return null}},[ce,ne,v,C]),{isValid:me}=H.formState,ve=m.useMemo(()=>{switch(v){case"progress":return a.jsxs($,{direction:"row",spacing:2,justifyContent:"flex-end",children:[e&&a.jsx(re,{"data-testid":"file-upload:wizard:close",variant:"contained",onClick:G,children:"Close"}),(!e||t)&&a.jsx(Dt,{"data-testid":"file-upload:wizard:continue",variant:"contained",onClick:X,disabled:!Y,loading:r,children:e?"Retry":"Continue"})]});case"summary":return g?a.jsxs(a.Fragment,{children:[a.jsx(re,{"data-testid":"file-upload:wizard:cancel-upload",onClick:l||G,color:"secondary",disabled:M,children:l?M?"Cancelling...":"Cancel Upload":"Close"}),a.jsx(re,{"data-testid":"file-upload:wizard:assign",onClick:K,variant:"contained",children:"Assign to Data Source"})]}):a.jsx(re,{"data-testid":"file-upload:wizard:close",onClick:G,variant:"contained",children:"Close"});case"assign":return a.jsxs(a.Fragment,{children:[a.jsx(re,{"data-testid":"file-upload:wizard:cancel",onClick:G,color:"secondary",disabled:P,children:"Cancel"}),a.jsx(Dt,{"data-testid":"file-upload:wizard:assign-confirm",onClick:J,variant:"contained",disabled:ae,loading:P,children:"Assign"})]});case"create":return a.jsxs(a.Fragment,{children:[a.jsx(re,{"data-testid":"file-upload:wizard:create-cancel",onClick:G,color:"secondary",disabled:P,children:"Cancel"}),a.jsx(Dt,{"data-testid":"file-upload:wizard:create-confirm",onClick:H.handleSubmit(he),variant:"contained",disabled:!me,loading:P,children:"Create Data Source"})]});default:return null}},[t,e,J,G,he,X,K,ae,M,Y,r,P,me,H,l,g,v]),Me=m.useCallback(()=>{switch(v){case"progress":return a.jsx(rbe,{error:e,filename:D,message:n,percentage:b});case"summary":return a.jsx(sbe,{summaryData:C??null});case"assign":return a.jsx(ebe,{assignError:z,selectedDataSourceId:R,selectedOption:N,showCreateOption:y,onCreateOpen:ie,onDataSourceChange:V,onNoneSelect:le});case"create":return a.jsx(nbe,{methods:H});default:return null}},[z,e,D,V,le,ie,n,H,b,R,N,y,v,C]),q=je;return a.jsxs(yt,{"data-testid":"file-upload:wizard-dialog",fullWidth:!0,maxWidth:v==="summary"?"md":"sm",onClose:G,open:x,TransitionProps:{onExited:h},children:[q&&a.jsxs(vt,{sx:{alignItems:"center",display:"flex",justifyContent:"space-between"},children:[q,a.jsx(Ie,{onClick:G,size:"small",children:a.jsx(Mt,{children:a.jsx(Jt,{})})})]}),a.jsx(Ct,{sx:v==="progress"?{p:4}:void 0,children:Me()}),a.jsx(un,{sx:{px:3,py:2},children:ve})]})},lbe=()=>{const{clientNiceId:e,dispatch:t,engagementId:n,engagementNiceId:r,fileMetadataResponse:s,isLoadingMetadata:i,onGetS3DownloadUrl:o,onGetS3FileMetadataByInputUri:l,onTriggerPreview:c,refetchMetadata:d,state:u}=mg(),p=Zxe(),{fileUploadMpTrack:h}=Y2(),[f,g]=m.useState(!1),[x,b]=m.useState(null),[y,v]=m.useState(null),C=m.useRef(null),{startProgress:w,updateProgress:S,state:E,resetProgress:k}=Xxe(),[j]=qV(),[_]=gC(),D=m.useCallback(se=>s?.items?$xe(s.items,se)?.input_uri:void 0,[s]),{uploadFile:M,uploadState:N,uploadedFiles:O,error:R,pendingUpload:L,confirmOverride:P,proceedWithUpload:F,cancelUpload:z,reset:B}=Kxe({onUploadStart:se=>{w(se),p.setInputUri(se)},onUploadComplete:async(se,oe)=>{h("upload",{inputUri:se}),C.current=oe??null;try{await j({input_uri:se,datasource_id:oe??-1}).unwrap(),S(10,"Processing file...")}catch(te){We(te)}},onFindExistingFile:D}),{createDataSource:W}=Gxe({clientNiceId:e,engagementId:n,engagementNiceId:r,inputUri:L?.inputUri||p.inputUri,skipMoveFile:!0}),H=m.useCallback((se,oe)=>{t({type:"setActiveTab",value:oe})},[t]),V=m.useCallback(async(se,oe)=>{try{t({type:"setDownloadingFileId",value:se});const te=await o(oe);if(!te)return;if(h("download",{inputUri:oe}),te.output_file){const de=te.output_file.key.split("/").pop()||"output-file";dT(te.output_file.url,de)}te.input_file&&setTimeout(()=>{if(te.input_file){const de=te.input_file.key.split("/").pop()||"input-file";dT(te.input_file.url,de)}},100)}catch(te){We(te)}finally{t({type:"setDownloadingFileId",value:null})}},[o,t,h]),G=m.useCallback(async()=>{const{inputUri:se}=E;if(!se){We("No inputUri available after progress completion");return}g(!0),v(null);try{const oe=C.current;if(oe&&r)try{await _({datasource_id:oe,engagement_nice_id:r,input_uri:se}).unwrap(),C.current=null}catch(de){We(de),v("Could not assign the file to its data source. Please try again.");return}const te=await l(se);if(te?.items&&te.items.length>0){const de=te.items[0];de?.report?(await c(se,10),p.setSummaryData({columns:de.report.columns,created_at:de.created_at??de.report.created_at,file_type:de.report.file_type,header_mapping:de.report.header_mapping??{},header_row_index:de.report.header_row_index,metrics:de.report.metrics??{},notes:de.report.notes||[],shape:de.report.shape,status:de.status,input_uri:de.input_uri,error:de.error??null,warning:de.warning??null}),p.setInputUri(de.input_uri),d(),p.setStep("summary"),p.ensureOpen(),k()):We("File metadata missing report data")}else We("No file metadata found for inputUri")}catch(oe){We(oe)}finally{g(!1)}},[r,_,l,c,E,d,k,p]),X=m.useCallback(se=>{p.openWizard("assign",void 0,!1),p.setInputUri(se)},[p]),K=m.useCallback(()=>{d()},[d]),{deleteFile:ie}=Yxe({engagementNiceId:r,onDeleteSuccess:d}),le=m.useCallback((se,oe)=>{t({type:"setFileToDelete",value:{inputUri:se,fileName:oe}}
226),t({type:"setDeleteModalOpen",value:!0}),t({type:"setDeleteError",value:null})},[t]),ce=m.useCallback(()=>{t({type:"setDeleteModalOpen",value:!1}),t({type:"setFileToDelete",value:null}),t({type:"setDeleteError",value:null})},[t]),J=m.useCallback(async()=>{if(u.fileToDelete){t({type:"setDeleteError",value:null}),t({type:"setDeletingFileId",value:u.fileToDelete.inputUri});try{const se=await ie(u.fileToDelete.inputUri);if(se.success)h("delete",{inputUri:u.fileToDelete.inputUri,fileName:u.fileToDelete.fileName}),ce();else{const oe=se.error||"Failed to delete file";t({type:"setDeleteError",value:oe}),We(new Error(`Failed to delete file: ${u.fileToDelete.fileName} (${u.fileToDelete.inputUri}): ${oe}`))}}catch(se){const oe=se instanceof Error?se.message:"An unexpected error occurred";t({type:"setDeleteError",value:oe}),We(new Error(`Error deleting file: ${u.fileToDelete.fileName} (${u.fileToDelete.inputUri})`,{cause:se}))}finally{t({type:"setDeletingFileId",value:null})}}},[u.fileToDelete,ie,ce,t,h]),he=m.useCallback(async()=>{if(p.inputUri){t({type:"setDeletingFileId",value:p.inputUri});try{(await ie(p.inputUri)).success&&(h("cancel",{inputUri:p.inputUri}),p.closeWizard(),k())}finally{t({type:"setDeletingFileId",value:null})}}},[p,ie,t,k,h]),ne=m.useCallback(async()=>{t({type:"setIsConfirming",value:!0});try{if(L?.existingFileInputUri){const se=await ie(L.existingFileInputUri);if(!se.success){We(`Failed to delete existing file: ${se.error}`);return}}L&&h("override",{fileName:L.file.name,inputUri:L.inputUri}),P()}finally{t({type:"setIsConfirming",value:!1})}},[P,t,L,ie,h]),Y=m.useCallback(async se=>{const oe=L?.inputUri;oe&&p.setInputUri(oe),await F(se)},[L,F,p]),ae=m.useCallback(se=>{const oe=s?.items?.find(te=>te.input_uri===se);oe&&(h("preview",{inputUri:se}),c(se,10),p.openWizard("summary",oe,!1,!0))},[s?.items,c,p,h]),je=m.useMemo(()=>Wxe({downloadingFileId:u.downloadingFileId,onDeleteClick:le,onDownloadClick:V,onStatusClick:X,onViewClick:ae}),[u.downloadingFileId,le,V,X,ae]),me=m.useMemo(()=>s?.items?s.items:[],[s]),ve=m.useCallback(se=>{b(null),v(null),C.current=null,k(),B(),se.reduce((oe,te)=>oe.then(()=>(t({type:"setUploadingFileName",value:te.name}),M(te))),Promise.resolve())},[M,t,B,k]),Me=m.useCallback(se=>{k();const oe=se.map(Le=>Le.file.name),de=se[0]?.errors[0]?.code;let ke;de==="file-invalid-type"?ke=`Unsupported file type: ${oe.join(", ")}. Supported formats: ${gw}`:de==="file-too-large"?ke=`File too large: ${oe.join(", ")}. Maximum size: ${mw}`:ke=`Unable to upload: ${oe.join(", ")}. Please check file type and size.`,b(ke)},[k]),{getRootProps:q,getInputProps:Q,isDragActive:ee}=fw({onDrop:ve,onDropRejected:Me,accept:Axe,maxSize:Nxe,multiple:!0,disabled:N==="uploading"||N==="getting-url"||N==="awaiting-confirmation"||N==="awaiting-datasource"||E.isListening}),Ce=N==="uploading"||N==="getting-url"||N==="awaiting-confirmation"||N==="awaiting-datasource"||E.isListening;return a.jsxs(T,{"data-testid":"file-upload:page:container",p:3,children:[a.jsx(Ub,{open:u.deleteModalOpen,title:"Delete File?",message:a.jsxs(I,{children:["Are you sure you want to delete"," ",a.jsx(I,{component:"span",sx:{fontWeight:"bold",color:"primary.main"},children:u.fileToDelete?.fileName}),"? This action cannot be undone."]}),confirmationText:"DELETE",confirmButtonText:"Delete",confirmButtonColor:"error",cancelButtonText:"Cancel",isProcessing:u.deletingFileId===u.fileToDelete?.inputUri,errorMessage:u.deleteError||void 0,onClose:ce,onConfirm:J,maxWidth:"sm"}),a.jsx(Ub,{open:N==="awaiting-confirmation",title:"File Already Exists",message:a.jsxs(I,{children:["A file named"," ",a.jsx(I,{component:"span",sx:{fontWeight:"bold",color:"primary.main"},children:L?.file.name})," ","already exists at this location. Uploading will overwrite the existing file."]}),confirmationText:"OVERRIDE",confirmButtonText:"Override",confirmButtonColor:"warning",cancelButtonText:"Cancel",isProcessing:u.isConfirming,onClose:z,onConfirm:ne,maxWidth:"sm"}),a.jsx(obe,{open:p.isOpen||N==="awaiting-datasource"||E.isListening||E.isComplete,step:E.isListening||E.isComplete?"progress":N==="awaiting-datasource"?p.currentStep==="create"?"create":"assign":p.currentStep,percentage:E.progress,message:E.message,error:y??E.error,canRetryOnError:y!=null,summaryData:p.summaryData,inputUri:p.inputUri||L?.inputUri||"",showCreateOption:p.showCreateOption,isLoadingContinue:f,isPreUploadAssign:N==="awaiting-datasource",onCancelUpload:p.isViewOnl
226y?void 0:he,onClose:()=>{p.closeWizard(),k(),C.current=null,N==="awaiting-datasource"&&z()},onExited:()=>{p.resetWizardState()},onProgressContinue:G,onSummaryConfirm:void 0,onAssignSuccess:K,onCreateOpen:()=>p.setStep("create"),onBackToAssign:()=>p.setStep("assign"),onCreateDataSource:W,onDataSourceSelected:Y}),a.jsx(T,{mb:4,children:a.jsx(I,{variant:"h5",children:"File Uploads"})}),a.jsx(T,{sx:{borderBottom:1,borderColor:"divider",mb:3},children:a.jsxs(Vv,{value:u.activeTab,onChange:H,"aria-label":"file upload tabs",children:[a.jsx(_n,{"data-testid":"file-upload:tab:upload",label:"Upload",id:"file-upload-tab-0","aria-controls":"file-upload-tabpanel-0"}),a.jsx(_n,{"data-testid":"file-upload:tab:browse",label:"Browse",id:"file-upload-tab-1","aria-controls":"file-upload-tabpanel-1"})]})}),a.jsx(T,{role:"tabpanel",hidden:u.activeTab!==0,id:"file-upload-tabpanel-0","aria-labelledby":"file-upload-tab-0",children:u.activeTab===0&&a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{mb:3,minHeight:68},children:[(R||x)&&a.jsx(vn,{severity:"error",children:R||x}),!R&&!x&&O.length>0&&E.isComplete&&!E.error&&a.jsxs(vn,{severity:"success",children:["Successfully uploaded ",O.length," file",O.length>1?"s":"",":"," ",O.map(se=>se.name).join(", ")]})]}),a.jsx(Hxe,{getRootProps:q,getInputProps:Q,isDragActive:ee,isUploading:Ce}),a.jsx(Pxe,{})]})}),a.jsx(T,{role:"tabpanel",hidden:u.activeTab!==1,id:"file-upload-tabpanel-1","aria-labelledby":"file-upload-tab-1",children:u.activeTab===1&&a.jsx(T,{sx:{height:600,width:"100%"},children:a.jsx(G2,{columns:je,disableColumnPinning:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,getRowId:se=>se.input_uri,initialState:{pagination:{paginationModel:{pageSize:25}}},loading:i,pagination:!0,pageSizeOptions:[10,25,50,100],rows:me,slots:{loadingOverlay:Cs}})})})]})},cbe=()=>{const{engagementNiceId:e,engagementId:t,clientNiceId:n}=pe(),[r]=GV(),[s]=YV(),[i,{data:o}]=KV(),{data:l}=EA(e||"",{skip:!e}),c=m.useMemo(()=>l?l.map(x=>({id:x.id,name:Mr(x)})).sort((x,b)=>x.name.localeCompare(b.name)):[],[l]),{data:d,isLoading:u,refetch:p}=QV({engagement_nice_id:e||""},{skip:!e}),h=m.useCallback(async x=>{if(!e)return null;try{return await r({engagement_nice_id:e,input_uri:x}).unwrap()}catch{return null}},[e,r]),f=m.useCallback(async x=>{if(!e)return null;try{return await s({engagement_nice_id:e,input_uri:x}).unwrap()}catch(b){return We(new Error(`Failed to get S3 file metadata for engagement: ${e}, inputUri: ${x}`,{cause:b})),null}},[e,s]),g=m.useCallback(async(x,b=10)=>{e&&i({engagement_nice_id:e,input_uri:x,rows:b})},[e,i]);return a.jsx(Oge,{clientNiceId:n,dataSourceOptions:c,engagementId:t,engagementNiceId:e||"",fileMetadataResponse:d,isLoadingMetadata:u,previewData:o,refetchMetadata:p,onGetS3DownloadUrl:h,onGetS3FileMetadataByInputUri:f,onTriggerPreview:g,children:a.jsx(lbe,{})})},K2=m.createContext(void 0),gg=()=>{const e=m.useContext(K2);if(!e)throw new Error("useQueryStudioContext must be used within QueryStudioProvider");return e},dbe={activeTab:"0",savedQueryToLoad:null,loadKey:0,configVersion:0},ube=(e,t)=>{switch(t.type){case"activeTab":return{...e,activeTab:t.value};case"savedQueryToLoad":return{...e,savedQueryToLoad:t.value,loadKey:e.loadKey+1};case"clearSavedQueryToLoad":return{...e,savedQueryToLoad:null};case"incrementConfigVersion":return{...e,configVersion:e.configVersion+1};default:return e}},pbe=({children:e})=>{const[t,n]=m.useReducer(ube,dbe),r=m.useRef(!1),s=m.useMemo(()=>({state:t,dispatch:n,skipNextApiConfigReset:r}),[t]);return a.jsx(K2.Provider,{value:s,children:e})},hbe={changeTab:"Change Tab",deleteQuery:"Delete Query",executeQuery:"Execute Query",openSavedQuery:"Open Saved Query",overwriteQuery:"Overwrite Query",renameQuery:"Rename Query",saveQuery:"Save Query"},xw=()=>pr({actionMap:hbe,eventName:"queryStudio"}),fbe=({connectors:e,isLoading:t,disabled:n=!1})=>{const{control:r}=on();return a.jsx(Et,{control:r,name:"connector.type",render:({field:s,fieldState:{error:i}})=>a.jsx(Nt,{isLoading:t,width:"100%",children:a.jsxs(Qe,{disabled:n,fullWidth:!0,required:!0,children:[a.jsx(wt,{error:!!i,children:"Connector"}),a.jsx(tt,{...s,label:"Connector",disabled:t||e.length===0,renderValue:o=>{const l=e.find(c=>c.niceId===o);return l?a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[l.logoUrl?a.jsx(T,{sx:{mr:1},children:a.jsx(sa,{src:l.logoUrl})}):null,a.jsx("span",{children:l.name})]}):""},children:e.map(o=>a.jsx(Se,{value:o.niceId,children:a.jsxs(T,{sx:{display:"flex",alignItems:"center",gap:1},children:[o.logoUrl?a.jsx(sa,{src:o.logoUrl}):null,a.jsx("span",{children:o.name})]})},o.id))}),a.jsx(Zn,{error:!!i,children:i?.message||" "})]})})})},mbe="There are no available connections for the selected connector type",gbe=({connections:e,connectors:t,isLoading:n,disabled:r=!1})=>{const{control:s,watch:i,setValue:o}=on(),l=i("connector.type"),c=i("connection"),u=t.find(({niceId:f})=>f===l)?.name,p=m.useMemo(()=>e.filter(({connectorName:f})=>f===u),[e,u]);m.useEffect(()=>{if(n)return;!p.some(({id:g})=>g===c)&&c!==null&&o("connection",null)},[p,c,o,n]);const h=p.length===0;return a.jsx(Et,{control:s,name:"connection",render:({field:f,fieldState:{error:g}})=>{const x=!!g||h&&!!l;return a.jsx(Nt,{isLoading:n,width:"100%",children:a.jsxs(Qe,{disabled:r,fullWidth:!0,required:!0,children:[a.jsx(wt,{error:x,children:"Connection"}),a.jsx(tt,{...f,value:f.value||"",label:"Connection",disabled:n||h||!l,required:!0,children:p.map(b=>a.jsx(Se,{value:b.id,children:b.name},b.id))}),a.jsx(Zn,{error:x,children:h&&l?mbe:g?.message||" "})]})})}})},xbe=()=>{const{watch:e,setValue:t}=on(),n=e("startDate"),r=e("endDate"),s=i=>{const[o,l]=i,c=Z(),d=l&&l.isAfter(c,"day")?c:l;t("startDate",o??null),t("endDate",d??null)};return a.jsxs(T,{children:[a.jsxs(I,{variant:"subtitle2",sx:{mb:2,display:"flex",alignItems:"center",gap:.5},children:[a.jsx(au,{size:16}),"Date Range"]}),a.jsx(ts,{fullWidth:!0,value:[n??null,r??null],setValue:s,minDate:Z().subtract(8,"years"),maxDate:Z()})]})},bbe=({connectors:e})=>{const{watch:t,setValue:n}=on(),{skipNextApiConfigReset:r,state:s,dispatch:i}=gg(),o=t("connector.type"),l=m.useRef(void 0);m.useEffect(()=>{if(l.current!==void 0&&l.current!==o)if(r.current)r.current=!1;else{const d=e.find(({niceId:u})=>u===o);if(d?.globalConfig){const u={};d.globalConfig.forEach(p=>{"default"in p&&p.default!==void 0&&(u[p.name]=p.default)}),n("connector.apiConfig",u,{shouldValidate:!0})}else n("connector.apiConfig",{},{shouldValidate:!0});i({type:"incrementConfigVersion"})}l.current=o},[o,n,e,r,i]);
226const c=e.find(({niceId:d})=>d===o);return o?!c||c.diProcess!=="connector"||!c.globalConfig||c.globalConfig.length===0?null:a.jsxs(T,{sx:{pb:2},children:[a.jsxs(I,{variant:"subtitle2",sx:{mb:1,display:"flex",alignItems:"center",gap:.5},children:[a.jsx(sA,{size:16}),"Global Config"]}),a.jsx(FC,{fields:c.globalConfig,parentField:"connector.apiConfig"},`${o}-${s.configVersion}`)]}):a.jsx(I,{variant:"body2",color:"text.secondary",children:"Select a connector to view configuration options"})},ybe=({formData:e})=>{const{connector:t,startDate:n,endDate:r,connection:s}=e,i=m.useMemo(()=>{const l={};return t?.apiConfig&&(l.apiConfig=t.apiConfig),n&&(l.startDate=n.format("YYYY-MM-DD")),r&&(l.endDate=r.format("YYYY-MM-DD")),s&&(l.connectionId=s),l},[t,n,r,s]),o=m.useMemo(()=>JSON.stringify(i,null,2),[i]);return a.jsxs(T,{children:[a.jsx(I,{variant:"caption",sx:{color:"text.secondary",display:"block",mb:1},children:"API Request Body"}),a.jsx(T,{component:"pre",sx:{bgcolor:"background.default",p:2,borderRadius:1,overflow:"auto",maxHeight:300,fontSize:"0.875rem",fontFamily:"monospace",border:1,borderColor:"divider",m:0},children:a.jsx("code",{children:o})})]})},vbe=({formData:e})=>{const[t,n]=m.useState("api"),[r,s]=m.useState(!1),i=m.useRef(null),o=(c,d)=>{n(d)},l=async()=>{try{const c=JSON.stringify(e,null,2);await navigator.clipboard.writeText(c),s(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>s(!1),2e3)}catch(c){console.error("Failed to copy to clipboard:",c)}};return m.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),a.jsxs(Br,{variant:"outlined",sx:{borderColor:"grey.400",mt:2},children:[a.jsxs(T,{sx:{borderBottom:1,borderColor:"divider",display:"flex",alignItems:"center",justifyContent:"space-between",px:2},children:[a.jsxs(Vv,{value:t,onChange:o,children:[a.jsx(_n,{label:"API Request",value:"api",sx:{textTransform:"none",minHeight:48}}),a.jsx(_n,{label:"Summary",value:"summary",disabled:!0,sx:{textTransform:"none",minHeight:48}})]}),a.jsx(be,{title:r?"Copied!":"Copy",children:a.jsx(Ie,{size:"small",onClick:l,children:a.jsx(SU,{size:16})})})]}),a.jsxs(T,{sx:{p:2},children:[t==="api"&&a.jsx(ybe,{formData:e}),t==="summary"&&a.jsx(T,{sx:{color:"text.secondary",fontStyle:"italic"},children:"Summary coming soon"})]})]})},Q2=m.createContext(null),Cbe=()=>{const e=m.useContext(Q2);if(!e)throw new Error("useQueryEditorFormContext must be used within a QueryEditorFormContext.Provider");return e},wbe=({open:e,onClose:t,onConfirm:n,queryName:r})=>{const s=()=>{n(),t()};return a.jsxs(yt,{open:e,onClose:t,children:[a.jsx(vt,{children:"Overwrite Existing Query?"}),a.jsx(Ct,{children:a.jsxs(AD,{children:['A query named "',r,'" already exists for this engagement. Do you want to overwrite it?']})}),a.jsxs(un,{children:[a.jsx(re,{onClick:t,children:"Cancel"}),a.jsx(re,{onClick:s,variant:"contained",autoFocus:!0,children:"Overwrite"})]})]})},Sbe=({isFormComplete:e,isLoading:t})=>{const{handleExecuteQuery:n}=Cbe(),{pushNotification:r}=jt(),{register:s,watch:i,getValues:o}=on(),{engagementId:l}=pe(),[c,{isLoading:d}]=JV(),[u,p]=m.useState(!1),h=xw(),{data:f=[]}=zA({engagementId:l},{skip:!l}),x=i("queryName")?.trim()??"",b=m.useCallback(()=>{const k=o();return!x||!k.connector.type||!k.connection||!l?null:{name:x,engagement_id:l,connection_id:k.connection,api_config:k.connector.apiConfig||{},start_date:k.startDate?.format("YYYY-MM-DD")||"",end_date:k.endDate?.format("YYYY-MM-DD")||""}},[x,o,l]),y=m.useCallback(async()=>{const k=b();if(k)try{await c(k).unwrap(),r({content:"Query saved successfully",severity:"success",timeout:1e4})}catch{r({content:"Error saving query",severity:"error",timeout:1e4})}},[b,c,r]),v=m.useCallback(()=>{const k=o();return{connectorType:k.connector.type||void 0,connectionId:k.connection||void 0,queryName:x||void 0}},[o,x]),C=m.useCallback(()=>{if(!b())return;f.some(_=>_.name.toLowerCase()===x?.toLowerCase())?p(!0):(h("saveQuery",v()),y())},[b,y,v,h,x,f]),w=m.useCallback(()=>{h("overwriteQuery",v()),y()},[y,v,h]),S=m.useCallback(()=>{const k=o();h("executeQuery",{connectorType:k.connector.type||void 0,connectionId:k.connection||void 0}),n()},[o,n,h]),E=!x||!e||d;return a.jsxs(T,{sx:{display:"flex",gap:1.5,alignItems:"center",mb:2},children:[a.jsx(De,{...s("queryName"),label:"Query Name",size:"small",sx:{width:280},placeholder:""}),a.jsx(T,{sx:{flex:1}}),a.jsx(Dt,{variant:"contained",type:"button",size:"small",sx:{py:.5},onClick:C,loading:d,disabled:E,children:"Save Query"}),a.jsx(Dt,{variant:"contained",type:"button",size:"small",sx:{py:.5},onClick:S,loading:t,disabled:!e||t,children:"Execute Query"}),a.jsx(wbe,{open:u,onClose:()=>p(!1),onConfirm:w,queryName:x||""})]})},J2=480,jbe=38,uv=bs(Mn)(({theme:e})=>{const{background:t,border:n,text:r}=e.palette,{spacing:s}=e,i=e.palette.mode==="dark"?t.brand.subtle.hovered:t.brand.subtlest.default;return{border:"none",fontSize:13,[`.${xe.main}`]:{borderRadius:6,border:"1px solid",borderColor:n.default},[`.${xe.columnHeaders}`]:{backgroundColor:t.tableHeader,borderBottom:"none",minHeight:38},[`.${xe.columnHeader}`]:{paddingLeft:s(2),paddingRight:s(1),color:r.secondary,fontSize:12,fontWeight:600,letterSpacing:.4,textTransform:"uppercase",":focus":{outline:`2px solid ${e.palette.primary.main}`,outlineOffset:-2},":focus-within":{outline:`2px solid ${e.palette.primary.main}`,outlineOffset:-2}},[`.${xe.columnSeparator}`]:{color:n.default,":hover":{color:n.bold}},[`.${xe.row}`]:{transition:"background-color 120ms ease",":hover":{backgroundColor:i},"&:nth-of-type(even)":{backgroundColor:e.palette.mode==="dark"?"rgba(42, 39, 54, 0.9)":e.palette.neutral[50],"&:hover":{backgroundColor:e.palette.mode==="dark"?e.palette.neutral[700]:i}},"&:nth-of-type(odd)":{"&:hover":{backgroundColor:e.palette.mode==="dark"?e.palette.neutral[700]:i}}},[`.${xe.cell}`]:{borderBottom:"none",color:r.default,paddingLeft:s(2),paddingRight:s(1.5),"&:focus":{outline:`2px solid ${e.palette.primary.main}`,outlineOffset:-2},"&:focus-within":{outline:`2px solid ${e.palette.primary.main}`,outlineOffset:-2}},[`.${xe.virtualScroller}`]:{maxHeight:J2},[`.${xe.footerContainer}`]:{borderTop:"none",justifyContent:"flex-end",paddingRight:s(2),color:r.secondary}}});uv.defaultProps={...uv.defaultProps,columnHeaderHeight:jbe,disableRowSelectionOnClick:!0,pagination:!0,rowHeight:Mu};const kbe=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/_/g," ").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase()),pT=e=>e.toLowerCase().replace(/[_\s]+/g,""),Ebe=({dimensions:e,metrics:t,rows:n,loading:r=!1,isTruncated:s=!1,totalRowsParsed:i=0,downloadUrl:o=null})=>{const[l,c]=m.useState({pageSize:H0,page:0}),d=m.useMemo(()=>{const g=[...e??[],...t??[]];if(g.length>0){const b=n?.[0];if(b){const y=Object.keys(b),v=g.filter(C=>C in b);return v.length>0?v:y.filter(C=>C!=="id")}return g}const x=n?.[0];return x?Object.keys(x).filter(b=>b!=="id"):[]},[e,t,n]),u=m.useMemo(()=>d.map(g=>({field:g,headerName:kbe(g),flex:1,minWidth:140,valueGetter:x=>{const{row:b}=x;if(g in b)return b[g];const y=pT(g),v=Object.keys(b).find(C=>pT(C)===y);if(v)return b[v]}})),[d]),p=m.useMemo(()=>n&&n.length?n.map((g,x)=>g.id!==void 0?{id:g.id,...g}:{id:`${x}-${JSON.stringify(g).slice(0,50)}`,...g}):[],[n]),h=d.length>0,f=n!==void 0;return a.jsxs(Br,{variant:"outlined",sx:{borderColor:"grey.400",p:2},children:[a.jsx(I,{variant:"subtitle2",sx:{mb:1},children:"Results"}),h?!f&&!r?a.jsx(T,{sx:{py:6,textAlign:"center"},children:a.jsx(I,{color:"text.secondary",children:"Run a query to see results."})}):a.jsxs(a.Fragment,{children:[o&&a.jsx(T,{sx:{mb:2,display:"flex",justifyContent:"flex-end"},children:a.jsx(re,{size:"small",startIcon:a.jsx(jU,{}),href:o,download:!0,children:"Download Full File"})}),s&&a.jsxs(vn,{severity:"info",sx:{mb:2},children:["Showing ",i," rows (preview limited to prevent browser issues)"]}),a.jsx(T,{sx:{height:J2+64},children:a.jsx(uv,{columns:u,rows:p,loading:r,paginationModel:l,onPaginationModelChange:c,pageSizeOptions:GP,slots:{loadingOverlay:Cs,noRowsOverlay:ng}})})]}):a.jsx(T,{sx:{py:6,textAlign:"center"},children:a.jsx(I,{color:"text.secondary",children:"Select dimensions and metrics to preview your results table."})})]})},_be=({onSubmit:e,queryResults:t,resultsLoading:n=!1,isTruncated:r=!1,totalRowsParsed:s=0,downloadUrl:i=null})=>{const{engagementId:o}=pe(),{data:l=[],isLoading:c}=mu(),{data:d=[],isLoading:u}=fC({engagement_id:o,status:["authorized"]}),p=m.useMemo(()=>l.filter(C=>C.active&&C.authType==="oauth2.0").toSorted(({name:C},{name:w})=>C.toLocaleLowerCase().localeCompare(w.toLocaleLowerCase())),[l]),{handleSubmit:h,watch:f}
226=on(),g=f(),x=g.connector?.apiConfig,b=m.useMemo(()=>Array.isArray(x?.dimensions)?x.dimensions.filter(C=>typeof C=="string"):[],[x?.dimensions]),y=m.useMemo(()=>Array.isArray(x?.metrics)?x.metrics.filter(C=>typeof C=="string"):[],[x?.metrics]),v=m.useMemo(()=>({connector:{type:g.connector?.type??"",apiConfig:g.connector?.apiConfig??{}},startDate:g.startDate??null,endDate:g.endDate??null,connection:g.connection??null}),[g]);return a.jsx(T,{component:"form",onSubmit:h(e),children:a.jsxs(T,{sx:{display:"flex",gap:1.5,alignItems:"flex-start"},children:[a.jsxs(T,{sx:{width:280,flexShrink:0,display:"flex",flexDirection:"column",gap:1.5},children:[a.jsxs(Br,{variant:"outlined",sx:{borderColor:"grey.400",p:1.5},children:[a.jsxs(I,{variant:"subtitle2",sx:{mb:2,display:"flex",alignItems:"center",gap:.5},children:[a.jsx(PD,{size:16}),"Data Connection"]}),a.jsxs($,{spacing:2,children:[a.jsx(fbe,{connectors:p,isLoading:c}),a.jsx(gbe,{connections:d,connectors:p,isLoading:u})]}),a.jsx(St,{sx:{my:2}}),a.jsx(xbe,{})]}),a.jsxs(Br,{variant:"outlined",sx:{borderColor:"grey.400",p:1.5},children:[a.jsxs(I,{variant:"subtitle2",sx:{mb:1.5,display:"flex",alignItems:"center",gap:.5},children:[a.jsx(Zv,{size:16}),"Data Selection"]}),a.jsx(bbe,{connectors:p})]})]}),a.jsxs(T,{sx:{flex:1,minWidth:0},children:[a.jsx(Ebe,{dimensions:b,metrics:y,rows:t??void 0,loading:n,isTruncated:r,totalRowsParsed:s,downloadUrl:i}),a.jsx(vbe,{formData:v})]})]})})},Tbe=U.object({queryName:U.string().optional(),connector:U.object({type:U.string().min(1,"Connector is required"),apiConfig:qs.optional()}),connection:U.number().min(1,"Connection is required").nullable(),startDate:U.custom(Z.isDayjs,"Start date must be a valid date").nullable().optional(),endDate:U.custom(Z.isDayjs,"End date must be a valid date").nullable().optional()}),Ibe={queryName:"",connector:{type:"",apiConfig:{}},connection:null,startDate:null,endDate:null},Dbe=e=>typeof e=="string"?e:!e||typeof e!="object"?"Unknown error occurred":"data"in e&&e.data!==null&&typeof e.data=="object"&&"message"in e.data&&typeof e.data.message=="string"?e.data.message:"error"in e&&typeof e.error=="string"?e.error:"message"in e&&typeof e.message=="string"?e.message:"Unknown error occurred",Abe=()=>{const{engagementNiceId:e,engagementId:t}=pe(),[n,{isLoading:r}]=XV(),[s,i]=m.useState(null);return{executeQuery:m.useCallback(async l=>{i(null);try{if(!t)return i("No engagement found"),{success:!1,error:"No engagement found"};const c=new Date().toISOString().replace(/[-:T.Z]/g,"").slice(0,14),d=l.connector?.type||"unknown",u=l.connection?String(l.connection):"",p=`${d}_${e}_${u}_${c}`,h=l.startDate&&typeof l.startDate.format=="function"?l.startDate.format("YYYY-MM-DD"):"",f=l.endDate&&typeof l.endDate.format=="function"?l.endDate.format("YYYY-MM-DD"):"",g=l.connector?.apiConfig?[l.connector.apiConfig]:[];return{success:!0,data:await n({step_function_job_id:p,engagement_nice_id:e,engagement_id:t,delivery_method:d,connection_id:u,api_config:g,start_date:h,end_date:f}).unwrap(),jobId:p}}catch(c){const d=Dbe(c);return i(d),{success:!1,error:d}}},[e,t,n]),isExecuting:r,error:s}},Mbe=e=>{const{message:t}=fu("QueryStudio"),[n,r]=m.useState({status:"IDLE",jobId:null,filePrefix:null,s3Bucket:null,error:null});return m.useEffect(()=>{r({status:"IDLE",jobId:e,filePrefix:null,s3Bucket:null,error:null})},[e]),m.useEffect(()=>{if(!e||!t)return;const{error:s,filePrefix:i,s3Bucket:o,status:l,stepFunctionJobId:c}=t.data;e===c&&r({status:l,jobId:e,filePrefix:i,s3Bucket:o,error:s})},[t,e]),n};function Rbe(e){return{status:e,isUninitialized:e==="uninitialized",isLoading:e==="pending",isSuccess:e==="fulfilled",isError:e==="rejected"}}var hT=e=>[].concat(...e);function Nbe(){return typeof navigator>"u"||navigator.onLine===void 0?!0:navigator.onLine}function Obe(){return typeof document>"u"?!0:document.visibilityState!=="hidden"}var fT=Pb;function X2(e,t){if(e===t||!(fT(e)&&fT(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let s=n.length===r.length;const i=Array.isArray(t)?[]:{};for(const o of n)i[o]=X2(e[o],t[o]),s&&(s=e[o]===i[o]);return s?e:i}var mT=class{constructor(e,t=void 0){this.value=e,this.meta=t}},bw=wr("__rtkq/focused"),Z2=wr("__rtkq/unfocused"),yw=wr("__rtkq/online"),eF=wr("__rtkq/offline");function tF(e){return e.type==="query"}function Pbe(e){return e.type==="mutation"}function vw(e,t,n,r,s,i){return Lbe(e)?e(t,n,r,s).map(pv).map(i):Array.isArray(e)?e.map(pv).map(i):[]}function Lbe(e){return typeof e=="function"}function pv(e){return typeof e=="string"?{type:e}:e}function gT(e){return e!=null}function Jo(e){let t=0;for(const n in e)t++;return t}function Fbe(e,t){return e.catch(t)}var eu=Symbol("forceQueryFn"),hv=e=>typeof e[eu]=="function";function $be({serializeQueryArgs:e,queryThunk:t,mutationThunk:n,api:r,context:s}){const i=new Map,o=new Map,{unsubscribeQueryResult:l,removeMutationResult:c,updateSubscriptionOptions:d}=r.internalActions;return{buildInitiateQuery:g,buildInitiateMutation:x,getRunningQueryThunk:u,getRunningMutationThunk:p,getRunningQueriesThunk:h,getRunningMutationsThunk:f};function u(b,y){return v=>{const C=s.endpointDefinitions[b],w=e({queryArgs:y,endpointDefinition:C,endpointName:b});return i.get(v)?.[w]}}function p(b,y){return v=>o.get(v)?.[y]}function h(){return b=>Object.values(i.get(b)||{}).filter(gT)}function f(){return b=>Object.values(o.get(b)||{}).filter(gT)}function g(b,y){const v=(C,{subscribe:w=!0,forceRefetch:S,subscriptionOptions:E,[eu]:k,...j}={})=>(_,D)=>{const M=e({queryArgs:C,endpointDefinition:y,endpointName:b}),N=t({...j,type:"query",subscribe:w,forceRefetch:S,subscriptionOptions:E,endpointName:b,originalArgs:C,queryCacheKey:M,[eu]:k}),O=r.endpoints[b].select(C),R=_(N),L=O(D()),{requestId:P,abort:F}=R,z=L.requestId!==P,B=i.get(_)?.[M],W=()=>O(D()),H=Object.assign(k?R.then(W):z&&!B?Promise.resolve(L):Promise.all([B,R]).then(W),{arg:C,requestId:P,subscriptionOptions:E,queryCacheKey:M,abort:F,async unwrap(){const V=await H;if(V.isError)throw V.error;return V.data},refetch:()=>_(v(C,{subscribe:!1,forceRefetch:!0})),unsubscribe(){w&&_(l({queryCacheKey:M,requestId:P}))},updateSubscriptionOptions(V){H.subscriptionOptions=V,_(d({endpointName:b,requestId:P,queryCacheKey:M,options:V}))}});if(!B&&!z&&!k){const V=i.get(_)||{};V[M]=H,i.set(_,V),H.then(()=>{delete V[M],Jo(V)||i.delete(_)})}return H};return v}function x(b){return(y,{track:v=!0,fixedCacheKey:C}={})=>(w,S)=>{const E=n({type:"mutation",endpointName:b,originalArgs:y,track:v,fixedCacheKey:C}),k=w(E),{requestId:j,abort:_,unwrap:D}=k,M=Fbe(k.unwrap().then(L=>({data:L})),L=>({error:L})),N=()=>{w(c({requestId:j,fixedCacheKey:C}))},O=Object.assign(M,{arg:k.arg,requestId:j,abort:_,unwrap:D,reset:N}),R=o.get(w)||{};return o.set(w,R),R[j]=O,O.then(()=>{delete R[j],Jo(R)||o.delete(w)}),C&&(R[C]=O,O.then(()=>{R[C]===O&&(delete R[C],Jo(R)||o.delete(w))})),O}}}function xT(e){return e}function zbe({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:s,assertTagType:i}){const o=(v,C,w,S)=>(E,k)=>{const j=n[v],_=r({queryArgs:C,endpointDefinition:j,endpointName:v});if(E(s.internalActions.queryResultPatched({queryCacheKey:_,patches:w})),!S)return;const D=s.endpoints[v].select(C)(k()),M=vw(j.providesTags,D.data,void 0,C,{},i);E(s.internalActions.updateProvidedBy({queryCacheKey:_,providedTags:M}))},l=(v,C,w,S=!0)=>(E,k)=>{const _=s.endpoints[v].select(C)(k());let D={patches:[],inversePatches:[],undo:()=>E(s.util.patchQueryData(v,C,D.inversePatches,S))};if(_.status==="uninitialized")return D;let M;if("data"in _)if(aC(_.data)){const[N,O,R]=BA(_.data,w);D.patches.push(...O),D.inversePatches.push(...R),M=N}else M=w(_.data),D.patches.push({op:"replace",path:[],value:M}),D.inversePatches.push({op:"replace",path:[],value:_.data});return D.patches.length===0||E(s.util.patchQueryData(v,C,D.patches,S)),D},c=(v,C,w)=>S=>S(s.endpoints[v].initiate(C,{subscribe:!1,forceRefetch:!0,[eu]:()=>({data:w})})),d=async(v,{signal:C,abort:w,rejectWithValue:S,fulfillWithValue:E,dispatch:k,getState:j,extra:_})=>{const D=n[v.endpointName];try{let M=xT,N;const O={signal:C,abort:w,dispatch:k,getState:j,extra:_,endpoint:v.endpointName,type:v.type,forced:v.type==="query"?u(v,j()):void 0},R=v.type==="query"?v[eu]:void 0;if(R?N=R():D.query?(N=await t(D.query(v.originalArgs),O,D.extraOptions),D.transformResponse&&(M=D.transformResponse)):N=await D.queryFn(v.originalArgs,O,D.extraOptions,L=>t(L,O,D.extraOptions)),typeof process<"u",N.error)throw new mT(N.error,N.meta);return E(await M(N.data,N.meta,v.originalArgs),{fulfilledTimeStamp:Date.now(),baseQueryMeta:N.meta,[nd]:!0})}catch(M){let N=M;if(N instanceof mT){let O=xT;D.query&&D.transformErrorResponse&&(O=D.transformErrorResponse);try{return S(await O(N.value,N.meta,v.originalArgs),{baseQueryMeta:N.meta,[nd]:!0})}catch(R){N=R}}throw console.error(N),N}};function u(v,C){const w=C[e]?.queries?.[v.queryCacheKey],S=C[e]?.config.refetchOnMountOrArgChange,E=w?.fulfilledTimeStamp,k=v.forceRefetch??(v.subscribe&&S);return k?k===!0||(Number(new Date)-Number(E))/1e3>=k:!1}const p=qj(`${e}/executeQuery`,d,{getPendingMeta(){return{startedTimeStamp:Date.now(),[nd]:!0}},condition(v,{getState:C}){const w=C(),S=w[e]?.queries?.[v.queryCacheKey],E=S?.fulfilledTimeStamp,k=v.originalArgs,j=S?.originalArgs,_=n[v.endpointName];return hv(v)?!0:S?.status==="pending"?!1:u(v,w)||tF(_)&&_?.forceRefetch?.({currentArg:k,previousArg:j,endpointState:S,state:w})?!0:!E},dispatchConditionRejection:!0}
226),h=qj(`${e}/executeMutation`,d,{getPendingMeta(){return{startedTimeStamp:Date.now(),[nd]:!0}}}),f=v=>"force"in v,g=v=>"ifOlderThan"in v,x=(v,C,w)=>(S,E)=>{const k=f(w)&&w.force,j=g(w)&&w.ifOlderThan,_=(M=!0)=>{const N={forceRefetch:M,isPrefetch:!0};return s.endpoints[v].initiate(C,N)},D=s.endpoints[v].select(C)(E());if(k)S(_());else if(j){const M=D?.fulfilledTimeStamp;if(!M){S(_());return}(Number(new Date)-Number(new Date(M)))/1e3>=j&&S(_())}else S(_(!1))};function b(v){return C=>C?.meta?.arg?.endpointName===v}function y(v,C){return{matchPending:hd(DC(v),b(C)),matchFulfilled:hd(ra(v),b(C)),matchRejected:hd(il(v),b(C))}}return{queryThunk:p,mutationThunk:h,prefetch:x,updateQueryData:l,upsertQueryData:c,patchQueryData:o,buildMatchThunkActions:y}}function nF(e,t,n,r){return vw(n[e.meta.arg.endpointName][t],ra(e)?e.payload:void 0,Am(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function Np(e,t,n){const r=e[t];r&&n(r)}function tu(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function bT(e,t,n){const r=e[tu(t)];r&&n(r)}var Dc={};function Bbe({reducerPath:e,queryThunk:t,mutationThunk:n,context:{endpointDefinitions:r,apiUid:s,extractRehydrationInfo:i,hasRehydrationInfo:o},assertTagType:l,config:c}){const d=wr(`${e}/resetApiState`),u=To({name:`${e}/queries`,initialState:Dc,reducers:{removeQueryResult:{reducer(C,{payload:{queryCacheKey:w}}){delete C[w]},prepare:Ql()},queryResultPatched:{reducer(C,{payload:{queryCacheKey:w,patches:S}}){Np(C,w,E=>{E.data=Ij(E.data,S.concat())})},prepare:Ql()}},extraReducers(C){C.addCase(t.pending,(w,{meta:S,meta:{arg:E}})=>{const k=hv(E);w[E.queryCacheKey]??={status:"uninitialized",endpointName:E.endpointName},Np(w,E.queryCacheKey,j=>{j.status="pending",j.requestId=k&&j.requestId?j.requestId:S.requestId,E.originalArgs!==void 0&&(j.originalArgs=E.originalArgs),j.startedTimeStamp=S.startedTimeStamp})}).addCase(t.fulfilled,(w,{meta:S,payload:E})=>{Np(w,S.arg.queryCacheKey,k=>{if(k.requestId!==S.requestId&&!hv(S.arg))return;const{merge:j}=r[S.arg.endpointName];if(k.status="fulfilled",j)if(k.data!==void 0){const{fulfilledTimeStamp:_,arg:D,baseQueryMeta:M,requestId:N}=S;let O=pu(k.data,R=>j(R,E,{arg:D.originalArgs,baseQueryMeta:M,fulfilledTimeStamp:_,requestId:N}));k.data=O}else k.data=E;else k.data=r[S.arg.endpointName].structuralSharing??!0?X2(oC(k.data)?t3(k.data):k.data,E):E;delete k.error,k.fulfilledTimeStamp=S.fulfilledTimeStamp})}).addCase(t.rejected,(w,{meta:{condition:S,arg:E,requestId:k},error:j,payload:_})=>{Np(w,E.queryCacheKey,D=>{if(!S){if(D.requestId!==k)return;D.status="rejected",D.error=_??j}})}).addMatcher(o,(w,S)=>{const{queries:E}=i(S);for(const[k,j]of Object.entries(E))(j?.status==="fulfilled"||j?.status==="rejected")&&(w[k]=j)})}}),p=To({name:`${e}/mutations`,initialState:Dc,reducers:{removeMutationResult:{reducer(C,{payload:w}){const S=tu(w);S in C&&delete C[S]},prepare:Ql()}},extraReducers(C){C.addCase(n.pending,(w,{meta:S,meta:{requestId:E,arg:k,startedTimeStamp:j}})=>{k.track&&(w[tu(S)]={requestId:E,status:"pending",endpointName:k.endpointName,startedTimeStamp:j})}).addCase(n.fulfilled,(w,{payload:S,meta:E})=>{E.arg.track&&bT(w,E,k=>{k.requestId===E.requestId&&(k.status="fulfilled",k.data=S,k.fulfilledTimeStamp=E.fulfilledTimeStamp)})}).addCase(n.rejected,(w,{payload:S,error:E,meta:k})=>{k.arg.track&&bT(w,k,j=>{j.requestId===k.requestId&&(j.status="rejected",j.error=S??E)})}).addMatcher(o,(w,S)=>{const{mutations:E}=i(S);for(const[k,j]of Object.entries(E))(j?.status==="fulfilled"||j?.status==="rejected")&&k!==j?.requestId&&(w[k]=j)})}}),h=To({name:`${e}/invalidation`,initialState:Dc,reducers:{updateProvidedBy:{reducer(C,w){const{queryCacheKey:S,providedTags:E}=w.payload;for(const k of Object.values(C))for(const j of Object.values(k)){const _=j.indexOf(S);_!==-1&&j.splice(_,1)}for(const{type:k,id:j}of E){const _=(C[k]??={})[j||"__internal_without_id"]??=[];_.includes(S)||_.push(S)}},prepare:Ql()}},extraReducers(C){C.addCase(u.actions.removeQueryResult,(w,{payload:{queryCacheKey:S}})=>{for(const E of Object.values(w))for(const k of Object.values(E)){const j=k.indexOf(S);j!==-1&&k.splice(j,1)}}).addMatcher(o,(w,S)=>{const{provided:E}=i(S);for(const[k,j]of Object.entries(E))for(const[_,D]of Object.entries(j)){const M=(w[k]??={})[_||"__internal_without_id"]??=[];for(const N of D)M.includes(N)||M.push(N)}}).addMatcher(vi(ra(t),Am(t)),(w,S)=>{const E=nF(S,"providesTags",r,l),{queryCacheKey:k}=S.meta.arg;h.caseReducers.updateProvidedBy(w,h.actions.updateProvidedBy({queryCacheKey:k,providedTags:E}))})}}),f=To({name:`${e}/subscriptions`,initialState:Dc,reducers:{updateSubscriptionOptions(C,w){},unsubscribeQueryResult(C,w){},internal_getRTKQSubscriptions(){}}}),g=To({name:`${e}/internalSubscriptions`,initialState:Dc,reducers:{subscriptionsUpdated:{reducer(C,w){return Ij(C,w.payload)},prepare:Ql()}}}),x=To({name:`${e}/config`,initialState:{online:Nbe(),focused:Obe(),middlewareRegistered:!1,...c},reducers:{middlewareRegistered(C,{payload:w}){C.middlewareRegistered=C.middlewareRegistered==="conflict"||s!==w?"conflict":!0}},extraReducers:C=>{C.addCase(yw,w=>{w.online=!0}).addCase(eF,w=>{w.online=!1}).addCase(bw,w=>{w.focused=!0}).addCase(Z2,w=>{w.focused=!1}).addMatcher(o,w=>({...w}))}}),b=e3({queries:u.reducer,mutations:p.reducer,provided:h.reducer,subscriptions:g.reducer,config:x.reducer}),y=(C,w)=>b(d.match(w)?void 0:C,w),v={...x.actions,...u.actions,...f.actions,...g.actions,...p.actions,...h.actions,resetApiState:d};return{reducer:y,actions:v}}var Eh=Symbol.for("RTKQ/skipToken"),rF={status:"uninitialized"},yT=pu(rF,()=>{}),vT=pu(rF,()=>{});function Ube({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=p=>yT,s=p=>vT;return{buildQuerySelector:l,buildMutationSelector:c,selectInvalidatedBy:d,selectCachedArgsForQuery:u};function i(p){return{...p,...Rbe(p.status)}}function o(p){return p[t]}function l(p,h){return f=>{const g=e({queryArgs:f,endpointDefinition:h,endpointName:p});
226return n(f===Eh?r:y=>o(y)?.queries?.[g]??yT,i)}}function c(){return p=>{let h;return typeof p=="object"?h=tu(p)??Eh:h=p,n(h===Eh?s:x=>o(x)?.mutations?.[h]??vT,i)}}function d(p,h){const f=p[t],g=new Set;for(const x of h.map(pv)){const b=f.provided[x.type];if(!b)continue;let y=(x.id!==void 0?b[x.id]:hT(Object.values(b)))??[];for(const v of y)g.add(v)}return hT(Array.from(g.values()).map(x=>{const b=f.queries[x];return b?[{queryCacheKey:x,endpointName:b.endpointName,originalArgs:b.originalArgs}]:[]}))}function u(p,h){return Object.values(p[t].queries).filter(f=>f?.endpointName===h&&f.status!=="uninitialized").map(f=>f.originalArgs)}}var CT=WeakMap?new WeakMap:void 0,wT=({endpointName:e,queryArgs:t})=>{let n="";const r=CT?.get(t);if(typeof r=="string")n=r;else{const s=JSON.stringify(t,(i,o)=>Pb(o)?Object.keys(o).sort().reduce((l,c)=>(l[c]=o[c],l),{}):o);Pb(t)&&CT?.set(t,s),n=s}return`${e}(${n})`};function Vbe(...e){return function(n){const r=Ob(d=>n.extractRehydrationInfo?.(d,{reducerPath:n.reducerPath??"api"})),s={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...n,extractRehydrationInfo:r,serializeQueryArgs(d){let u=wT;if("serializeQueryArgs"in d.endpointDefinition){const p=d.endpointDefinition.serializeQueryArgs;u=h=>{const f=p(h);return typeof f=="string"?f:wT({...h,queryArgs:f})}}else n.serializeQueryArgs&&(u=n.serializeQueryArgs);return u(d)},tagTypes:[...n.tagTypes||[]]},i={endpointDefinitions:{},batch(d){d()},apiUid:IC(),extractRehydrationInfo:r,hasRehydrationInfo:Ob(d=>r(d)!=null)},o={injectEndpoints:c,enhanceEndpoints({addTagTypes:d,endpoints:u}){if(d)for(const p of d)s.tagTypes.includes(p)||s.tagTypes.push(p);if(u)for(const[p,h]of Object.entries(u))typeof h=="function"?h(i.endpointDefinitions[p]):Object.assign(i.endpointDefinitions[p]||{},h);return o}},l=e.map(d=>d.init(o,s,i));function c(d){const u=d.endpoints({query:p=>({...p,type:"query"}),mutation:p=>({...p,type:"mutation"})});for(const[p,h]of Object.entries(u)){if(d.overrideExisting!==!0&&p in i.endpointDefinitions){if(d.overrideExisting==="throw")throw new Error(Dr(39));continue}i.endpointDefinitions[p]=h;for(const f of l)f.injectEndpoint(p,h)}return o}return o.injectEndpoints({endpoints:n.endpoints})}}function Wbe(e){for(let t in e)return!1;return!0}var Hbe=2147483647/1e3-1,qbe=({reducerPath:e,api:t,queryThunk:n,context:r,internalState:s})=>{const{removeQueryResult:i,unsubscribeQueryResult:o}=t.internalActions,l=vi(o.match,n.fulfilled,n.rejected);function c(h){const f=s.currentSubscriptions[h];return!!f&&!Wbe(f)}const d={},u=(h,f,g)=>{if(l(h)){const x=f.getState()[e],{queryCacheKey:b}=o.match(h)?h.payload:h.meta.arg;p(b,x.queries[b]?.endpointName,f,x.config)}if(t.util.resetApiState.match(h))for(const[x,b]of Object.entries(d))b&&clearTimeout(b),delete d[x];if(r.hasRehydrationInfo(h)){const x=f.getState()[e],{queries:b}=r.extractRehydrationInfo(h);for(const[y,v]of Object.entries(b))p(y,v?.endpointName,f,x.config)}};function p(h,f,g,x){const y=r.endpointDefinitions[f]?.keepUnusedDataFor??x.keepUnusedDataFor;if(y===1/0)return;const v=Math.max(0,Math.min(y,Hbe));if(!c(h)){const C=d[h];C&&clearTimeout(C),d[h]=setTimeout(()=>{c(h)||g.dispatch(i({queryCacheKey:h})),delete d[h]},v*1e3)}}return u},Gbe=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:s,api:i,assertTagType:o,refetchQuery:l,internalState:c})=>{const{removeQueryResult:d}=i.internalActions,u=vi(ra(r),Am(r)),p=vi(ra(r,s),il(r,s));let h=[];const f=(b,y)=>{u(b)?x(nF(b,"invalidatesTags",n,o),y):p(b)?x([],y):i.util.invalidateTags.match(b)&&x(vw(b.payload,void 0,void 0,void 0,void 0,o),y)};function g(b){for(const y in b.queries)if(b.queries[y]?.status==="pending")return!0;for(const y in b.mutations)if(b.mutations[y]?.status==="pending")return!0;return!1}function x(b,y){const v=y.getState(),C=v[e];
226if(h.push(...b),C.config.invalidationBehavior==="delayed"&&g(C))return;const w=h;if(h=[],w.length===0)return;const S=i.util.selectInvalidatedBy(v,w);t.batch(()=>{const E=Array.from(S.values());for(const{queryCacheKey:k}of E){const j=C.queries[k],_=c.currentSubscriptions[k]??{};j&&(Jo(_)===0?y.dispatch(d({queryCacheKey:k})):j.status!=="uninitialized"&&y.dispatch(l(j,k)))}})}return f},Ybe=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:s})=>{const i={},o=(h,f)=>{(n.internalActions.updateSubscriptionOptions.match(h)||n.internalActions.unsubscribeQueryResult.match(h))&&c(h.payload,f),(t.pending.match(h)||t.rejected.match(h)&&h.meta.condition)&&c(h.meta.arg,f),(t.fulfilled.match(h)||t.rejected.match(h)&&!h.meta.condition)&&l(h.meta.arg,f),n.util.resetApiState.match(h)&&u()};function l({queryCacheKey:h},f){const g=f.getState()[e],x=g.queries[h],b=s.currentSubscriptions[h];if(!x||x.status==="uninitialized")return;const{lowestPollingInterval:y,skipPollingIfUnfocused:v}=p(b);if(!Number.isFinite(y))return;const C=i[h];C?.timeout&&(clearTimeout(C.timeout),C.timeout=void 0);const w=Date.now()+y;i[h]={nextPollTimestamp:w,pollingInterval:y,timeout:setTimeout(()=>{(g.config.focused||!v)&&f.dispatch(r(x,h)),l({queryCacheKey:h},f)},y)}}function c({queryCacheKey:h},f){const x=f.getState()[e].queries[h],b=s.currentSubscriptions[h];if(!x||x.status==="uninitialized")return;const{lowestPollingInterval:y}=p(b);if(!Number.isFinite(y)){d(h);return}const v=i[h],C=Date.now()+y;(!v||C<v.nextPollTimestamp)&&l({queryCacheKey:h},f)}function d(h){const f=i[h];f?.timeout&&clearTimeout(f.timeout),delete i[h]}function u(){for(const h of Object.keys(i))d(h)}function p(h={}){let f=!1,g=Number.POSITIVE_INFINITY;for(let x in h)h[x].pollingInterval&&(g=Math.min(h[x].pollingInterval,g),f=h[x].skipPollingIfUnfocused||f);return{lowestPollingInterval:g,skipPollingIfUnfocused:f}}return o},Kbe=({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:s})=>{const{removeQueryResult:i}=n.internalActions,o=(c,d)=>{bw.match(c)&&l(d,"refetchOnFocus"),yw.match(c)&&l(d,"refetchOnReconnect")};function l(c,d){const u=c.getState()[e],p=u.queries,h=s.currentSubscriptions;t.batch(()=>{for(const f of Object.keys(h)){const g=p[f],x=h[f];if(!x||!g)continue;(Object.values(x).some(y=>y[d]===!0)||Object.values(x).every(y=>y[d]===void 0)&&u.config[d])&&(Jo(x)===0?c.dispatch(i({queryCacheKey:f})):g.status!=="uninitialized"&&c.dispatch(r(g,f)))}})}return o},ST=new Error("Promise never resolved before cacheEntryRemoved."),Qbe=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:s,internalState:i})=>{const o=zb(r),l=zb(s),c=ra(r,s),d={},u=(f,g,x)=>{const b=p(f);if(r.pending.match(f)){const y=x[t].queries[b],v=g.getState()[t].queries[b];!y&&v&&h(f.meta.arg.endpointName,f.meta.arg.originalArgs,b,g,f.meta.requestId)}else if(s.pending.match(f))g.getState()[t].mutations[b]&&h(f.meta.arg.endpointName,f.meta.arg.originalArgs,b,g,f.meta.requestId);else if(c(f)){const y=d[b];y?.valueResolved&&(y.valueResolved({data:f.payload,meta:f.meta.baseQueryMeta}),delete y.valueResolved)}else if(e.internalActions.removeQueryResult.match(f)||e.internalActions.removeMutationResult.match(f)){const y=d[b];y&&(delete d[b],y.cacheEntryRemoved())}else if(e.util.resetApiState.match(f))for(const[y,v]of Object.entries(d))delete d[y],v.cacheEntryRemoved()};function p(f){return o(f)?f.meta.arg.queryCacheKey:l(f)?f.meta.arg.fixedCacheKey??f.meta.requestId:e.internalActions.removeQueryResult.match(f)?f.payload.queryCacheKey:e.internalActions.removeMutationResult.match(f)?tu(f.payload):""}function h(f,g,x,b,y){const v=n.endpointDefinitions[f],C=v?.onCacheEntryAdded;if(!C)return;let w={};const S=new Promise(M=>{w.cacheEntryRemoved=M}),E=Promise.race([new Promise(M=>{w.valueResolved=M}),S.then(()=>{throw ST})]);E.catch(()=>{}),d[x]=w;const k=e.endpoints[f].select(v.type==="query"?g:x),j=b.dispatch((M,N,O)=>O),_={...b,getCacheEntry:()=>k(b.getState()),requestId:y,extra:j,updateCachedData:v.type==="query"?M=>b.dispatch(e.util.updateQueryData(f,g,M)):void 0,cacheDataLoaded:E,cacheEntryRemoved:S},D=C(g,_);Promise.resolve(D).catch(M=>
226{if(M!==ST)throw M})}return u},Jbe=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const s=DC(n,r),i=il(n,r),o=ra(n,r),l={};return(d,u)=>{if(s(d)){const{requestId:p,arg:{endpointName:h,originalArgs:f}}=d.meta,g=t.endpointDefinitions[h],x=g?.onQueryStarted;if(x){const b={},y=new Promise((S,E)=>{b.resolve=S,b.reject=E});y.catch(()=>{}),l[p]=b;const v=e.endpoints[h].select(g.type==="query"?f:p),C=u.dispatch((S,E,k)=>k),w={...u,getCacheEntry:()=>v(u.getState()),requestId:p,extra:C,updateCachedData:g.type==="query"?S=>u.dispatch(e.util.updateQueryData(h,f,S)):void 0,queryFulfilled:y};x(f,w)}}else if(o(d)){const{requestId:p,baseQueryMeta:h}=d.meta;l[p]?.resolve({data:d.payload,meta:h}),delete l[p]}else if(i(d)){const{requestId:p,rejectedWithValue:h,baseQueryMeta:f}=d.meta;l[p]?.reject({error:d.payload??d.error,isUnhandledError:!h,meta:f}),delete l[p]}}},Xbe=({api:e,context:{apiUid:t},reducerPath:n})=>(r,s)=>{e.util.resetApiState.match(r)&&s.dispatch(e.internalActions.middlewareRegistered(t))},Zbe=({api:e,queryThunk:t,internalState:n})=>{const r=`${e.reducerPath}/subscriptions`;let s=null,i=null;const{updateSubscriptionOptions:o,unsubscribeQueryResult:l}=e.internalActions,c=(f,g)=>{if(o.match(g)){const{queryCacheKey:b,requestId:y,options:v}=g.payload;return f?.[b]?.[y]&&(f[b][y]=v),!0}if(l.match(g)){const{queryCacheKey:b,requestId:y}=g.payload;return f[b]&&delete f[b][y],!0}if(e.internalActions.removeQueryResult.match(g))return delete f[g.payload.queryCacheKey],!0;if(t.pending.match(g)){const{meta:{arg:b,requestId:y}}=g,v=f[b.queryCacheKey]??={};return v[`${y}_running`]={},b.subscribe&&(v[y]=b.subscriptionOptions??v[y]??{}),!0}let x=!1;if(t.fulfilled.match(g)||t.rejected.match(g)){const b=f[g.meta.arg.queryCacheKey]||{},y=`${g.meta.requestId}_running`;x||=!!b[y],delete b[y]}if(t.rejected.match(g)){const{meta:{condition:b,arg:y,requestId:v}}=g;if(b&&y.subscribe){const C=f[y.queryCacheKey]??={};C[v]=y.subscriptionOptions??C[v]??{},x=!0}}return x},d=()=>n.currentSubscriptions,h={getSubscriptions:d,getSubscriptionCount:f=>{const x=d()[f]??{};return Jo(x)},isRequestSubscribed:(f,g)=>!!d()?.[f]?.[g]};return(f,g)=>{if(s||(s=JSON.parse(JSON.stringify(n.currentSubscriptions))),e.util.resetApiState.match(f))return s=n.currentSubscriptions={},i=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(f))return[!1,h];const x=c(n.currentSubscriptions,f);let b=!0;if(x){i||(i=setTimeout(()=>{const C=JSON.parse(JSON.stringify(n.currentSubscriptions)),[,w]=BA(s,()=>C);g.next(e.internalActions.subscriptionsUpdated(w)),s=C,i=null},500));const y=typeof f.type=="string"&&!!f.type.startsWith(r),v=t.rejected.match(f)&&f.meta.condition&&!!f.meta.arg.subscribe;b=!y&&!v}return[b,!1]}};function eye(e){const{reducerPath:t,queryThunk:n,api:r,context:s}=e,{apiUid:i}=s,o={invalidateTags:wr(`${t}/invalidateTags`)},l=p=>p.type.startsWith(`${t}/`),c=[Xbe,qbe,Gbe,Ybe,Qbe,Jbe];return{middleware:p=>{let h=!1;const g={...e,internalState:{currentSubscriptions:{}},refetchQuery:u,isThisApiSliceAction:l},x=c.map(v=>v(g)),b=Zbe(g),y=Kbe(g);return v=>C=>{if(!gA(C))return v(C);h||(h=!0,p.dispatch(r.internalActions.middlewareRegistered(i)));const w={...p,next:v},S=p.getState(),[E,k]=b(C,w,S);let j;if(E?j=v(C):j=k,p.getState()[t]&&(y(C,w,S),l(C)||s.hasRehydrationInfo(C)))for(let _ of x)_(C,w,S);return j}},actions:o};function u(p,h,f={}){return n({type:"query",endpointName:p.endpointName,originalArgs:p.originalArgs,subscribe:!1,forceRefetch:!0,queryCacheKey:h,...f})}}function Ai(e,...t){return Object.assign(e,...t)}var jT=Symbol(),tye=({createSelector:e=Oi}={})=>({name:jT,init(t,{baseQuery:n,tagTypes:r,reducerPath:s,serializeQueryArgs:i,keepUnusedDataFor:o,refetchOnMountOrArgChange:l,refetchOnFocus:c,refetchOnReconnect:d,invalidationBehavior:u},p){ZV();const h=z=>z;Object.assign(t,{reducerPath:s,endpoints:{},internalActions:{onOnline:yw,onOffline:eF,onFocus:bw,onFocusLost:Z2},util:{}});const{queryThunk:f,mutationThunk:g,patchQueryData:x,updateQueryData:b,upsertQueryData:y,prefetch:v,buildMatchThunkActions:C}=zbe({baseQuery:n,reducerPath:s,context:p,api:t,serializeQueryArgs:i,assertTagType:h}),{reducer:w,actions:S}=Bbe({context:p,queryThunk:f,mutationThunk:g,reducerPath:s,assertTagType:h,config:{refetchOnFocus:c,refetchOnReconnect:d,refetchOnMountOrArgChange:l,keepUnusedData
226For:o,reducerPath:s,invalidationBehavior:u}});Ai(t.util,{patchQueryData:x,updateQueryData:b,upsertQueryData:y,prefetch:v,resetApiState:S.resetApiState}),Ai(t.internalActions,S);const{middleware:E,actions:k}=eye({reducerPath:s,context:p,queryThunk:f,mutationThunk:g,api:t,assertTagType:h});Ai(t.util,k),Ai(t,{reducer:w,middleware:E});const{buildQuerySelector:j,buildMutationSelector:_,selectInvalidatedBy:D,selectCachedArgsForQuery:M}=Ube({serializeQueryArgs:i,reducerPath:s,createSelector:e});Ai(t.util,{selectInvalidatedBy:D,selectCachedArgsForQuery:M});const{buildInitiateQuery:N,buildInitiateMutation:O,getRunningMutationThunk:R,getRunningMutationsThunk:L,getRunningQueriesThunk:P,getRunningQueryThunk:F}=$be({queryThunk:f,mutationThunk:g,api:t,serializeQueryArgs:i,context:p});return Ai(t.util,{getRunningMutationThunk:R,getRunningMutationsThunk:L,getRunningQueryThunk:F,getRunningQueriesThunk:P}),{name:jT,injectEndpoint(z,B){const W=t;W.endpoints[z]??={},tF(B)?Ai(W.endpoints[z],{name:z,select:j(z,B),initiate:N(z,B)},C(f,z)):Pbe(B)&&Ai(W.endpoints[z],{name:z,select:_(),initiate:O(z)},C(g,z))}}}});tye();
226const nye=10*1024*1024,rye=1e4,sye=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iye=()=>{const[e,t]=m.useState({data:null,loading:!1,error:null,isTruncated:!1,totalRowsParsed:0}),n=m.useCallback(async s=>{t({data:null,loading:!0,error:null,isTruncated:!1,totalRowsParsed:0});let i=0,o=0;const l=[];let c=!1;try{ow.parse(s,{download:!0,header:!0,skipEmptyLines:!0,step:(d,u)=>{if(!sye(d.data))return;o+=1;const p=JSON.stringify(d.data).length*2;i+=p,l.push(d.data),(i>=nye||o>=rye)&&(c=!0,u.abort(),t({data:l,loading:!1,error:null,isTruncated:!0,totalRowsParsed:l.length}))},complete:d=>{if(!(c||d.meta.aborted)){if(l.length===0&&(d.meta.fields?.length??0)>0){t({data:[],loading:!1,error:"CSV file contains headers but no data rows",isTruncated:!1,totalRowsParsed:0});return}t({data:l,loading:!1,error:null,isTruncated:!1,totalRowsParsed:l.length})}},error:d=>{const u=d instanceof Error?d.message:"Unknown error";t({data:null,loading:!1,error:`Failed to parse CSV: ${u}`,isTruncated:!1,totalRowsParsed:0})}})}catch(d){const u=d instanceof Error?d.message:"Unknown error occurred";t({data:null,loading:!1,error:u,isTruncated:!1,totalRowsParsed:0})}},[]),r=m.useCallback(()=>{t({data:null,loading:!1,error:null,isTruncated:!1,totalRowsParsed:0})},[]);return{...e,parseCsv:n,reset:r}},aye=e=>{if(!e)return null;if(typeof e=="string")return e;if(typeof e!="object")return"An error occurred while fetching results";if("message"in e&&typeof e.message=="string")return e.message;if("data"in e){const{data:t}=e;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"message"in t){const{message:n}=t;if(typeof n=="string")return n}}return"An error occurred while fetching results"},oye=e=>{const{data:t,isLoading:n,isFetching:r,error:s}=n3(e?{filePrefix:e}:Eh),{data:i,loading:o,error:l,isTruncated:c,totalRowsParsed:d,parseCsv:u}=iye();return m.useEffect(()=>{t?.presigned_url&&u(t.presigned_url)},[t?.presigned_url,u]),{data:i,loading:n||r||o,error:aye(s)||l,isTruncated:c,totalRowsParsed:d,downloadUrl:t?.presigned_url||null}},lye=({error:e,resultsError:t,wsError:n,executionStatus:r,queryResults:s,userIsInternal:i,onClearSpinner:o})=>{const{pushNotification:l,clearNotification:c}=jt(),d=m.useRef(null),u=m.useRef(null),p=m.useRef(null),h=m.useRef(!1);m.useEffect(()=>{const f=e||t||n;f&&f!==d.current?(o(),p.current&&(c(p.current),p.current=null),l({severity:"error",content:f,timeout:-1}),d.current=f):!f&&d.current&&(d.current=null)},[e,t,n,l,c,o]),m.useEffect(()=>{const{status:f}=r;if(f==="RUNNING"&&f!==u.current){const g=l({content:"Query submitted successfully! Waiting for results...",timeout:-1});p.current=g,u.current=f}else f==="FAILED"&&f!==u.current&&(o(),p.current&&(c(p.current),p.current=null),u.current=f)},[r,l,c,o]),m.useEffect(()=>{r.status==="COMPLETED"&&r.status!==u.current&&(o(),p.current&&(c(p.current),p.current=null),u.current=r.status,h.current=!1)},[r.status,c,o]),m.useEffect(()=>{if(r.status==="COMPLETED"&&s!==void 0&&!h.current)if(h.current=!0,s.length>0){const f=i?`Query completed successfully! Results available at: ${r.s3Bucket}/${r.filePrefix}`:"Query completed successfully!";l({severity:"success",content:f,timeout:-1})}else l({severity:"warning",content:"Query completed with no results.",timeout:-1})},[r.status,r.s3Bucket,r.filePrefix,s,i,l])},cye=e=>{const t=e.match(/Details:\s*"?\[?\{[^}]*'message':\s*'([^']+)'/);if(t&&t[1])return t[1];const n=e.match(/returned\s+"([^"]+)"/);if(n&&n[1])return n[1];const r=e.match(/^Error:\s*(.+?)(?:,\s*CloudWatch|$)/);if(r&&r[1]){const s=r[1].match(/returned\s+"([^"]+)"/);return s&&s[1]?s[1]:r[1]}return e},dye=({connectorType:e,connection:t,startDate:n,endDate:r,apiConfig:s,connectorData:i})=>{const o=!!e,l=!!t&&t>0,c=Z.isDayjs(n)&&Z.isDayjs(r),d=i.find(p=>p.niceId===e);let u=!0;if(d?.globalConfig){const p=d.globalConfig.filter(h=>h.required===!0);p.length>0&&(u=p.every(h=>{const f=s?.[h.name];return Array.isArray(f)?f.length>0:typeof f=="string"?f.trim()!=="":typeof f=="number"?!0:f==null?!1:!!f}))}return!!(o&&l&&c&&u)},uye=()=>{const{userIsInternal:e}=gt(),{state:t,dispatch:n,skipNextApiConfigReset:r}=gg(),{savedQueryToLoad:s,loadKey:i}=t,o=Xs({mode:"onSubmit",resolver:Zs(Tbe),defaultValues:Ibe}),{getValues:l,trigger:c,control:d}=o,{data:u=[]}=mu(),p=m.useRef(s),h=m.useRef(u);p.current=s,h.current=u;const f=Fo({control:d,name:"connector.type"}),g=Fo({control:d,name:"connection"}),x=Fo({control:d,name:"startDate"}),b=Fo({control:d,name:"endDate"}),y=Fo({control:d,name:"connector.apiConfig"}),v=m.useMemo(()=>dye({connectorType:f,connection:g,startDate:x,endDate:b,apiConfig:y,connectorData:u}),[f,g,x,b,y,u]),{executeQuery:C,isExecuting:w,error:S}=Abe(),[E,k]=m.useState(null),[j,_]=m.useState(!1),[D,M]=m.useState(void 0),N=Mbe(E),{data:O,loading:R,error:L,isTruncated:P,totalRowsParsed:F,downloadUrl:z}=oye(N.filePrefix),B=m.useMemo(()=>
226{if(N.status==="FAILED"){const le=N.error||"Query execution failed";return cye(le)}return null},[N.status,N.error]),W=m.useCallback(()=>{_(!1)},[]),H=m.useCallback(le=>{M(le)},[]);lye({error:S,resultsError:L,wsError:B,executionStatus:N,queryResults:O??void 0,userIsInternal:e,onClearSpinner:W}),m.useEffect(()=>{O&&H(O)},[N.status,O,H]),m.useEffect(()=>{if(i===0)return;const le=p.current;if(!le)return;const J=h.current.find(Y=>Y.id===le.connector_id)?.niceId??"",{setValue:he}=o,ne=o.getValues("connector.type");he("queryName",le.name),he("connection",le.connection_id),he("startDate",le.start_date?Z(le.start_date):null),he("endDate",le.end_date?Z(le.end_date):null),he("connector.apiConfig",le.api_config,{shouldValidate:!1}),r.current=!0,he("connector.type",J,{shouldValidate:!0}),ne===J&&(r.current=!1),n({type:"clearSavedQueryToLoad"}),n({type:"incrementConfigVersion"})},[i,o,n,r]);const V=m.useCallback(()=>{M(void 0),_(!0)},[]),G=m.useCallback(async le=>{k(null);const ce=await C(le);ce.success&&ce.jobId?k(ce.jobId):_(!1)},[C]),X=m.useMemo(()=>({handleExecuteQuery:async()=>{V();try{if(await c()){const ce=l();await G(ce)}else _(!1)}catch(le){throw _(!1),le}}}),[l,c,G,V]),K=N.status==="RUNNING",ie=j||w||K||R;return a.jsx(Q2.Provider,{value:X,children:a.jsx(Js,{...o,children:a.jsxs(Br,{sx:{backgroundColor:"background.paper",borderRadius:2,mt:"10px",p:2},children:[a.jsx(Sbe,{isFormComplete:v,isLoading:ie}),a.jsx(_be,{onSubmit:G,queryResults:D,resultsLoading:R,isTruncated:P,totalRowsParsed:F,downloadUrl:z})]})})})},pye=({queryToDelete:e,onClose:t,onDelete:n})=>{const[r,s]=m.useState(""),[i,o]=m.useState(!1),l=()=>{s(""),t()},c=async()=>{if(!e)return;o(!0);const d=await n(e.id);if(o(!1),"error"in d){s("An error occurred while trying to delete this query");return}l()};return a.jsx(eg,{captchaText:"DELETE",deleting:i,errorMessage:r,onClose:l,onDelete:c,open:!!e,resourceName:e?.name??"",resourceType:"Query"})},hye=({queryToRename:e,existingNames:t,onClose:n,onRename:r})=>{const[s,i]=m.useState(""),[o,l]=m.useState(""),[c,d]=m.useState(!1),u=()=>{i(e?.name??""),l("")},p=x=>{const b=x.trim();return b?b===e?.name?"New name must be different from the current name.":t.some(y=>y.toLowerCase()===b.toLowerCase())?"A query with this name already exists for this engagement.":"":"Name cannot be empty."},h=()=>{i(""),l(""),n()},f=async()=>{if(!e)return;const x=p(s);if(x){l(x);return}d(!0);const b=await r(e.id,s.trim());if(d(!1),"error"in b){l("An error occurred while renaming the query. Please try again.");return}h()},g=x=>{i(x),o&&l("")};return a.jsxs(yt,{open:!!e,onClose:h,TransitionProps:{onEntered:u},maxWidth:"xs",fullWidth:!0,children:[a.jsx(vt,{children:"Rename Query"}),a.jsxs(Ct,{children:[a.jsx(Tl,{autoFocus:!0,fullWidth:!0,label:"Query name",value:s,onChange:x=>g(x.target.value),onKeyDown:x=>{x.key==="Enter"&&f()},error:!!o,variant:"filled",sx:{mt:1}}),o&&a.jsx(Zn,{error:!0,sx:{mx:0},children:o})]}),a.jsxs(un,{children:[a.jsx(re,{onClick:h,disabled:c,children:"Cancel"}),a.jsx(re,{onClick:f,variant:"contained",disabled:c,children:c?"Saving...":"Save"})]})]})},fye=({onOpen:e,onRename:t,onDelete:n})=>{const[r,s]=m.useState(null),i=!!r,o=()=>{s(null)},l=()=>{e(),o()},c=()=>{t(),o()},d=()=>{n(),o()};return a.jsxs(T,{children:[a.jsx(Ie,{"aria-label":"Query actions",onClick:u=>{s(u.currentTarget)},sx:{p:.5},children:a.jsx(vl,{size:16})}),a.jsxs(dr,{anchorEl:r,open:i,onClose:o,sx:{"> .MuiPaper-root":{borderRadius:"6px",width:"120px"}},children:[a.jsx(Se,{onClick:l,children:"Open"}),a.jsx(Se,{onClick:c,children:"Rename"}),a.jsx(Se,{onClick:d,children:"Delete"})]})]})},kT=({value:e})=>
226{if(e==null)return a.jsx(I,{children:"N/A"});const t=new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return a.jsx(I,{sx:{whiteSpace:"normal",wordBreak:"break-word"},children:t})},Ac={flex:1,minWidth:110,resizable:!0,sortable:!0,type:"action"},mye=(e,t,n)=>[{...Ac,field:"name",headerName:"Name",minWidth:200},{...Ac,field:"connector_name",headerName:"Connector",minWidth:150},{...Ac,field:"created_at",headerName:"Created",type:"dateTime",valueGetter:({value:r})=>r?new Date(r):null,renderCell:({row:{created_at:r}})=>a.jsx(kT,{value:r})},{...Ac,field:"updated_at",headerName:"Updated",type:"dateTime",valueGetter:({value:r})=>r?new Date(r):null,renderCell:({row:{updated_at:r}})=>a.jsx(kT,{value:r})},{...Ac,field:"actions",headerName:"Actions",maxWidth:100,resizable:!1,sortable:!1,renderCell:({row:r})=>a.jsx(fye,{onOpen:()=>e(r),onRename:()=>t(r),onDelete:()=>n(r)})}],sF=25,gye={pagination:{paginationModel:{pageSize:sF}}},xye=15,bye=40,Cw=58,yye=bye+Cw*sF+xye,vye=()=>a.jsx(T,{sx:{alignItems:"center",display:"flex",height:"100%",justifyContent:"center",width:"100%"},children:a.jsx(I,{children:"No saved queries."})}),fv=bs(Mn)(({theme:e})=>{const{text:t,background:n,border:r}=e.palette,{spacing:s}=e,i={backgroundColor:n.paper,color:t.default,":hover":{backgroundColor:e.palette.mode==="dark"?n.brand.subtle.hovered:n.brand.subtlest.default}};return{border:"none",minHeight:Cw*2.5,[`.${xe.main}`]:{maxHeight:yye,height:"100%",borderRadius:"6px",border:"1px solid",borderColor:r.default,boxSizing:"border-box"},[`.${xe.cell}`]:{border:"none",paddingLeft:s(2),paddingRight:s(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1)}},[`.${xe.columnHeader}`]:{paddingLeft:s(2.5),paddingRight:s(1),":focus-within":{outline:"none"},"&:first-of-type":{paddingLeft:s(1.5)}},[`.${xe.columnHeaders}`]:{backgroundColor:n.tableHeader,border:"none"},[`.${xe.columnHeaderTitleContainerContent}`]:{textTransform:"uppercase",fontSize:12},[`.${xe.iconButtonContainer}`]:{paddingLeft:s(1.5)},[`.${xe.row}`]:{...i,cursor:"pointer"},[`.${xe.virtualScroller}`]:{width:"calc(100% + 2px)"}}});fv.defaultProps={...fv.defaultProps,columnHeaderHeight:40,disableColumnMenu:!1,disableColumnFilter:!1,disableRowSelectionOnClick:!0,pagination:!0,rowHeight:Cw};const Cye=({isLoading:e,onDeleteQuery:t,onOpenQuery:n,onRenameQuery:r,savedQueries:s})=>{const i=m.useMemo(()=>mye(n,r,t),[n,r,t]);return a.jsx(T,{sx:{display:"grid",maxWidth:"2000px",width:"100%"},children:a.jsx(fv,{autoHeight:!e,columns:i,getRowId:o=>o.id,initialState:gye,loading:e,onCellClick:o=>{o.field!=="actions"&&n(o.row)},pageSizeOptions:[25,50,100],rows:s,disableColumnPinning:!0,disableColumnSelector:!0,slots:{loadingOverlay:Cs,noRowsOverlay:vye}})})},wye=()=>{const{engagementId:e}=pe(),{dispatch:t}=gg(),n=xw(),[r,s]=m.useState(null),[i,o]=m.useState(null),{data:l=[],isLoading:c}=zA({engagementId:e},{skip:!e}),[d]=r3(),[u]=s3(),p=m.useCallback(C=>{n("openSavedQuery",{queryId:C.id,queryName:C.name}),t({type:"savedQueryToLoad",value:C}),t({type:"activeTab",value:"0"})},[t,n]),h=m.useCallback(C=>{s(C)},[]),f=m.useCallback(C=>{o(C)},[]),g=m.useCallback(async C=>{n("deleteQuery",{queryId:C});try{return await d({id:C,engagementId:e}).unwrap(),{}}catch(w){return{error:w}}},[d,e,n]),x=m.useCallback(async(C,w)=>{n("renameQuery",{queryId:C,queryName:w});try{return await u({id:C,name:w,engagement_id:e}).unwrap(),{}}catch(S){return{error:S}}},[e,n,u]),b=m.useCallback(()=>{s(null)},[]),y=m.useCallback(()=>{o(null)},[]),v=l.filter(C=>C.id!==i?.id).map(C=>C.name);return e?a.jsxs(T,{children:[a.jsx(Cye,{savedQueries:l,isLoading:c,onOpenQuery:p,onRenameQuery:f,onDeleteQuery:h}),a.jsx(pye,{queryToDelete:r,onClose:b,onDelete:g}),a.jsx(hye,{queryToRename:i,existingNames:v,onClose:y,onRename:x})]}):a.jsx(T,{sx:{p:3},children:a.jsx(I,{children:"No engagement selected"})})},ET=[{authorized:"DataSources.QueryStudio",label:"Query Editor",value:"0"},{authorized:"DataSources.QueryStudio",label:"Saved Queries",value:"1"}],Sye=()=>{const{state:e,dispatch:t}=gg(),n=xw(),{activeTab:r}=e,s=i=>{const o=ET.find(l=>l.value===i)?.label;
226n("changeTab",{tab:typeof o=="string"?o:i}),t({type:"activeTab",value:i})};return a.jsxs(T,{sx:{width:"100%"},children:[a.jsx(T,{mb:4,children:a.jsx(Xt,{title:"Query Studio"})}),a.jsxs(fo,{onChange:s,tabs:ET,value:r,children:[a.jsx(xt,{value:"0",sx:{p:0}}),a.jsx(xt,{value:"1",sx:{px:0},children:a.jsx(m.Suspense,{fallback:a.jsx("div",{children:"Loading..."}),children:a.jsx(wye,{})})})]}),a.jsx(T,{sx:{display:r==="0"?"block":"none"},children:a.jsx(uye,{})})]})},jye=()=>a.jsx(pbe,{children:a.jsx(Sye,{})}),iF=m.createContext(null),ti=()=>m.useContext(iF),kye=()=>{const{engagement:{active:e,brand_name:t},client:{name:n}={},dispatch:r,assigned:s}=ti(),i=ma(),{setRaiseConversationIcon:o}=jt(),l=()=>{i("clickEditEngagement"),o(!0),r({type:"engagementFormOpen",value:!0})};return a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsxs(T,{sx:{marginBottom:"24px"},children:[a.jsxs(T,{sx:{display:"flex",gap:"16px"},children:[a.jsx(I,{variant:"h5",children:t}),a.jsx(ut,{label:e?"Active":"Inactive",color:e?"success":"default"})]}),a.jsxs(T,{sx:{display:"flex"},children:[a.jsx(I,{color:"text.secondary",children:"Client:Â "}),a.jsx(I,{children:n})]})]}),a.jsx(T,{children:a.jsx(be,{title:s?null:"You need to be assigned to the engagement to edit it",children:a.jsx(T,{children:a.jsx(re,{"data-testid":"engagement:edit:button",sx:{padding:"4px 10px 4px 15px"},color:"secondary",startIcon:a.jsx(ou,{size:14}),onClick:l,disabled:!s,children:"Edit"})})})})]})},Eye=e=>Object.keys(e),_ye=(e,t=[])=>Object.entries(t).reduce((n,[r,s])=>{const i=e[Number(r)];return Object.values(s).some(o=>o)&&i&&n.push(i),n},[]),Tye=(e,t={})=>{const{targets:n=[],...r}=t,{targets:s,...i}=e,o=Eye(r);return{targets:_ye(s,n),...o.reduce((l,c)=>r[c]?{...l,[c]:i[c]}:l,{})}},Iye=e=>{if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"){const t=e.trim();if(t==="")return null;const n=Number(t);return Number.isFinite(n)?n:null}return null},Op=({field:e,loading:t,sx:n,sxValue:r,tooltipValue:s,value:i})=>a.jsxs(T,{sx:{display:"flex",flexDirection:"row",...n},children:[a.jsxs(I,{sx:{width:200},variant:"body2",color:"text.secondary",children:[e,":"]}),t?a.jsx(fe,{variant:"text",sx:{fontSize:14,width:100}}):a.jsx(be,{title:s,children:a.jsx(I,{sx:r,variant:"body2",children:i})})]}),_T=({loading:e=!1,value:t})=>e?a.jsx(fe,{variant:"rounded",sx:{height:28,width:48,borderRadius:2}}):a.jsx(ut,{color:t?"success":"secondary",label:t?"Yes":"No",sx:{height:28,width:48}}),Vu={appearance:"Appearance",details:"Engagement Details",notes:"Notes",security:"Security",settings:"Account Settings"},Dye=()=>{const{engagement:e}=ti(),{ds_license:t,kpi_license:n,active:r,dataplatform_flag:s}=e||{};return a.jsx(Zt,{title:Vu.settings,children:a.jsxs($,{rowGap:1,children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:"Active"}),a.jsx(_T,{value:!!r})]}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",height:28},children:[a.jsx(I,{variant:"body2",children:"Data Source Licenses"}),t]}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",height:28},children:[a.jsx(I,{variant:"body2",children:"KPI Licenses"}),n]}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:"Data Platform"}),a.jsx(_T,{value:!!s}
226)]})]})})},Aye=()=>{const{engagement:e}=ti(),{brand_name:t,id:n,brand_logo:r,brand_color:s}=e||{},i=pd(s),o=i?JD(i):null;return a.jsx(Zt,{title:Vu.details,children:a.jsxs($,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[a.jsxs($,{rowGap:1,sx:{width:{xs:"100%",lg:"40%"},gap:2},children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:"Engagement Name:"}),t]}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:"Engagement ID:"}),n]})]}),a.jsxs($,{rowGap:1,sx:{width:{xs:"100%",lg:"40%"},gap:3},children:[a.jsxs(T,{children:[a.jsx(I,{variant:"body2",sx:{mb:1},children:"Engagement Logo"}),r?a.jsx("img",{src:r,alt:"Engagement Logo",style:{maxHeight:"60px",maxWidth:"100%",objectFit:"contain"}}):a.jsx(I,{variant:"body2",children:"No Image"})]}),a.jsxs(T,{children:[a.jsx(I,{variant:"body2",sx:{mb:1},children:"Brand Color"}),o&&s?a.jsxs($,{direction:"row",sx:{alignItems:"center",gap:1},children:[a.jsx(T,{"data-testid":"engagement:brand-color:swatch",sx:{backgroundColor:o,border:"1px solid",borderColor:"border.input",borderRadius:1,height:24,width:24}}),a.jsx(I,{variant:"body2",children:s.toUpperCase()})]}):a.jsx(I,{variant:"body2",children:"Uses Darwin branding"})]})]})]})})},Mye=()=>{const{engagementTargets:e=[],loadingEngagementTargets:t}=ti();return a.jsx(Zt,{title:"Target Audience",children:a.jsx($,{direction:"column",spacing:2,sx:{width:{xs:"100%",lg:"40%"}},children:t?a.jsx(fe,{variant:"rounded",width:"100%",height:20}):e.length===0?a.jsx(I,{variant:"body2",children:"None"}):e.map((n,r)=>a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:r>0?"":"Names:"}),a.jsx(I,{variant:"body2",children:n.target_name})]},n.id))})})},Rye=()=>{const{engagement:{country:e,geo_granularity:t,date_format:n,currency:r}}=ti();return a.jsx(Zt,{title:Vu.appearance,children:a.jsxs(xn,{rowGap:1,children:[a.jsx(Op,{field:"Country",value:e}),a.jsx(Op,{field:"Currency",value:r}),a.jsx(Op,{field:"Geographic Level of Detail",value:t}),a.jsx(Op,{field:"Date Format",value:n})]})})},Nye=()=>{const{engagement:e}=ti(),{notes:t}=e||{};return a.jsx(Zt,{title:Vu.notes,children:a.jsx(ms,{markdownText:t??"No notes were added."})})},Oye=()=>{const{engagement:e}=ti(),{mfa_flag:t}=e||{};return a.jsx(Zt,{title:Vu.security,children:a.jsx($,{direction:"row",justifyContent:"space-between",alignItems:"center",children:a.jsx($,{rowGap:1,sx:{width:{xs:"100%",lg:"40%"},gap:3},children:a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:"Multi-Factor Authentication:"}),t?"Enabled":"Disabled"]})})})})},Pye=({kpiToEdit:e,handleClose:t})=>{const{handleSwitchEngagement:n,engagement:r}=ti(),s=en(),i=()=>{e&&(n(r.id,r.client_id),s("/data-pipeline/machine-learning/objective/:objective_id",{pathParams:{objective_id:e.objective_id}}))},{brand_name:o}=r;return a.jsxs(yt,{open:!!e,children:[a.jsx(vt,{children:"Warning"}),a.jsxs(Ct,{children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"column",gap:1,justifyContent:"flex-end"},children:[a.jsxs(I,{children:["You will be switched to ",a.jsx(I,{component:"span",sx:{fontWeight:"bold"},children:o})," in order to edit the kpi ",a.jsx(I,{component:"span",sx:{fontWeight:"bold"},children:e?.objective_name})]}),a.jsx(I,{children:"Do you want to continue?"})]}),a.jsxs(T,{sx:{display:"flex",gap:1,justifyContent:"flex-end"},children:[a.jsx(re,{color:"secondary",onClick:t,children:"Close"}),a.jsx(re,{color:"primary",variant:"contained",onClick:i,children:"Continue"})]})]})]})},Lye=()=>{const{engagement:e,assigned:t,engagementObjectives:n=[],loadingEngagementObjectives:r}=ti(),s=en(),{engagementId:i}=pe(),[o,l]=m.useState(null),c=d=>{i===e?.id?s("/data-pipeline/machine-learning/objective/:objective_id",{pathParams:{objective_id:d.objective_id}}):l(d)};return a.jsxs(a.Fragment,{children:[a.jsx(Zt,{title:"KPIs",children:a.jsx($,{direction:"column",spacing:1,sx:{width:{xs:"100%",lg:"40%"}},children:r?a.jsx(fe,{variant:"rounded",width:"100%",height:20}):n.length===0?a.jsx(I,{variant:"body2",children:"None"}):n.map((d,u)=>a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsx(I,{variant:"body2",children:u>0?"":"Names:"}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",gap:1,alignItems:"center"},children:[a.jsx(I,{variant:"body2",children:d.objective_name}),a.jsx(be,{title:t?null:"You need to be assigned to the engagement in order to edit this KPI",children:a.jsx(T,{children:a.jsx(Ie,{"aria-label":`Edit KPI ${d.objective_name}`,"data-testid":`engagement:kpi:edit:${d.objective_id}`,size:"small",disabled:!t,onClick:()=>c(d),children:a.jsx(ou,{size:18})})})})]})]},d.objective_id))})}),a.jsx(Pye,{handleClose:()=>l(null),kpiToEdit:o})]})},Fye=()=>{const{engagement:{brand_name:e},engagementObjectives:t=[],client:{niceId:n=null}={},engagement:r,handleNavigateToConfiguration:s,state:{engagementFormOpen:i},dispatch:o,engagementTargets:l=[],putEngagementLogo:c,userIsInternal:d}=ti(),[u]=UA(),[p]=mC(),h=ma(),{setRaiseConversationIcon:f}=jt(),{state:g}=es(),x=g?.openFormFromTable;m.useEffect(()=>
226{x&&(f(!0),o({type:"engagementFormOpen",value:!0}))},[o,x,f]);const b=()=>{if(f(!1),x){s();return}o({type:"engagementFormOpen",value:!1})},y=async({nextLogoFile:v,...C},w)=>{const S=Tye(C,w);if(!r?.id)return;h("editEngagement",{edits:S});const{objectives:E,targets:k,...j}=w??{};if(Object.values(j).some(D=>D)){const D=await u({body:{brand_name:S.engagement_name,brand_logo:v?`${hs.logoAssetsUrl}/${r.nice_id}/${v.name}`:void 0,brand_color:S.brand_color===void 0?void 0:RP(S.brand_color),mfa_flag:S.mfa_flag,country:S.country,currency:S.currency,geo_granularity:S.geo_granularity,date_format:S.date_format,ds_license:S.ds_license,kpi_license:S.kpi_license,active:S.active,dataplatform_flag:S.dataplatform_flag,notes:S.notes},engagementId:r.id});if("error"in D)throw new Error(String(D.error))}if(S.objectives?.length){const D=await p({engagementId:r.id,objectives:S.objectives.map(({name:M,value_per_conversion:N,kpi_scalar:O})=>({name:M,value_per_conversion:N,kpi_scalar:O??null}))});if("error"in D)throw new Error(String(D.error))}r.nice_id&&v&&c(r.nice_id,v)};return a.jsxs(T,{"data-testid":"engagement:page:container",children:[!i&&a.jsxs(a.Fragment,{children:[a.jsx(vu,{handleNavigateHome:s,pageName:e,parentConfig:{handleNavigateToParent:s,parentName:"Configuration"}}),a.jsx(kye,{}),a.jsx(T,{children:a.jsxs($,{sx:{py:2,px:{xs:8,lg:20},minWidth:600,flexDirection:{xs:"column",lg:"row"},gap:3,justifyContent:"center"},children:[a.jsxs($,{sx:{width:{xs:"100%",lg:"67%"},gap:3},children:[a.jsx(Aye,{}),a.jsx(Oye,{}),a.jsx(Rye,{}),a.jsx(Lye,{}),a.jsx(Mye,{})]}),a.jsxs($,{sx:{width:{xs:"100%",lg:"33%"},gap:3,display:d?"inherit":"none"},children:[a.jsx(Dye,{}),a.jsx(Nye,{})]})]})})]}),a.jsx(FP,{engagement:r,targets:l.map(({target_name:v,id:C})=>({name:v,id:C,active:!0})),objectives:t.map(({objective_id:v,objective_name:C,value_per_conversion:w,kpi_scalar:S,active:E})=>({id:v,name:C,value_per_conversion:Iye(w),kpi_scalar:S,active:E})),editing:!0,clientNiceId:n,onClose:b,onSubmit:y,open:i})]})},$ye={engagementFormOpen:!1},zye=(e,t)=>t.type in e?{...e,[t.type]:t.value}:e,Bye=({engagement:e,engagementObjectives:t,engagementTargets:n,loadingEngagementObjectives:r,loadingEngagementTargets:s,client:i,assigned:o,putEngagementLogo:l,userIsInternal:c})=>{const d=en(),[u,p]=m.useReducer(zye,$ye),h=m.useCallback(()=>d("/settings/configuration"),[d]),f=jA(),g=m.useCallback((b,y)=>{f({clientId:y,engagementId:b})},[f]),x=m.useMemo(()=>({dispatch:p,engagement:e,engagementObjectives:t,engagementTargets:n,loadingEngagementObjectives:r,loadingEngagementTargets:s,handleNavigateToConfiguration:h,putEngagementLogo:l,state:u,client:i,assigned:o,userIsInternal:c,handleSwitchEngagement:g}),[e,t,n,r,s,h,l,u,i,o,c,g]);return a.jsx(iF.Provider,{value:x,children:a.jsx(Fye,{})})},Uye=()=>{const e=en(),{userIsInternal:t}=gt(),{clientId:n}=pe(),[r]=Sm(),{data:s=[],isSuccess:i}=Nd({body:t?{}:{client_id:n}}),{data:o=[],isLoading:l}=pC(null),{id:c}=Cm(),d=s.find(({id:v})=>v.toString()===c),{data:u,isLoading:p}=i3(d?.id??0,{skip:!d}),{data:h=[],isLoading:f}=hu(d?.id??0,{skip:!d});m.useEffect(()=>{!d&&i&&e("/settings/configuration",{replace:!0})},[d,e,i]);const g=(v,C)=>{const w=`${hs.logoAssetsUrl}/${v}/${C.name}`,S={"Content-Type":`${C.type}`,"x-amz-acl":"bucket-owner-full-control"};r({url:w,method:"put",headers:S,data:C})},{userEngagements:x}=yu(d?.id??-1);if(!d)return null;const b=x.some(({engagement_id:v})=>v.toString()===c);let y;if(d&&!l){const v=o.find(({id:C})=>d.client_id===C);v&&(y={name:v.name,niceId:v.niceId,id:v.id})}return a.jsx(Bye,{engagement:d,engagementTargets:u,engagementObjectives:h,loadingEngagementTargets:p,loadingEngagementObjectives:f,client:y,assigned:b,putEngagementLogo:g,userIsInternal:t})},aF=e=>Object.entries(e.reduce((t,{targetName:n,targetNiceId:r})=>(n&&r&&(t[n]=r),t),{})).map(([t,n])=>({name:t,niceId:n})).sort((t,n)=>t.name.localeCompare(n.name)),Vye=e=>{const t=aF(e),n=t.find(({niceId:r})=>r==="adults18");return n?n.niceId:t[0]?t[0].niceId:""},oF=({data:e,target:t})=>Object.entries(e.reduce((n,{kpiName:r,kpiNiceId:s,targetNiceId:i})=>(i===t&&(n[r]=s),n),{})).map(([n,r])=>({name:n,niceId:r})).sort((n,r)=>n.name.localeCompare(r.name)),TT=({data:e,target:t})=>{const n=oF({data:e,target:t});return n[0]?n[0].niceId:""},nb=({metaDataItem:e,dateRange:t})=>{const[n,r]=t;if(!n||!r)return!1;const s=Z(e.minEventDate),i=Z(e.maxEventDate);return!!((n.isSame(s)||n.isAfter(s))&&(r.isSame(i)||r.isBefore(i)))},_h=({data:e,target:t,kpi:n})=>!t||!n?null:e.find(({kpiNiceId:r,targetNiceId:s})=>r===n&&s===t)||null,rb=e=>{const{maxEventDate:t,minEventDate:n}=e,r=Z(n),s=Z(t),i=Ui(s,"last3Months");return i[0].isBefore(r)?[r,s]:i},Ys=({metaData:e,selectedTarget:t,selectedDateRange:n,selectedKpi:r})=>{let s="",i="",o=[null,null];const l=_h({data:e,kpi:r,target:t});if(l){const{kpiNiceId:c,targetNiceId:d}=l;s=d,i=c,nb({metaDataItem:l,dateRange:n})?o=n:o=rb(l)}else if(t){const c=TT({data:e,target:t}),d=_h({data:e,kpi:c,target:t});d?(s=t,i=c,nb({metaDataItem:d,dateRange:n})?o=n:o=rb(d)):We("No meta data found - code error")}else{const c=Vye(e),d=TT({data:e,target:c}),u=_h({data:e,target:c,kpi:d});u?(s=c,i=d,nb({metaDataItem:u,dateRange:n})?o=n:o=rb(u)):We("No meta data found - code error")}return{nextDateRange:o,nextKpi:i,nextTarget:s}},Zr={tooltipContainer:"tooltip-container",tooltipItemContainer:"tooltip-item-container",tooltipItem:"tooltip-item"},Wye={GL_TYPE_NAME:"Media Type",GL_PLATFORM_NAME:"Media Platform",GL_MARKET_NAME:"Market",GL_TACTIC_NAME:"Tactic",GL_COUNTRY_NAME:"Country",GL_VEHICLE_NAME:"Vehicle",GL_PROGRAM_NAME:"Program",KPI_MARKET:"KPI Market"},Hye=["conversions","investment","impressions","roas"],xg="conversions",qye={conversions:"Conversions",investment:"Spend Per Conversion",impressions:"Impressions Per Conversion"},Fr={...qye,roas:"Return On Advertising Spend"},Wu="contribution",Gye=!1,IT={type_name:"GL_TYPE_NAME",vehicle_name:"GL_VEHICLE_NAME",platform_name:"GL_P
226LATFORM_NAME",tactic_name:"GL_TACTIC_NAME",program_name:"GL_PROGRAM_NAME",country_name:"GL_COUNTRY_NAME",market_name:"GL_MARKET_NAME"},Yye=({attributesData:e,themesData:t,fieldDefinitions:n,defaultClassifications:r})=>{const s=[...e,...t].filter(({active:c,dimension:d,dimension_type:u})=>c&&u!=="creative"&&oP(d)).sort((c,d)=>c.title.toLowerCase()<d.title.toLowerCase()?-1:1),i=new Map(n?[...n.taxonomy_fields||[],...n.campaign_fields||[],...n.campaign_id_fields||[],...n.data_source_fields||[]].flatMap(c=>{const d=c.dimension?.toLowerCase();if(!d)return[];const u=[[d,c.active]],p=IT[d];return p&&u.push([p,c.active]),u}):[]),o={};Object.entries(r).reduce((c,[d,u])=>(i.get(d)!==!1&&(c[d]=u),c),o);const l=new Set;return s.reduce((c,{dimension:d,dimension_type:u,title:p})=>{const h=N0[d]||d,f=IT[h];if(f&&p)c[f]!==void 0&&(c[f]=p),l.add(d);else if(!l.has(d)){const g=d.split("_").map(b=>b.charAt(0).toUpperCase()+b.slice(1)).join(" "),x=(d.startsWith("theme")?d:`${u}_${d}`).toUpperCase();c[x]=p||g}return c},o),o},ww=()=>{const{engagementId:e,engagementNiceId:t}=pe(),{data:n=[]}=Qs(e),r=n[0]?.brand_nice_id??"",{data:s=[]}=wm({brandNiceId:r,engagementNiceId:t},{skip:!r||!t}),{data:i=[]}=dC({brandNiceId:r,engagementNiceId:t},{skip:!r||!t}),{data:o}=wA({engagementNiceId:t,brandNiceId:r},{skip:!r||!t});return m.useMemo(()=>Yye({attributesData:s,themesData:i,fieldDefinitions:o,defaultClassifications:Wye}),[s,o,i])},DT="YYYY-MM-DD",Kye=({conversionType:e,datePart:t,getMetaData:n,mediaAttribute:r,metaData:s,metaDataLoading:i,onFilterChange:o,requiredColumns:l=[],selectedDateRange:c,selectedKpi:d,selectedTarget:u})=>{const p=ct(),{engagementNiceId:h}=pe(),{getKpiConfig:f,isLoadingConfig:g}=lP(),[x]=a3(),[b,y]=m.useState([]),[v,C]=m.useState(!0),[w,S]=m.useState(!1),E=m.useCallback(async({nextConversionType:j=e,nextDateRange:_=c,nextKpi:D=d,nextMediaAttribute:M=r,nextTarget:N=u}={})=>{const[O,R]=_;if(O&&R&&D&&N&&!g){const{valuePerConversion:L,kpiScalar:P}=f(D);C(!0);const F=[...l];M&&F.push(M);const z={columns:Array.from(new Set(F)),end_date:R.format(DT),engagement_nice_id:h,kpi_nice_id:D,kpi_target:N,start_date:O.format(DT),table:j};t&&(z.date_part=t),L!=null&&(z.value_per_conversion=L),P!=null&&(z.kpi_scalar=P);const{data:B}=await x({body:z},!0);p()&&(y(B||[]),C(!1))}},[e,t,h,x,p,f,g,r,l,u,c,d]),k=m.useCallback(async j=>{o({type:"conversionType",value:j});const _=n(j);C(!0);const D=await _,{nextDateRange:M,nextKpi:N,nextTarget:O}=Ys({metaData:D,selectedDateRange:c,selectedKpi:d,selectedTarget:u});p()&&(o({type:"filtersBar",value:{nextDateRange:M,nextKpi:N,nextTarget:O}}),E({nextConversionType:j,nextDateRange:M,nextKpi:N,nextTarget:O}),C(!1))},[E,n,p,o,c,d,u]);return m.useEffect(()=>{if(!w&&!i&&s.length){const[j,_]=c;if(!u&&!d&&!j&&!_){const{nextDateRange:D,nextKpi:M,nextTarget:N}=Ys({metaData:s,selectedDateRange:c,selectedKpi:d,selectedTarget:u});o({type:"filtersBar",value:{nextDateRange:D,nextKpi:M,nextTarget:N}})}}},[w,s,i,o,c,d,u]),m.useEffect(()=>{if(!w){const[j,_]=c;j&&_&&d&&u&&!g&&(E(),S(!0))}},[c,w,E,g,d,u]),{getMediaData:E,handleConversionTypeChange:k,mediaData:b,mediaDataLoading:v}},Qye=({conversionType:e,selectedKpi:t,selectedTarget:n})=>{const r=ct(),[s,i]=m.useState(!1),[o,l]=m.useState([]),[c,d]=m.useState(!0),{engagementNiceId:u}=pe(),[p]=o3(),h=m.useMemo(()=>aF(o),[o]),f=m.useMemo(()=>oF({data:o,target:n}),[o,n]),{activeKpiNiceIds:g,kpisLoading:x}=Ol(),b=m.useMemo(()=>{const v=_h({data:o,kpi:t,target:n});if(v){const{minEventDate:C,maxEventDate:w}=v;return[Z(C),Z(w)]}return[null,null]},[o,n,t]),y=m.useCallback(async v=>{d(!0);let C=[];const w=await p({conversionType:v,engagementNiceId:u},!0);return r()&&(C=(w?.data??[]).filter(E=>g.has(E.kpiNiceId)),l(C),d(!1)),C},[u,p,r,g]);return m.useEffect(()=>{!s&&!x&&(i(!0),y(e))},[e,s,y,x]),{targetOptions:h,availableDateRange:b,getMetaData:y,kpiOptions:f,metaData:o,metaDataLoading:x||c}},Sw=({conversionType:e,datePart:t,mediaAttribute:n,onFilterChange:r,requiredColumns:s,selectedDateRange:i,selectedKpi:o,selectedTarget:l})=>{const{availableDateRange:c,getMetaData:d,kpiOptions:u,metaData:p,metaDataLoading:h,targetOptions:f}=Qye({conversionType:e,selectedKpi:o,selectedTarget:l}),{getMediaData:g,handleConversionTypeChange:x,mediaData:b,mediaDataLoading:y}=Kye({conversionType:e,datePart:t,getMetaData:d,mediaAttribute:n,metaData:p,metaDataLoading:h,onFilterChange:r,requiredColumns:s,selectedDateRange:i,selectedKpi:o,selectedTarget:l}),v=ww();return{availableDateRange:c,getMediaData:g,getMetaData:d,handleConversionTypeChange:x,kpiOptions:u,mediaClassifications:v,mediaData:b,mediaDataLoading:y,metaData:p,metaDataLoading:h,targetOptions:f}},Jye={geography:"GEO",journey:"JOURNEY",lookback:"LOOKBACK",summary:"SUMMARY",externalFactors:"EXTERNAL_FACTORS"},Xye={conversionType:"Conversion Type Change",dateRange:"Date Range Change",download:"Download Chart",kpi:"KPI Change",reset:"Reset All Selections",targetAudience:"Target Audience Change",totalsType:"Totals Type Change",presentBy:"Pivot Column Change",includeBase:"Include Base Change",aggregatedView:"Aggregate View Change",extfactorsWaterfallSelection:"Waterfall Selection",extfactorsTrendSelection:"Trend Selection",dateType:"Date Type Change"},Hu=e=>{const{mpTrack:t}=tr();return m.useCallback((n,r)=>{t(`MEVO_INSIGHTS_${Jye[e]}`,{actionType:Xye[n],actionData:r})},[t,e])},lF=m.createContext(null),Co=()=>m.useContext(lF),Zye=()=>{const{availableDateRange:e,dispatch:t,getMediaData:n,kpiOptions:r,mediaDataLoading:s,metaData:i,metaDataLoading:o,state:l,targetOptions:c,track:d}=Co(),{selectedDateRange:u,selectedKpi:p,selectedTarget:h}=l,[f,g]=e,x=m.useCallback(v=>{const{nextDateRange:C,nextKpi:w,nextTarget:S}=Ys({metaData:i,selectedDateRange:u,selectedKpi:p,selectedTarget:v});t({type:"filtersBar",value:{selectedDateRange:C,selectedKpi:w,selectedTarget:S}}),d("targetAudience"),n({nextDateRange:C,nextKpi:w,nextTarget:S})},[t,n,i,u,p,d]),b=m.useCallback(v=>{const{nextDateRange:C,nextKpi:w,nextTarget:S}=Ys({metaData:i,selectedDateRange:u,selectedKpi:v,selectedTarget:h});t({type:"filtersBar",value:{selectedDateRange:C,selectedKpi:w,selectedTarget:S}}),d("kpi"),n({nextDateRange:C,nextKpi:w,nextTarget:S})},[t,n,i,h,u,d]),y=m.useCallback(v=>{t({type:"selectedDateRange",value:v}),d("dateRange"),n({nextDateRange:v})},[t,n,d]);return a.jsx(da,{dataFirstDate:f??void 0,dataLastDate:g??void 0,handleDatePickerOnChange:y,handleKpiOnChange:b,handleTargetAudienceOnChange:x,isDataLoading:s,isMetaLoading:o,kpiListOptions:r,selectedDateRange:u,selectedKpi:p,selectedTargetAudience:h,targetAudienceListOptions:c})},eve=()=>{const{dispatch:e,mediaDataLoading:t,metaDataLoading:n,state:{valueToShow:r},track:s}=Co(),i=({target:{value:o}})=>{Tn(Hye,o)&&(e({type:"valueToShow",value:o}),s("totalsType",{totalsType:o}))};return a.jsx(Ar,{sx:{width:"240px",maxWidth:"300px"},disabled:t,isLoading:n,onChange:i,options:Fr,value:r||Object.keys(Fr)[0]})};var Mc={},AT;function tve(){if(AT)return Mc;AT=1;var e=Pt();Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.default=void 0;var t=e(Lt()),n=Ot();return Mc.default=(0,t.default)((0,n.jsx)("path",{d:"M11 18h2v-2h-2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4"}),"HelpOutline"),Mc}var nve=tve();const jw=dt(nve),rve=bs(be)({".MuiTooltip-tooltip":{padding:"3px 4px",fontSize:"13px",fontStyle:"normal",fontWeight:"500",lineHeight:"18px",letterSpacing:"0.16px"}}),sve=({title:e})=>a.jsx(rve,{title:e,placement:"bottom",children:a.jsx(jw,{width:"18px"})}),ive=["_all-value","_others-value"],Rc={all:"_all-value",others:"_others-value"},cF=({data:e,dataLoading:t,limit:n,metaDataLoading:r,onChange:s,values:i})=>{const o=m.useMemo(()=>Object.entries(e).sort((g,x)=>x[1]-g[1]),[e]),l=m.useMemo(()=>o.slice(0,n).map(([g])=>g).sort((g,x)=>g.localeCompare(x)),[n,o]),c=m.useMemo(()=>(n?o.slice(n):[]).map(([g])=>g),[n,o]),d=!!c.length,u=i.length===o.length,p=c.every(g=>i.includes(g)),h=()=>`${i.length===o.length?"All":i.length} Values Selected`,f=g=>{const{value:x}=g.target;
226if(typeof x=="string")return;const b=x.filter(v=>!Tn(ive,v));let y=b;if(x.includes(Rc.all))u?y=[]:y=o.map(([v])=>v);else if(x.includes(Rc.others)){const v=b.filter(w=>l.includes(w));b.filter(w=>!l.includes(w)).length===c.length?y=v:y=[...v,...c]}s(y)};return a.jsx(Nt,{isLoading:r,children:a.jsxs(tt,{disabled:t,multiple:!0,onChange:f,renderValue:h,sx:{width:200,maxHeight:"40px"},value:i,children:[a.jsxs(Se,{className:u?"Mui-selected":"",value:Rc.all,children:[a.jsx(et,{checked:u,indeterminate:!!i.length&&!u}),a.jsx(Kt,{primary:"Select All"})]}),d&&a.jsxs(Se,{className:p?"Mui-selected":"",value:Rc.others,children:[a.jsx(et,{checked:p}),a.jsx(Kt,{primary:`Select Others (${c.length})`})]},Rc.others),a.jsx(St,{}),l.map(g=>a.jsxs(Se,{value:g,children:[a.jsx(et,{checked:i.includes(g)}),a.jsx(Kt,{primary:g})]},g))]})})},kw=({dataLoading:e,excludedAttributes:t=[],mediaAttributes:n,metaDataLoading:r,onChange:s,selectedMediaAttribute:i})=>{const o=m.useMemo(()=>{if(!t?.length)return n;const c=new Set(t);return Object.fromEntries(Object.entries(n).filter(d=>!c.has(d[0])))},[t,n]),l=({target:{value:c}})=>{Tn(kU,c)&&s(c)};return a.jsx(Ar,{value:i,disabled:e,isLoading:r,onChange:l,options:o,sx:{width:"180px",maxWidth:"250px"}})},qu=({disabled:e,isLoading:t,onClick:n})=>a.jsx(Nt,{isLoading:t,children:a.jsx(re,{color:"secondary",disabled:e,onClick:n,size:"small",sx:{alignSelf:"flex-start",minWidth:130},variant:"text",children:"Reset All Filters"})}),bg=rt("div")(({theme:e})=>({[`.${Zr.tooltipContainer}`]:{backgroundColor:e.palette.surface.tertiary,marginBottom:"4px",borderBottom:`1px solid ${e.palette.border.default}`,padding:"6px",color:e.palette.text.primary},[`.${Zr.tooltipItemContainer}`]:{display:"flex",flexFlow:"column wrap",maxHeight:"210px",flexWrap:"wrap"},[`.${Zr.tooltipItem}`]:{padding:"6px 10px 5px 10px",textAlign:"left",justifyContent:"left",alignItems:"center",display:"flex",color:e.palette.text.primary}})),ave=()=>{const{dispatch:e,getMediaData:t,mediaDataLoading:n,metaData:r,metaDataLoading:s,track:i}=Co(),o=()=>{const{nextDateRange:l,nextKpi:c,nextTarget:d}=Ys({metaData:r,selectedDateRange:[null,null],selectedKpi:"",selectedTarget:""});e({type:"resetFilters",value:{conversionType:Wu,selectedDateRange:l,selectedKpi:c,selectedTarget:d,valueToShow:xg}}),i("reset"),t({nextDateRange:l,nextKpi:c,nextTarget:d})};return a.jsx(qu,{disabled:n,isLoading:s,onClick:o})},ove=["89%","76%","70%","65%","51%","47%","40%","32%","20%","11%"],lve=()=>a.jsxs(T,{height:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:20,width:"25%"}),a.jsx($,{sx:{width:"100%",pl:"40px",pb:"40px",height:"250px"},direction:"row",spacing:3,alignItems:"flex-end",children:ove.map((e,t)=>a.jsx(fe,{variant:"rounded",animation:"pulse",height:e,sx:{flex:1}},`skeleton-item-${t}`))})]}),cve=({metricsByGl:e,valueToShow:t,theme:n,currency:r})=>{const{palette:s,typography:i}=n,{chartSet:o}=s,{secondary:l}=s.text,{fontFamily:c=""}=i,d=Array.from(e.entries()).sort((b,y)=>y[1].metricTotal-b[1].metricTotal).filter(b=>b[1].metricTotal&&b[0]),u=d.map(b=>b[0]),p=d.map(b=>b[1].metricTotal),h=d.reduce((b,y)=>b+y[1].metricTotal,0),f=b=>t==="roas"?`${(b*100).toFixed(2)}%`:t==="impressions"||t==="conversions"?b.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):new Intl.NumberFormat("en-US",{style:"currency",currency:r,minimumFractionDigits:2,maximumFractionDigits:2}).format(b),g=b=>{const y=b.map(C=>{if(!C.value)return"";const w=(C.value/h*100).toFixed(2);return` 227 <div class="${Zr.tooltipItem}"> 228 ${C.marker} <span style="font-size: 12px"><b>${f(C.value)}</b> (${w}%)</span> 229 </div> 230 `});return` 231 <div class="${Zr.tooltipContainer}"">${b[0]?b[0].name:""}</div> 232 <div class="${Zr.tooltipItemContainer}">${y.join("")}</div> 233 `},x={name:"Metrics",type:"bar",data:p.map((b,y)=>({value:b,itemStyle:{color:o[y%o.length],borderRadius:[5,5,0,0]}})),emphasis:{focus:"none"}};return{animation:!0,grid:{left:"0%",right:"5%",bottom:"0%",top:"10%",containLabel:!0},xAxis:{type:"category",axisTick:{show:!1},splitLine:{show:!1}
233,axisLine:{show:!1},axisLabel:{color:l,fontFamily:c||"",fontSize:11,rotate:e.size>17?45:0,interval:e.size>17?"auto":0,overflow:"truncate",width:75},data:u},yAxis:{type:"value",axisLabel:{color:l,fontFamily:c||"",fontSize:11,formatter:b=>f(b)},axisTick:{show:!1},splitLine:{show:!1}},tooltip:{trigger:"axis",axisPointer:{type:"none"},padding:0,backgroundColor:s.background.paper,borderColor:s.border.default,borderWidth:1,textStyle:{color:s.text.primary,fontFamily:c},formatter:g},series:[x],color:o}},Ew=e=>`${e}-${new Date().toISOString()}`,dve=e=>({export:{csv:{filename:e},png:{filename:e},svg:{filename:e}}}),Xo=(e,t)=>({...t,toolbar:{...t?.toolbar,...dve(e)}}),wo=(e,t)=>({chart:{type:"bar",height:350,stacked:!0,foreColor:e.palette.grey[600],fontFamily:e.typography.fontFamily,events:{click:(n,r,s)=>{const{className:i}=n.target;if(typeof i!="string")return;let o;if(i.includes("exportCSV")?o="csv":i.includes("exportSVG")?o="svg":i.includes("exportPNG")&&(o="png"),o){const{[o]:l}=s.config.chart.toolbar.export;l.filenameWithoutTimestamp||=l.filename,l.filename=Ew(l.filenameWithoutTimestamp),t&&t("download",{chartName:l.filenameWithoutTimestamp,fileType:o})}}},toolbar:{show:!0,tools:{download:`<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none !important"> 234 <path d="M17.5 12.5V15.8333C17.5 16.2754 17.3244 16.6993 17.0118 17.0118C16.6993 17.3244 16.2754 17.5 15.8333 17.5H4.16667C3.72464 17.5 3.30072 17.3244 2.98816 17.0118C2.67559 16.6993 2.5 16.2754 2.5 15.8333V12.5" stroke="#5A566A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 235 <path d="M5.8335 8.33337L10.0002 12.5L14.1668 8.33337" stroke="#5A566A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 236 <path d="M10 12.5V2.5" stroke="#5A566A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 237</svg>`}},zoom:{enabled:!1}},responsive:[{breakpoint:480,options:{legend:{position:"bottom",offsetX:-10,offsetY:0}}}],plotOptions:{bar:{horizontal:!1,columnWidth:"60%",borderRadius:6,dataLabels:{total:{enabled:!1}}}},xaxis:{categories:[],axisBorder:{show:!1},axisTicks:{show:!1}},yaxis:{labels:{offsetX:-6,formatter:n=>new Intl.NumberFormat("en",{notation:"compact"}).format(n)}},dataLabels:{enabled:!1},legend:{position:"top",horizontalAlign:"left",markers:{radius:8}},fill:{opacity:1},grid:{show:!1,padding:{left:-5,right:0,top:0,bottom:0}},tooltip:{theme:e.palette.mode==="dark"?"dark":"light",y:{formatter:n=>new Intl.NumberFormat("en",{minimumFractionDigits:2,maximumFractionDigits:2}).format(n)}}}),uve=(e,t)=>{const n=wo(e,t);return{...n,chart:{...n.chart,toolbar:{...n.chart?.toolbar,offsetY:-35}}}},pve=(e,t="USD",n)=>{const r=wo(e,n);return{...r,chart:{...r.chart,toolbar:{...r.chart?.toolbar,offsetY:-35}},yaxis:{labels:{offsetX:-6,formatter:s=>new Intl.NumberFormat("en",{notation:"compact",style:"currency",currency:t}).format(s)}},tooltip:{...r.tooltip,y:{formatter:s=>new Intl.NumberFormat("en",{minimumFractionDigits:2,maximumFractionDigits:2,style:"currency",currency:t}).format(s)}}}},hve=(e,t)=>{const n=wo(e,t);return{...n,chart:{...n.chart,toolbar:{...n.chart?.toolbar,offsetY:-35}}}},fve=(e,t,n,r)=>{const s=wo(n,r),i=s.chart?.events||{};return{...s,chart:Xo(Ew("Highest-Converting-Journeys"),{...s.chart,stacked:!1,type:"rangeBar",events:{...i,dataPointSelection:(o,l,c)=>{const d=c.w.config.series[c.seriesIndex].data[c.dataPointIndex].x;e(Number(d))}},toolbar:{...s.chart?.toolbar,offsetY:-25},animations:{enabled:!1}}),plotOptions:{bar:{...s.plotOptions?.bar,horizontal:!0,rangeBarGroupRows:!0,barHeight:"60%",borderRadius:2}},tooltip:{...s.tooltip,custom({dataPointIndex:o,seriesIndex:l,w:c}){const{name:d,customName:u}=c.config.series[l],{x:p,y:[,h]}=c.globals.initialSeries[l].data[o];return`<div class="insights-journey-tooltip"> Journey Touchpoint ${Math.floor(h)}, Length ${p}: ${u||d}</div>`}},yaxis:{labels:{offsetX:11,offsetY:4,formatter:o=>`${Number(o)}`},title:{text:"Journey Touchpoint Length"}},xaxis:{...s.xaxis,labels:{show:!1},title:{text:"Touchpoint Number",offsetX:-40,offsetY:-20}},grid:{show:!1,padding:{left:5,right:-30,top:0,bottom:0}},legend:{position:"bottom",horizontalAlign:"left",markers:{radiu
237s:8},onItemClick:{toggleDataSeries:!1}},colors:t}},mve=(e,t=0,n)=>{const r=wo(e,n);return{chart:Xo(Ew("Media-Type-Touchpoint-Percentages"),{...r.chart,height:550,type:"treemap",toolbar:{...r?.chart?.toolbar,offsetY:-25+t},animations:{enabled:!1}}),plotOptions:{treemap:{distributed:!1,enableShades:!1}},dataLabels:{enabled:!0,style:{colors:["#fff"],fontSize:"14px",fontWeight:600},formatter:(s,i)=>{const o=i.value??0;return`${s} 238${o}%`}},yaxis:{labels:{formatter:s=>`${s}%`}}}},_w=rt(ua)(({theme:e})=>({".apexcharts-menu-icon svg":{fill:"none !important"},".apexcharts-menu-icon svg path":{stroke:`${e.palette.icon.default} !important`},".apexcharts-menu-icon":{transform:"none"},".apexcharts-canvas":{display:"flex",flexDirection:"row",alignItems:"flex-start"},".apexcharts-svg":{overflow:"visible"},".apexcharts-menu":{backgroundColor:e.palette.background.paper,border:`1px solid ${e.palette.border.default}`},".apexcharts-menu-item":{color:e.palette.text.primary},".apexcharts-menu-item:hover":{backgroundColor:e.palette.background.secondary.hovered},".apexcharts-tooltip":{backgroundColor:`${e.palette.background.paper} !important`,border:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`},".apexcharts-tooltip-title":{backgroundColor:`${e.palette.surface.tertiary} !important`,borderBottom:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`}}));rt(_w)({});const dF=rt(_w)({".insights-journey-tooltip":{padding:"8px 16px"}}),gve=rt(dF)({".apexcharts-menu-item":{"&.exportCSV":{display:"none"}}}),xve=(e,t)=>{const n=wo(e,t);return{...n,xaxis:{...n.xaxis,categories:[]},legend:{...n.legend,horizontalAlign:"center",offsetY:20},plotOptions:{bar:{distributed:!0,borderRadius:6,borderRadiusApplication:"end"}},chart:{...n.chart,height:332,width:1600},tooltip:{y:{...n.tooltip?.y,title:{formatter:()=>""}}}}},bve=(e,t)=>{const n=wo(e,t);return{...xve(e,t),tooltip:{theme:e.palette.mode==="dark"?"dark":"light",y:{...n.tooltip?.y},shared:!0,intersect:!1,custom:({dataPointIndex:s,w:i})=>{const o=i.globals.tooltip.tooltipTitle.outerHTML,{series:l,seriesPercent:c}=i.globals,p=i.globals.tooltip.ttItems.map((h,f)=>{const g=c[f][s];return{val:l[f][s],html:h.outerHTML.replace("</div>",`<span> (${new Intl.NumberFormat("en",{maximumFractionDigits:2}).format(Number(g))}%)</span></div>`)}}).sort((h,f)=>f.val-h.val).slice(0,36).reduce((h,f)=>h+f.html,"");return`${o}<div class='media-stacked-chart'>${p}</div>`}}}},yve=(e,t)=>{switch(t){case"stackedBar":{const n=e.dataset[0].dimensions;return e.dataset[0].source.map(s=>{const i={};return n.forEach(o=>{i[Pr(o)]=s[o]}),i})}case"bar":{const n=e.xAxis[0].data,r=e.series[0].data;return n.map((s,i)=>({Category:s,Value:r[i]?r[i].value:void 0}))}default:return[]}},uF=(e,t)=>{if(e.current){const n=e.current.getEchartsInstance();if(n){const r=n.getOption(),s=yve(r,t),i=ow.unparse(s),o=new Blob([i],{type:"text/csv;charset=utf-8;"});return URL.createObjectURL(o)}}return null},vve=(e,t,n)=>{const r=new Map;return e.forEach((s,i)=>{let o=0,l=0,c=0;s.forEach(d=>{l+=d[t]||0,c+=d.investment,o+=d.conversions}),r.set(i,{metricTotal:l,conversionsTotal:o,investmentTotal:c})}),t!=="conversions"&&t!=="roas"?r.forEach((s,i)=>{s&&s.conversionsTotal&&s.conversionsTotal!==0?r.set(i,{metricTotal:Math.ceil(s.metricTotal/s.conversionsTotal)}):r.delete(i)}):t==="roas"&&r.forEach((s,i)=>{s&&s.investmentTotal&&s.conversionsTotal&&n?r.set(i,{metricTotal:s.conversionsTotal*n/s.investmentTotal}):r.delete(i)}),r},MT=({metric:e,metricsByGlAndMonth:t})=>{const n=Array.from(t).reduce((r,[s,i])=>{const o={conversions:0,impressions:0,investment:0,roas:0};return Array.from(i.values()).forEach(l=>{const c=l;o.conversions+=c.conversions,o.impressions+=c.impressions,o.investment+=c.investment,o.roas+=c.roas}),r[s]=o,r},{});return Object.entries(n).reduce((r,[s,i])=>{let o;switch(e){case"conversions":o=i.conversions;break;case"impressions":o=i.conversions?i.impressions/i.conversions:0;break;case"investment":o=i.conversions?i.investment/i.conversions:0;break;default:o=0;break}return r[s]=o,r},{})},Cve=({metricsByGl:e,chartRef:t,mediaAttribute:n,mediaAttributes:r,track:s})=>{const{mediaDataLoading:i,metaDataLoading:o,state:{valueToShow:l}}=Co(),{engagementCurrency:c}=pe(),d=i||o,u=Re(),p=m.useMemo(()=>cve({metricsByGl:e,valueToShow:l,theme:u,currency:c}),[e,l,u,c]),h=!e.size,f=m.useCallback(x=>{const b=`Conversion-Summary-${Fr[l||"conversions"]}-By-${r[n]}-${new Date().toLocaleDateString()}`;return x==="csv"?{dataUrl:uF(t,"bar")||"",fileName:b}:x==="png"&&t.current?{dataUrl:t.current.getEchartsInstance().getDataURL({backgroundColor:"white"}),fileName:b}:{dataUrl:"",error:!0,fileName:""}},[n]),g=m.useCallback(({fileName:x,fileType:b})=>{s("download",{chartName:x,fileType:b})},[s]);return a.jsx(Ve,{children:a.jsx(Ue,{children:d?a.jsx(lve,{}):a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between"},children:[a.jsxs(I,{children:[Fr[l||"conversions"]," By"," ",r[n]]}),a.jsxs(T,{sx:{alignItems:"center",display:"flex",justifyContent:"space-around",zIndex:1e3},children:[a.jsx(T,{sx:{px:2},children:"Show: "}),a.jsx(eve,{}),a.jsx(T,{sx:{pl:1},children:a.jsx(Rm,{getFileData:f,onDownload:g,disabled:h})})]})]}),a.jsx(T,{sx:{alignItems:"center",minHeight:"360px",overflowY:"visible"},children:a.jsx(gs,{isDataEmpty:h,children:a.jsx(bg,{children:a.jsx(Fl,{notMerge:!0,option:p,ref:t,style:{height:360}})})})})]})})})},wve=Ne.memo(Cve),pF=({categories:e,chartRef:t,source:n,stacks:r})=>{const[s,i]=m.useState(0),{width:o}=EU({debounceDelay:250});return m.useEffect(()=>{if(t.current){const l=t.current.getEchartsInstance();
238if("_componentsViews"in l&&Array.isArray(l._componentsViews)){const c=l._componentsViews.find(d=>d.type==="legend.plain");if(c){const d=c?._backgroundEl?.shape?.height??0;i(d)}}}},[e,t,n,r,o]),s},hF=20,Sve=32,Tw=350,fF=e=>Z(e).format("MMM YYYY"),jve=e=>t=>{const n={minimumFractionDigits:2,maximumFractionDigits:2};return new Intl.NumberFormat("en",n).format(t)},kve=e=>{if(!e.length||!e[0])return"";const t=Object.values(e[0].value).reduce((r,s)=>typeof s=="number"?r+s:r,0),n=e.map(r=>{const s=Number(r.value[r.seriesName])||0,i=I2.format(s/t);return` 239 <div class="${Zr.tooltipItem}"> 240 ${r.marker} <span style="font-size: 12px">${r.seriesName}: <b>${new Intl.NumberFormat("en",{minimumFractionDigits:2,maximumFractionDigits:2}).format(s)}</b> (${i})</span> 241 </div> 242 `});return` 243 <div class="${Zr.tooltipContainer}"">${fF(e[0].name)}</div> 244 <div class="${Zr.tooltipItemContainer}">${n.join("")}</div> 245 `},Eve=(e=0)=>()=>({type:"bar",datasetIndex:e,stack:"total",label:{show:!1},barMaxWidth:"60%",emphasis:{focus:"none"}}),_ve=({categories:e,datasetOptions:t,isCurrency:n,legendHeight:r,source:s,theme:i})=>{const{palette:o,typography:l}=i,{chartSet:c}=o,{secondary:d}=o.text,{fontFamily:u=""}=l,p=[{dimensions:e,source:s}];return t&&p.push(t),{animation:!0,tooltip:{trigger:"axis",axisPointer:{type:"none"},confine:!0,padding:0,backgroundColor:o.background.paper,borderColor:o.border.default,borderWidth:1,textStyle:{color:o.text.primary,fontFamily:u},formatter:kve},legend:{textStyle:{color:d,fontFamily:u,padding:-6},icon:"circle",itemGap:7,selectedMode:!1,padding:[0,5,0,5]},grid:{top:r+16,right:32,bottom:32,left:32,containLabel:!0},dataset:p,xAxis:{type:"category",axisLabel:{color:d,fontFamily:u||"",fontSize:11,formatter:fF},axisLine:{show:!1},axisTick:{show:!1}},yAxis:{position:"left",axisLabel:{formatter:jve()},splitLine:{show:!1}},series:Array.from({length:e.length-1},Eve(p.length-1)),color:c}},Tve=({categories:e,chartRef:t,source:n})=>{const r=Re(),s=pF({categories:e,chartRef:t,source:n}),i=m.useMemo(()=>_ve({categories:e,datasetOptions:{transform:{type:"sort",config:{dimension:"month",order:"asc"}}},isCurrency:!1,legendHeight:s,source:n,theme:r}),[e,s,n,r]),o=!e.length||!n.length;return a.jsx(gs,{isDataEmpty:o,children:a.jsx(bg,{children:a.jsx(Fl,{notMerge:!0,option:i,ref:t,style:{height:Tw}})})})},Ive=["89%","69%","76%"],Dve=()=>a.jsxs(T,{height:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:hF,width:300}),a.jsx($,{sx:{height:Tw,p:"32px",width:"100%"},direction:"row",spacing:8,alignItems:"flex-end",children:Ive.map((e,t)=>a.jsx(fe,{variant:"rounded",animation:"pulse",height:e,sx:{flex:1}},`skeleton-item-${t}`))})]}),Ave=({loading:e,presentBy:t,source:n,track:r})=>{const s=m.useRef(null),i=m.useMemo(()=>{const c=new Set;return n.map(d=>Object.keys(d).forEach(c.add,c)),Array.from(new Set(["month",...c]))},[n]),o=m.useCallback(c=>{const d=`Conversion-Summary-${Fr.conversions}-By-${t}-By-Month-${new Date().toLocaleDateString()}`;return c==="csv"?{dataUrl:uF(s,"stackedBar")||"",fileName:d}:c==="png"&&s.current?{dataUrl:s.current.getEchartsInstance().getDataURL({backgroundColor:"white"}),fileName:d}:{dataUrl:"",error:!0,fileName:""}},[t]),l=m.useCallback(({fileName:c,fileType:d})=>{r("download",{chartName:c,fileType:d})},[r]);return a.jsx(Ve,{children:a.jsx(Ue,{children:e?a.jsx(Dve,{}):a.jsxs(a.Fragment,{children:[a.jsxs(T,{height:hF,display:"flex",justifyContent:"space-between",mb:Sve/8,children:[a.jsxs(I,{children:[Fr.conversions," By ",t," By Month"]}),a.jsx(Rm,{getFileData:o,onDownload:l,disabled:!n.length})]}),a.jsx(T,{sx:{width:"100%",height:Tw,overflow:"auto"},children:a.jsx(Tve,{categories:i,chartRef:s,source:n})})]})})})},Mve=Ne.memo(Ave),Rve=(e,t)=>m.useMemo(()=>!t||!(t in(e[0]||{}))?new Map:e.filter(r=>r.GL_TYPE_NAME?.toLowerCase()!=="base").reduce((r,s)=>{if(s.month&&t in s&&typeof s[t]=="string"){const o=Z(s.month).format("MMM-YYYY"),l=String(s[t]),c=r.get(l)||new Map,d=c.get(o)||{};d.conversions=(d.conversions||0)+s.conversions,d.impressions=(d.impressions||0)+s.impressions,d.investment=(d.investment||0)+s.investment,d.roas=(d.roas||0)+(s.roas||0),c.set(o,d),r.set(l,c)}return r},new Map),[e,t]),RT=20,Nve=()=>{const{dispatch:e,getMediaData:t,mediaClassifications:n,mediaData:r,mediaDataLoading:s,metaDataLoading:i,valuePerConversion:o,state:{mediaAttribute:l,valueToShow:c},track:d}=Co(),u=m.useRef(null),p=s||i,h=Rve(r,l),f=m.useMemo(()=>MT({metric:c,metricsByGlAndMonth:h}),[c,h]),[g,x]=m.useState(Object.entries(f).sort((w,S)=>S[1]-w[1]).slice(0,RT).map(([w])=>w)),b=m.useMemo(()=>{const w=new Set(g),S=new Map;return h.forEach((E,k)=>{w.has(k)&&k!=="Unclassified"&&S.set(k,E)}),S},[g,h]),y=m.useMemo(()=>{const w=new Set(g),S=r.filter(j=>j.GL_TYPE_NAME!=="Base"&&j?.[l]&&w.has(j?.[l]??"")&&j.conversions),E=Ws(S,aY("month"));return Object.entries(E).map(([j,_])=>{const D={month:j};return _.forEach(M=>{const N=M[l]??"";D[N]=(Number(D[N])||0)+M.conversions}),D}).map(j=>Object.fromEntries(Object.entries(j).sort(([,_],[,D])=>Number(D)-Number(_))))},[l,g,r]),v=n[l],C=m.useCallback(w=>
245{e({type:"mediaAttribute",value:w}),d("presentBy",{pivot:w}),t({nextMediaAttribute:w})},[e,t,d]);return m.useEffect(()=>{x(Object.entries(MT({metric:c,metricsByGlAndMonth:h})).sort((w,S)=>S[1]-w[1]).slice(0,RT).map(([w])=>w))},[c,h]),a.jsx(T,{children:a.jsxs($,{spacing:2,children:[a.jsxs($,{direction:"row",spacing:2,justifyContent:"space-between",children:[a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:a.jsx(I,{variant:"h6",mb:3,marginBottom:"0px",children:"Media Details"})}),a.jsxs($,{direction:"row",spacing:2,children:[a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:"Present By:"}),a.jsx(kw,{dataLoading:s,mediaAttributes:n,metaDataLoading:i,onChange:C,selectedMediaAttribute:l}),a.jsx(cF,{data:f,dataLoading:s,onChange:x,limit:20,metaDataLoading:i,values:g})]})]}),a.jsxs($,{spacing:3,children:[a.jsx(wve,{metricsByGl:vve(b,c,o),chartRef:u,mediaAttribute:l||"GL_TYPE_NAME",mediaAttributes:n,track:d}),a.jsx(Mve,{loading:p,presentBy:v||"",source:y,track:d})]})]})})},Ove=()=>{const e=Re(),{palette:{chartBrand:t}}=e,{mediaData:n,mediaDataLoading:r,metaDataLoading:s,track:i}=Co(),{engagementCurrency:o}=pe(),l=r||s,c=(b,y)=>y.reduce((v,C)=>(v.push({y:b[C]||0,x:Z(C).format("MMM")}),v),[]),d=b=>b.sort((y,v)=>Z(y).isAfter(Z(v))?1:-1),u=m.useMemo(()=>{const b={},y={},v={},C={},w=new Set;let S=0,E=0,k=0,j=0;n.forEach(({conversions:D,investment:M,impressions:N,month:O,GL_TYPE_NAME:R})=>{const L=R==="Base";S+=D,k+=M,j+=N,L&&(E+=D),O&&(w.add(O),b[O]?b[O]+=L?0:D:b[O]=L?0:D,y[O]?y[O]+=L?D:0:y[O]=L?D:0,v[O]?v[O]+=M:v[O]=M,C[O]?C[O]+=N:C[O]=N)});const _=d(Array.from(w));return{chartSeriesConversionsBase:c(y,_),chartSeriesConversions:c(b,_),chartSeriesInvestment:c(v,_),chartSeriesImpressions:c(C,_),total:{conversionsTotal:S,investmentTotal:k,impressionsTotal:j,baseFraction:E/S}}},[n]),p=pw(u.total.investmentTotal),h=uve(e,i),f=pve(e,o,i),g=hve(e,i),x={enabled:!0,position:"topLeft",offsetX:50};return a.jsxs(T,{children:[a.jsx(I,{variant:"h6",mb:3,children:"Summary"}),a.jsxs($,{direction:{base:"column",lg:"row"},gap:4,alignItems:"stretch",justifyContent:"stretch",children:[a.jsx(Og,{loading:l,title:"Conversions",titleValue:fg(u.total.conversionsTotal),isDataEmpty:!u.total.conversionsTotal,options:{...h,colors:[t.main.bolder,t.main.light],chart:Xo("ConversionSummary-Conversions",h.chart),tooltip:{...h.tooltip,fixed:x,y:{formatter:(b,{series:y,seriesIndex:v,dataPointIndex:C})=>{const w=y.reduce((E,k)=>E+(k[C]??0),0),S=y[v][C];return`${new Intl.NumberFormat("en",{minimumFractionDigits:2,maximumFractionDigits:2}).format(S)} (${(S*100/w).toFixed(2)}%)`}}},legend:{position:"top",horizontalAlign:"right",floating:!0}},series:[{data:u.chartSeriesConversionsBase,name:"Base"},{data:u.chartSeriesConversions,name:"Media Driven"}],subtext:u.total.baseFraction?`Base is ${(u.total.baseFraction*100).toFixed(2)}% of conversions`:void 0}),a.jsx(Og,{loading:l,title:"Spend",titleValue:a.jsxs(I,{variant:"h5",display:"flex",flexDirection:"row",alignItems:"center",color:p?"inherit":"text.disabled",children:[a.jsx(Dl,{sx:{fontSize:"28px",marginLeft:1}}),p||"n/a"]}),isDataEmpty:!u.total.investmentTotal,options:{...f,colors:[t.secondary.bold],chart:Xo("ConversionSummary-Spend",f.chart),tooltip:{...f.tooltip,fixed:x}},series:[{data:u.chartSeriesInvestment,name:""}]}),a.jsx(Og,{loading:l,title:"Impressions",titleValue:D2(u.total.impressionsTotal),isDataEmpty:!u.total.impressionsTotal,options:{...g,colors:[t.tertiary.bold],chart:Xo("ConversionSummary-Impressions",g.chart),tooltip:{...g.tooltip,fixed:x}},series:[{data:u.chartSeriesImpressions,name:""}]})]})]})},Pve=()=>{const{handleConversionTypeChange:e,mediaDataLoading:t,metaDataLoading:n,state:{conversionType:r}}=Co(),s=t||n;return a.jsxs($,{direction:"column",gap:5,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(ho,{loading:s}),a.jsxs($,{gap:2.5,children:[a.jsx(Xt,{title:"Conversion Summary"}),a.jsxs($,{direction:"row",justifyContent:"space-between",children:[a.jsx(Mm,{disabled:s,isLoading:n,onChange:e,value:r}),a.jsx(ave,{})]}),a.jsx(Zye,{})]}),a.jsx(Ove,{}),a.jsx(Nve,{})]})},Lve={conversionType:Wu,mediaAttribute:"GL_TYPE_NAME",selectedDateRange:[null,null],selectedKpi:"",selectedTarget:"",valueToShow:xg},Fve=(e,t)=>
245t.type in e?{...e,[t.type]:t.value}:t.type==="filtersBar"||t.type==="resetFilters"?{...e,...t.value}:e,$ve=()=>{const e=Hu("summary"),[t,n]=m.useReducer(Fve,Lve),{conversionType:r,mediaAttribute:s,selectedDateRange:i,selectedKpi:o,selectedTarget:l}=t,c=cP(o),d=m.useCallback(({type:E,value:k})=>{switch(E){case"conversionType":n({type:E,value:k}),e("conversionType",{conversionType:k});break;case"filtersBar":n({type:E,value:{selectedDateRange:k.nextDateRange,selectedKpi:k.nextKpi,selectedTarget:k.nextTarget}});break}},[e]),{availableDateRange:u,getMediaData:p,getMetaData:h,handleConversionTypeChange:f,kpiOptions:g,mediaClassifications:x,mediaData:b,mediaDataLoading:y,metaData:v,metaDataLoading:C,targetOptions:w}=Sw({conversionType:r,datePart:"month",mediaAttribute:s,onFilterChange:d,requiredColumns:["GL_TYPE_NAME"],selectedDateRange:i,selectedKpi:o,selectedTarget:l}),S=m.useMemo(()=>({availableDateRange:u,dispatch:n,getMediaData:p,getMetaData:h,handleConversionTypeChange:f,kpiOptions:g,mediaClassifications:x,mediaData:b,mediaDataLoading:y,metaData:v,metaDataLoading:C,state:t,targetOptions:w,track:e,valuePerConversion:c}),[u,n,p,h,f,g,x,b,y,v,C,t,w,e,c]);return a.jsx(lF.Provider,{value:S,children:a.jsx(Pve,{})})},mF=m.createContext(null),Gu=()=>m.useContext(mF),yg=e=>Object.entries(e.reduce((t,{kpiName:n,kpiNiceId:r})=>(n&&r&&(t[n]=r),t),{})).map(([t,n])=>({name:t,niceId:n})).sort((t,n)=>t.name.localeCompare(n.name)),zve=e=>yg(e)[0]?.niceId||"",NT=({dateRange:e,dateType:t="event",metaDataItem:n})=>{const[r,s]=e;if(!r||!s)return!1;const i=Z(t==="event"?n.minEventDate:n.minMediaDate),o=Z(t==="event"?n.maxEventDate:n.maxMediaDate);return!!((r.isSame(i)||r.isAfter(i))&&(s.isSame(o)||s.isBefore(o)))},mv=({data:e,kpi:t})=>t&&e.find(({kpiNiceId:n})=>n===t)||null,OT=e=>{const{maxEventDate:t,minEventDate:n}=e,r=Z(n),s=Z(t),i=Ui(s,"last3Months");return i[0].isBefore(r)?[r,s]:i},Iw=({dateType:e="event",metaData:t,selectedKpi:n})=>{const r=mv({data:t,kpi:n});let s=[null,null];if(r){const i=Z(e==="event"?r.minEventDate:r.minMediaDate),o=Z(e==="event"?r.maxEventDate:r.maxMediaDate);s=[i,o]}return s},wi=({dateType:e="event",metaData:t,selectedDateRange:n,selectedKpi:r})=>{let s="",i=[null,null];const o=mv({data:t,kpi:r});if(o)s=o.kpiNiceId,NT({dateType:e,metaDataItem:o,dateRange:n})?i=n:i=OT(o);else{s=zve(t);const l=mv({data:t,kpi:s});l?NT({dateType:e,metaDataItem:l,dateRange:n})||(i=OT(l)):We("No meta data found- code error")}return{nextDateRange:i,nextKpi:s}},Bve=rt(sn)({".MuiFormControlLabel-label":{fontSize:14,fontWeight:500,paddingTop:"2px"}}),Uve=()=>{const{state:{dateType:e,selectedDateRange:t,selectedKpi:n},dataLoading:r,dispatch:s,metaData:i,metaDataLoading:o,track:l}=Gu(),c=m.useMemo(()=>yg(i),[i]),[d,u]=m.useMemo(()=>Iw({dateType:e,metaData:i,selectedKpi:n}),[e,i,n]),p=m.useCallback(g=>{const{nextDateRange:x,nextKpi:b}=wi({dateType:e,metaData:i,selectedKpi:g,selectedDateRange:t});s({type:"filtersBar",value:{selectedDateRange:x,selectedKpi:b}}),l("kpi")},[s,e,i,t,l]),h=m.useCallback(g=>{s({type:"selectedDateRange",value:g}),l("dateRange")},[s,l]),f=m.useCallback(g=>{s({type:"dateType",value:g}),l("dateType")},[s,l]);return m.useEffect(()=>{const[g,x]=t;if(i.length&&(!n||!g||!x)){const{nextDateRange:b,nextKpi:y}=wi({dateType:e,metaData:i,selectedDateRange:t,selectedKpi:n});s({type:"filtersBar",value:{selectedDateRange:b,selectedKpi:y}})}},[s,e,i,t,n]),a.jsx(da,{dataFirstDate:d??void 0,dataLastDate:u??void 0,handleDatePickerOnChange:h,handleKpiOnChange:p,hideTargetAudience:!0,isDataLoading:r,isMetaLoading:o,kpiListOptions:c,selectedDateRange:t,selectedKpi:n,children:a.jsx(xn,{minWidth:300,direction:"row",justifyContent:{sm:"start",md:"flex-end"},flexGrow:1,children:a.jsx(Bve,{label:"Show by:",labelPlacement:"start",sx:{gap:2},control:a.jsx(Ar,{sx:{width:208},disabled:r,isLoading:o,onChange:({target:{value:g}})=>{g!=="event"&&g!=="media"||f(g)},options:{event:"Conversion Date",media:"Media Exposure Date"},value:e||""})})})})},Vve="Analyze how media spend made during a particular month translates into media-driven conversions during that month and beyond.",PT=bs(_w)({".media-stacked-chart":{flexFlow:"column wrap",maxHeight:"335px",flexWrap:"wrap",display:"flex"},".apexcharts-tooltip.apexcharts-theme-light, .apexcharts-tooltip.apexcharts-theme-dark":{height:"335px"},".media-stacked-chart .apexcharts-tooltip-series-group":{order:"1 !important"},".apexcharts-toolbar":{position:"sticky"}}),Wve=["69%","76%","85%","76%","69%"],LT=()=>a.jsxs(T,{height:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:20,width:"30%"}),a.jsx($,{sx:{width:"100%",pl:"40px",pb:"4px",pt:"40px",height:"350px"},direction:"row",spacing:8,alignItems:"flex-end",justifyContent:"space-around",children:Wve.map((e,t)=>a.jsx(fe,{variant:"rounded",animation:"pulse",height:e,width:"25%",sx:{flex:1,maxWidth:100}},`skeleton-item-${t}`))})]}),Hve=(e,t)=>
245{let n=0;return t?.reduce((r,s)=>(r.get(s.mediaType)||(r.set(s.mediaType,e[n]||""),n+=1),r),new Map)},FT=(e,t)=>{const n=m.useMemo(()=>t?.reduce((s,i)=>{const l=Z(e==="eventDate"?i.eventDate:i.mediaDate).format("MMM-YYYY"),c=s?.get(i.mediaType)||new Map,d=c?.get(l)||0;return c?.set(l,d+i.conversions),s?.set(i.mediaType,c),s},new Map),[t,e]),r=m.useMemo(()=>[...t?.reduce((i,o)=>{const l=e==="eventDate"?o.eventDate:o.mediaDate;return l&&i.add(l),i},new Set)??[]].map(i=>Z(i)).sort((i,o)=>i.isAfter(o)?1:-1),[t,e]);return{series:n,dateRange:r}},$T=({series:e,graphColors:t,dateRange:n,filename:r,xAxisTitle:s,theme:i,track:o})=>{const l=bve(i,o);if(!n)return{series:[],options:{...l}};const c=[];e?.forEach((u,p)=>{const h=e?.get(p),f=n.map(g=>Math.ceil(h?.get(g.format("MMM-YYYY"))||0));c.push({color:t?.get(p),name:p,data:f})});const d=n.map(u=>[u.format("MMM"),u.format("YYYY")]);return{series:c,options:{...l,chart:Xo(r,{...l.chart,stacked:!0,animations:{enabled:!0}}),colors:i?.palette.chartSet,legend:{...l.legend,show:!0},plotOptions:{bar:{...l?.plotOptions?.bar,columnWidth:"40%",distributed:!1}},xaxis:{...l.xaxis,categories:d,axisBorder:{show:!0,color:"#78909C",height:1,width:"100%",offsetX:25,offsetY:0},title:{text:s,offsetX:0,offsetY:0,style:{fontSize:"11px",lineHeight:"18px",fontWeight:600,cssClass:"apexcharts-xaxis-title"}}}}}},qve=()=>{const e=Re(),{palette:{chartSet:t}}=e,{insightsConversionLookbackLoading:n,insightsConversionLookback:r,track:s}=Gu(),i=m.useMemo(()=>Hve(t,r),[t,r]),{series:o,dateRange:l}=FT("eventDate",r),{series:c,dateRange:d}=FT("mediaDate",r),u=m.useMemo(()=>$T({series:o,graphColors:i,dateRange:l,filename:"Conversion-Lookback-Graph-by-Contribution",xAxisTitle:"Conversion Date",theme:e,track:s}),[o,i,l,e,s]),p=m.useMemo(()=>$T({series:c,graphColors:i,dateRange:d,filename:"Conversion-Lookback-Graph-by-Attribution",xAxisTitle:"Media Exposure Date",theme:e,track:s}),[c,i,d,e,s]),h=!u.series[0]?.data.length,f=!p.series[0]?.data.length;return a.jsxs(a.Fragment,{children:[a.jsx(Ve,{style:{marginBottom:40},children:a.jsx(Ue,{children:n?a.jsx(LT,{}):a.jsx(gs,{isDataEmpty:h,children:a.jsxs(a.Fragment,{children:[a.jsx(I,{children:"Contribution By Media Type"}),a.jsx(T,{sx:{overflowX:"auto",overflowY:"visible",minHeight:"700px",alignItems:"center"},children:a.jsx(PT,{series:u.series,options:u.options,type:"bar",height:"600px",width:"95%",sx:{minWidth:"600px"}})})]})})})}),a.jsx(Ve,{children:a.jsx(Ue,{children:n?a.jsx(LT,{}):a.jsx(T,{sx:{overflowX:"auto",overflowY:"visible",minHeight:"700px",alignItems:"center"},children:a.jsx(gs,{isDataEmpty:f,children:a.jsxs(a.Fragment,{children:[a.jsx(I,{children:"Attribution By Media Type"}),a.jsx(PT,{series:p.series,options:p.options,type:"bar",height:"600px",width:"95%",sx:{minWidth:"600px"}})]})})})})})]})},Gve="Displays the portion of media spend that is still impacting conversions across the selected months.",Yve="A breakdown of how media-driven conversions in a particular month were influenced by media spend attributed to earlier months.",Kve="Calculated as the total media spend through an exposure month divided by accumulated conversions for each conversion month.",Dw={totalsCell:"lookback--cell-total"},gv=rt(Mn)(({theme:e})=>{const{background:t,border:n}=e.palette,{spacing:r}=e,s=e.palette.mode==="dark",i={backgroundColor:t.paper,":hover":{backgroundColor:s?t.brand.subtle.hovered:t.brand.subtlest.default}};return{border:"none",borderRadius:"6px",backgroundColor:t.paper,overflow:"hidden",[`.${Dw.totalsCell}`]:{".MuiTypography-root":{fontWeight:"bold"}},".MuiDataGrid-cell":{border:"none",paddingLeft:r(2),paddingRight:r(1),"&:nth-of-type(2)":{borderRight:`1px dashed ${n.default}`},"&:focus":{outline:"none"},"&:focus-within":{outline:"none"}},".MuiDataGrid-columnHeader":{":focus-within":{outline:"none"},border:"none","&:nth-of-type(2)":{borderRight:`1px dashed ${n.default}`}},".MuiDataGrid-columnHeader--filledGroup":{borderRight:`1px dashed ${n.default}`,"&:last-child":{border:"none"}},".MuiDataGrid-columnHeadersInner":{".MuiDataGrid-columnHeader":{paddingLeft:r(2),paddingRight:r(2)}},".MuiDataGrid-columnHeaders":{backgroundColor:t.tableHeader,borderBottom:`2px solid ${n.default}`,border:"none",borderRadius:"6px 6px 0 0",overflow:"hidden"},".MuiDataGrid-columnHeaderTitleContainer":{border:"none !important"},".MuiDataGrid-columnHeaderTitleContainerContent":{fontSize:12,height:18,textTransform:"uppercase",border:"none",fontWeight:600},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-row":{...i},".MuiDataGrid-row:nth-of-type(even)":{...i},".MuiDataGrid-row:last-of-type":{borderBottomLeftRadius:"6px",borderBottomRightRadius:"6px",fontWeight:"bold"}}});gv.defaultProps={...gv.defaultProps,autoHeight:!0,columnHeaderHeight:36,disableColumnMenu:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,experimentalFeatures:{columnGrouping:!0},getRowClassName:e=>e.row.id==="Total"?Dw.totalsCell:"",hideFooter:!0,localeText:{toolbarExport:"Download"},rowHeight:48};const zT={top:"-56px",position:"absolute"},Qve=({csvFileName:e,isLoading:t=!1,onClickDownload:n})=>a.jsx(km,{sx:{display:"flex",justifyContent:"flex-end"},children:a.jsx(Nt,{isLoading:t,sx:zT,children:a.jsx(vC,{disabled:t,variant:"outlined",color:"secondary",printOptions:{disableToolbarButton:!0},sx:{...zT,position:t?"relative":"absolute"},csvOptions:{fileName:`${e}-${new Date().toISOString()}`},onClick:n})})}),Jve=()=>
245a.jsx($,{sx:{gap:.5,my:"6px",mx:.5},children:Array(2).fill(null).map((e,t)=>a.jsx(fe,{variant:"rounded",height:38},`${t}-skeleton-item`))}),Xve=()=>a.jsx(DM,{sx:{minHeight:"100px"}}),sb=({columnGroupingModel:e,columns:t,csvFileName:n,rows:r,subtitle:s,title:i})=>{const{insightsConversionLookbackLoading:o,metaDataLoading:l,dataLoading:c,track:d}=Gu(),u=o||l||c,p=()=>d("download",{chartName:n,fileType:"csv"});return a.jsxs($,{direction:"column",alignItems:"center",gap:"20px",children:[a.jsxs($,{direction:"column",gap:"8px",alignItems:"flex-start",width:"100%",children:[a.jsx(I,{variant:"h6",children:i}),a.jsx(I,{variant:"subtitle2",fontWeight:"400",width:"75%",children:s})]}),a.jsx("div",{style:{width:"100%"},children:a.jsx(gv,{columnGroupingModel:e,columns:t,loading:u,rows:u?[]:r,slots:{loadingOverlay:Jve,noRowsOverlay:Xve,toolbar:Qve},slotProps:{toolbar:{csvFileName:n,isLoading:u,onClickDownload:p}}})})]})},BT=e=>Z(e).format("MMM YYYY"),Zve=e=>lY(Ws(e,t=>`${t.mediaDate}|${t.eventDate}`)).map(t=>t.reduce((n,r)=>(n.eventDate||(n.eventDate=r.eventDate),n.mediaDate||(n.mediaDate=r.mediaDate),n.conversions+=r.conversions,n.cost+=r.cost||0,n),{eventDate:"",mediaDate:"",conversions:0,cost:0})),eCe=e=>qh(Ws(e,({mediaDate:t})=>t)).map(([t,n])=>{const r={id:t,months:{},totals:{conversions:0,cost:0,costPerConversion:0}};let s=0,i=0;const o=n.reduce((l,{eventDate:c,conversions:d,cost:u})=>(s+=d,i+=u||0,l.months[c]={conversions:d,cost:u||0,costPerConversion:i/s},l),r);return o.totals={conversions:s,cost:i,costPerConversion:i/s},o}),tCe=e=>Kb(Ws(e,({eventDate:t})=>t)),nCe=e=>{let t=0,n=0;const r={id:"Total",months:{},totals:{cost:0,conversions:0,costPerConversion:0}},s=qh(Ws(e,({eventDate:i})=>i)).reduce((i,[o,l])=>{const c=l.reduce((d,{conversions:u,cost:p})=>(d.conversions+=u,d.cost+=p||0,d),{conversions:0,cost:0});return t+=c.conversions,n+=c.cost,i.months[o]={conversions:c.conversions,cost:c.cost,costPerConversion:n/t},i},r);return s.totals={conversions:t,cost:n,costPerConversion:n/t},s},ib=(e,t)=>{const n=t==="costPerConversion"?2:0,r=t!=="conversions";return[{field:"id",headerName:"Month",width:124,valueFormatter:s=>Date.parse(s.value)?BT(s.value):s.value},{field:"totalCost",headerName:"Spend",width:162,valueGetter:({row:s})=>s.totals.cost,renderCell:s=>a.jsx(ft,{fractionDigits:0,isCurrency:!0,value:s.value})},...e.map(s=>({field:s,headerName:BT(s),flex:1,minWidth:150,valueGetter:({row:i})=>i.months[s]?.[t],renderCell:i=>a.jsx(ft,{fractionDigits:n,isCurrency:r,value:i.value})})),{field:"totals",headerName:"Total",width:150,cellClassName:Dw.totalsCell,valueGetter:({row:s})=>s.totals[t],renderCell:s=>a.jsx(ft,{fractionDigits:n,isCurrency:r,value:s.value})}]},rCe=e=>[{groupId:"media-exposure",headerName:"Media exposure",children:[{field:"id"},{field:"totalCost"}]},{groupId:"month",headerName:"Conversion month",children:e.map(t=>({field:t}))}],sCe=e=>{const t=Zve(e),n=eCe(t),r=nCe(t),s=n.concat(r),i=tCe(t),o=rCe(i),l=ib(i,"conversions"),c=ib(i,"cost"),d=ib(i,"costPerConversion");return{columnGroupingModel:o,conversionsColumns:l,costColumns:c,costPerConversionColumns:d,rows:s}},iCe=()=>{const{insightsConversionLookback:e}=Gu(),{columnGroupingModel:t,costColumns:n,costPerConversionColumns:r,conversionsColumns:s,rows:i}=m.useMemo(()=>sCe(e),[e]);return a.jsxs(xn,{direction:"column",gap:5,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(sb,{columnGroupingModel:t,columns:s,csvFileName:"ConversionLookback-Conversion",rows:i,subtitle:Yve,title:"Media-Driven Conversions"}),a.jsx(sb,{columnGroupingModel:t,columns:n,csvFileName:"ConversionLookback-Spend",rows:i,subtitle:Gve,title:"Conversion Spend"}),a.jsx(sb,{columnGroupingModel:t,columns:r,csvFileName:"ConversionLookback-SpendPerConversion",rows:i,title:a.jsxs(xn,{direction:"row",alignItems:"center",gap:"8px",children:["Spend Per Conversion",a.jsx(sve,{title:Kve})]})})]})},aCe=()=>{const[e,t]=m.useState("0"),n=(r,s)=>{t(s)};return a.jsxs(co,{value:e,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default"},children:a.jsxs(uo,{onChange:n,"aria-label":"conversion-lookback-tabs",children:[a.jsx(_n,{label:"Tables",value:"
2450"}),a.jsx(_n,{label:"Graphs",value:"1"})]})}),a.jsx(xt,{value:"0",sx:{padding:0},children:a.jsx(iCe,{})}),a.jsx(xt,{value:"1",children:a.jsx(qve,{})})]})},oCe=()=>{const{dataLoading:e,dispatch:t,metaData:n,metaDataLoading:r,track:s}=Gu(),i=m.useCallback(()=>{const{nextDateRange:o,nextKpi:l}=wi({metaData:n,selectedKpi:"",selectedDateRange:[null,null]});t({type:"reset",value:{selectedDateRange:o,selectedKpi:l}}),s("reset")},[t,n,s]);return a.jsxs(xn,{direction:"column",gap:5,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(ho,{loading:r||e}),a.jsxs(xn,{gap:2.5,children:[a.jsx(Xt,{title:"Conversion Lookback"}),a.jsxs(xn,{direction:"row",alignItems:"center",justifyContent:"space-between",children:[a.jsx(I,{variant:"subtitle2",fontWeight:"400",children:Vve}),a.jsx(qu,{disabled:e,isLoading:r,onClick:i})]}),a.jsx(Uve,{})]}),a.jsx(aCe,{})]})},gF="GL_TYPE_NAME",lCe={selectedDateRange:[null,null],selectedKpi:"",selectedMediaAttribute:gF,conversionType:"attribution_report",dateType:"event",selectedColumns:[]},cCe=(e,t)=>t.type==="filtersBar"?{...e,...t.value}:t.type==="reset"?{...e,selectedMediaAttribute:gF,...t.value}:t.type in e?{...e,[t.type]:t.value}:e,dCe=({selectedDateRange:e,selectedKpi:t,selectedMediaAttribute:n,dateType:r})=>{const[s,i]=e,{engagementNiceId:o}=pe(),{kpiScalar:l,isLoadingConfig:c}=Zm(t),{data:d=[],isFetching:u,isUninitialized:p}=VA({engagementNiceId:o}),{activeKpiNiceIds:h,kpisLoading:f}=Ol(),g=m.useMemo(()=>!d.length||!h.size?[]:d.filter(S=>h.has(S.kpiNiceId)),[d,h]),x=m.useMemo(()=>({engagement_nice_id:o,kpi_nice_id:t,start_date:s?.format("YYYY-MM-DD")??"",end_date:i?.format("YYYY-MM-DD")??"",date_type:r,kpi_scalar:l??null}),[r,i,o,l,t,s]),b=f||c||u||p||!t||!s||!i,{data:y=[],isFetching:v,isUninitialized:C}=l3({body:x},{skip:b});return{insightsConversionLookback:y,insightsConversionLookbackLoading:v,dataLoading:v||C,metaData:g,metaDataLoading:f||u}},uCe=()=>{const e=Hu("lookback"),[t,n]=m.useReducer(cCe,lCe),{selectedDateRange:r,selectedKpi:s,selectedMediaAttribute:i,dateType:o}=t,{insightsConversionLookback:l,insightsConversionLookbackLoading:c,dataLoading:d,metaData:u,metaDataLoading:p}=dCe({selectedDateRange:r,selectedKpi:s,selectedMediaAttribute:i,dateType:o}),h=ww(),f=m.useMemo(()=>({insightsConversionLookback:l,insightsConversionLookbackLoading:c,dataLoading:d,dispatch:n,mediaClassifications:h,metaData:u,metaDataLoading:p,state:t,track:e}),[l,c,d,h,u,p,t,e]);return a.jsx(mF.Provider,{value:f,children:a.jsx(oCe,{})})},xF=m.createContext(null),ba=()=>m.useContext(xF),pCe=()=>{const{coordinatesLoading:e,handleConversionTypeChange:t,mediaDataLoading:n,metaDataLoading:r,state:{conversionType:s}}=ba(),i=e||n||r;return a.jsx(Mm,{disabled:i,isLoading:r,onChange:t,value:s})},hCe=()=>{const{availableDateRange:e,dispatch:t,getMediaData:n,kpiOptions:r,mediaDataLoading:s,metaData:i,metaDataLoading:o,state:l,targetOptions:c,track:d}=ba(),{selectedDateRange:u,selectedKpi:p,selectedTarget:h}=l,[f,g]=e,x=m.useCallback(v=>{const{nextDateRange:C,nextKpi:w,nextTarget:S}=Ys({metaData:i,selectedDateRange:u,selectedKpi:p,selectedTarget:v});t({type:"filtersBar",value:{selectedDateRange:C,selectedKpi:w,selectedTarget:S}}),d("targetAudience"),n({nextDateRange:C,nextKpi:w,nextTarget:S})},[t,n,i,u,p,d]),b=m.useCallback(v=>{const{nextDateRange:C,nextKpi:w,nextTarget:S}=Ys({metaData:i,selectedDateRange:u,selectedKpi:v,selectedTarget:h});t({type:"filtersBar",value:{selectedDateRange:C,selectedKpi:w,selectedTarget:S}}),d("kpi"),n({nextDateRange:C,nextKpi:w,nextTarget:S})},[t,n,i,h,u,d]),y=m.useCallback(v=>{t({type:"selectedDateRange",value:v}),d("dateRange"),n({nextDateRange:v})},[t,n,d]);return a.jsx(da,{dataFirstDate:f??void 0,dataLastDate:g??void 0,handleDatePickerOnChange:y,handleKpiOnChange:b,handleTargetAudienceOnChange:x,isDataLoading:s,isMetaLoading:o,kpiListOptions:r,selectedDateRange:u,selectedKpi:p,selectedTargetAudience:h,targetAudienceListOptions:c})},fCe=rt(sn)({".MuiFormControlLabel-label":{fontSize:14,fontWeight:500,paddingTop:"2px"}}),bF=()=>{const{dispatch:e,mediaDataLoading:t,metaDataLoading:n,state:{includeBase:r},track:s}=ba();return a.jsx(Nt,{isLoading:n,children:a.jsx(fCe,{disabled:t,control:a.jsx(et,{checked:r,disableRipple:!0,sx:{p:1},onChange:i=>{e({type:"includeBase",value:i.target.checked}),s("includeBase",{includeBase:i.target.checked})}}),label:"Include Base"})})},mCe=()=>{const{coordinatesLoading:e,mediaDataLoading:t,metaDataLoading:n}=ba();return a.jsx(ho,{loading:e||t||n})},gCe=()=>{const{coordinatesLoading:e,dispatch:t,mediaDataLoading:n,metaDataLoading:r,state:{valueToShow:s},track:i}=ba(),o=({target:{value:l}})=>{if(l in Fr){const c=l;t({type:"valueToShow",value:c}),i("totalsType",{totalsType:c})}};return a.jsx(Ar,{sx:{width:"240px",maxWidth:"300px"},disabled:n||e,isLoading:r,onChange:o,options:Fr,value:s||Object.keys(Fr)[0]})},xCe=()=>{const{coordinatesLoading:e,dispatch:t,getMediaData:n,mediaDataLoading:r,metaData:s,metaDataLoading:i,track:o}=ba(),l=e||r,c=()=>{const{nextDateRange:d,nextKpi:u,nextTarget:p}=Ys({metaData:s,selectedDateRange:[null,null],selectedKpi:"",selectedTarget:""});t({type:"resetFilters",value:{conversionType:Wu,includeBase:!1,selectedDateRange:d,selectedKpi:u,selectedTarget:p,valueToShow:xg}}),o("reset"),n({nextDateRange:d,nextKpi:u,nextTarget:p})};return a.jsx(qu,{disabled:l,isLoading:i,onClick:c})},bCe={conversionType:Wu,includeBase:Gye,mediaAttribute:"GL_TYPE_NAME",selectedDateRange:[null,null],selectedKpi:"",selectedTarget:"",valueToShow:xg},yCe=(e,t)=>t.type in e?{...e,[t.type]:t.value}:t.type==="filtersBar"||t.type==="resetFilters"?{...e,...t.value}:e,vCe=({children:e})=>{const t=Hu("geography"),{engagementNiceId:n}=pe(),[r,s]=m.useReducer(yCe,bCe),{conversionType:i,mediaAttribute:o,selectedDateRange:l,selectedKpi:c,selectedTarget:d}=r,{data:u=null,isFetching:p}=c3(n),h=cP(c),f=m.useCallback(({type:D,value:M})=>{switch(D){case"conversionType":s({type:"conversionType",value:M}),t("conversionType",{conversionType:M});break;case"filtersBar":s({type:"filtersBar",value:{selectedDateRange:M.nextDateRange,selectedKpi:M.nextKpi,selectedTarget:M.nextTarget}});break}},[t]),{availableDateRange:g,getMediaData:x,getMetaData:b,handleConversionTypeChange:y,kpiOptions:v,mediaClassifications:C,mediaData:w,mediaDataLoading:S,metaData:E,metaDataLoading:k,targetOptions:j}=Sw({conversionType:i,mediaAttribute:o,onFilterChange:f,requiredColumns:["GL_TYPE_NAME","KPI_MARKET"],selectedDateRange:l,selectedKpi:c,selectedTarget:d}),_=m.useMemo(()=>({availableDateRange:g,coordinates:u,coordinatesLoading:p,dispatch:s,getMediaData:x,getMetaData:b,handleConversionTypeChange:y,kpiOptions:v,mediaClassifications:C,mediaData:w,metaData:E,mediaDataLoading:S,metaDataLoading:k,state:r,targetOptions:j,track:t,valuePerConversion:h}),[g,u,p,s,x,b,y,v,C,w,S,E,k,r,j,t,h]);return a.jsx(xF.Provider,{value:_,children:e})},yF=({includeBase:e,mediaData:t,valueToShow:n})=>t.filter(r=>r.KPI_MARKET!==""&&r[n]!==0&&r.conversions!==0&&(e||r.GL_TYPE_NAME!=="Base")),UT=({filteredMediaData:e,mediaAttribute:t})=>Array.from(new Set(e.map(n=>t?n[t]:null).filter(n=>typeof n=="string"&&!!n&&n!=="base"))),CCe=({filteredMediaData:e,mediaAttribute:t,valueToShow:n})=>{const r=Array.from(e).reduce((s,i)=>{if(!t)return s;const o=i[t];return o&&(s[o]||(s[o]={conversions:0,impressions:0,investment:0,roas:0}),s[o].conversions+=i.conversions,s[o].impressions+=i.impressions,s[o].investment+=i.investment),s},{});return Object.entries(r).reduce((s,[i,o])=>{let l;switch(n){case"conversions":l=o.conversions;break;case"impressions":l=o.conversions?o.impressions/o.conversions:0;break;case"investment":l=o.conversions?o.investment/o.conversions:0;break;default:l=0;break}return s[i]=l,s},{})},im=20,Aw=32,Yu=472,wCe=im+Aw+Yu,SCe=e=>t=>{const n={notation:"compact"};return new Intl.NumberFormat("en",n).format(t)},jCe=e=>{const t=e.reduce((r,s)=>r+s.value,0),n=e.map(r=>{if(!r.value)return"";const s=I2.format(r.value/t);return` 246 <div class="${Zr.tooltipItem}"> 247 ${r.marker} <span style="font-size: 12px">${r.seriesName}: <b>${tge.format(r.value)}</b> (${s})</span> 248 </div> 249 `});return` 250 <div class="${Zr.tooltipContainer}"">${e[0]?e[0].name:""}</div> 251 <div class="${Zr.tooltipItemContainer}">${n.join("")}</div> 252 `},kCe=e=>e.map(t=>({...t,type:"bar",stack:"total",label:{show:!1},barMaxWidth:"60%",emphasis:{focus:"none"}})),ECe=({categories:e,isCurrency:t,legendHeight:n,stacks:r,theme:s})=>{const{palette:i,typography:o}=s,{chartSet:l}=i,{secondary:c}=i.text,{fontFamily:d=""}=o;return{animation:!0,tooltip:{trigger:"axis",axisPointer:{type:"none"},padding:0,backgroundColor:i.background.paper,borderColor:i.border.default,borderWidth:1,textStyle:{color:i.text.primary,fontFamily:d},formatter:jCe},legend:{textStyle:{color:c,fontFamily:d,padding:-6},icon:"circle",selectedMode:!1,padding:8},grid:{top:n+32,right:32,bottom:0,left:240},xAxis:{position:"top",axisLabel:{formatter:SCe()},splitLine:{show:!1}},yAxis:{type:"category",data:e,axisLabel:{color:c,fontFamily:d||"",fontSize:11}
252,axisLine:{show:!1},axisTick:{show:!1}},series:kCe(r),color:l}},_Ce=({categories:e,chartRef:t,stacks:n})=>{const r=Re(),s=pF({categories:e,chartRef:t,stacks:n}),i=m.useMemo(()=>ECe({categories:e,isCurrency:!1,legendHeight:s,stacks:n,theme:r}),[e,s,n,r]),o=!e.length||!n.length,l=Math.max(Yu,e.length*36);return a.jsx(gs,{isDataEmpty:o,children:a.jsx(bg,{children:a.jsx(Fl,{notMerge:!0,option:i,ref:t,style:{height:l}})})})},TCe=["86%","67%","46%","38%","23%","18%","8%","6%"],vF=32,CF=24,ICe=Yu-vF-CF,DCe=()=>a.jsxs(T,{height:wCe,width:"100%",children:[a.jsx(fe,{variant:"rounded",animation:"wave",height:im,width:"30%",sx:{mb:Aw/8}}),a.jsxs($,{height:Yu,justifyContent:"start",children:[a.jsx($,{justifyContent:"center",direction:"row",children:a.jsx(fe,{variant:"rounded",animation:"wave",height:vF,width:"50%",sx:{mb:CF/8}})}),a.jsx($,{alignItems:"flex-start",direction:"column",height:ICe,pl:16,rowGap:1.5,children:TCe.map((e,t)=>a.jsx(fe,{variant:"rounded",animation:"wave",width:e,sx:{flex:1}},`skeleton-item-${t}`))})]})]}),ACe=(e,t)=>{const n=Object.keys(e).reduce((r,s)=>{const i=e[s]||{};return Object.keys(i).reduce((o,l)=>{const c=i[l];return c&&(o[l]=(o[l]||0)+c[t]),o},r),r},{});return Object.entries(n).sort((r,s)=>s[1]-r[1]).map(r=>r[0])},MCe=({mediaAttribute:e,mediaData:t,valueToShow:n})=>{const r=t.reduce((d,u)=>{if(e&&e in u){const p=u[e];p&&(d[p]=(d[p]||0)+u.conversions)}return d},{}),s=new Set(Object.entries(r).sort((d,u)=>u[1]-d[1]).map(d=>d[0]).slice(0,20)),i=t.reduce((d,u)=>{if(e&&e in u){let p=u[e];if(n in u&&p&&u.KPI_MARKET!==void 0){s.has(p)||(p="Other");const h=d[p]||{},f=h[u.KPI_MARKET]||{conversions:0,impressions:0,investment:0,roas:0};f.conversions+=u.conversions,f.impressions+=u.impressions,f.investment+=u.investment,h[u.KPI_MARKET]=f,d[p]=h}}return d},{});
252Object.keys(i).forEach(d=>{const u=i[d]||{};Object.keys(u).forEach(p=>{const h=u[p];h&&(h.conversions=Math.ceil(h.conversions))})});const o=ACe(i,n).reverse(),c=(i.Other?[...s,"Other"]:[...s]).map(d=>({data:o.map(p=>i[d]?.[p]?.[n]||0),name:d}));return{categories:o,stacks:c}},RCe=({categories:e,stacks:t})=>{const o=["Categories"].concat(t.map(({name:u})=>`"${u}"`)).join(","),c=e.map((u,p)=>{const h=t.map(({data:f})=>{const g=f[p];return g?String(g):"0"});return h.unshift(`"${u}"`),h}).map(u=>u.join(",")).reverse().join(` 253`),d=`${o} 254${c}`;return`data:text/csv; charset=utf-8,${encodeURIComponent(`\uFEFF${d}`)}`},NCe=({loading:e,mediaAttribute:t,mediaAttributeName:n,mediaData:r,track:s})=>{const i=m.useRef(null),{categories:o,stacks:l}=m.useMemo(()=>MCe({mediaAttribute:t,mediaData:r,valueToShow:"conversions"}),[t,r]),c=`${Fr.conversions} By `,d=`${n} By KPI Market`,u=`${Fr.conversions}-By-${n}-By-KPI-Market-${new Date().toLocaleDateString()}`,p=m.useCallback(f=>f==="csv"?{dataUrl:RCe({categories:o,stacks:l}),fileName:u}:f==="png"&&i.current?{dataUrl:i.current.getEchartsInstance().getDataURL({backgroundColor:"white"}),fileName:u}:{dataUrl:"",error:!0,fileName:""},[o,u,l]),h=m.useCallback(({fileName:f,fileType:g})=>{s("download",{chartName:f,fileType:g})},[s]);return a.jsx(Ve,{children:a.jsx(Ue,{children:e?a.jsx(DCe,{}):a.jsxs(a.Fragment,{children:[a.jsxs(T,{height:im,display:"flex",justifyContent:"space-between",mb:Aw/8,children:[a.jsxs(I,{height:im,variant:"h6",children:[c,d]}),a.jsx(Rm,{getFileData:p,onDownload:h})]}),a.jsx(T,{sx:{width:"100%",height:Yu,overflow:"auto"},children:a.jsx(_Ce,{categories:o,chartRef:i,stacks:l})})]})})})},OCe=()=>{const{dispatch:e,getMediaData:t,mediaClassifications:n,mediaData:r,mediaDataLoading:s,metaDataLoading:i,state:{includeBase:o,mediaAttribute:l},track:c}=ba(),d=m.useMemo(()=>yF({includeBase:o,mediaData:r,valueToShow:"conversions"}),[o,r]),[u,p]=m.useState(UT({filteredMediaData:d,mediaAttribute:l})),h=m.useMemo(()=>CCe({filteredMediaData:d,mediaAttribute:l,valueToShow:"conversions"}),[d,l]),f=m.useMemo(()=>{const x=new Set(u);return d.map(b=>{const y=b[l];return y&&x.has(y)?b:null}).filter(b=>b!==null)},[d,l,u]),g=m.useCallback(x=>{e({type:"mediaAttribute",value:x}),c("presentBy",{pivot:x}),t({nextMediaAttribute:x})},[e,t,c]);return m.useEffect(()=>{p(UT({filteredMediaData:d,mediaAttribute:l}))},[d,l]),a.jsxs(xn,{spacing:2,children:[a.jsx(xn,{direction:"row",spacing:2,justifyContent:"end",children:a.jsxs(xn,{direction:"row",spacing:2,children:[a.jsx(bF,{}),a.jsx(gi,{sx:{display:"flex",alignItems:"center"},children:"Present By:"}),a.jsx(kw,{dataLoading:s,excludedAttributes:["KPI_MARKET"],mediaAttributes:n,metaDataLoading:i,onChange:g,selectedMediaAttribute:l}),a.jsx(cF,{data:h,dataLoading:s,limit:20,metaDataLoading:i,onChange:p,values:u})]})}),a.jsx(NCe,{loading:s||i,mediaAttribute:l,mediaAttributeName:n[l]||"",mediaData:f,track:c})]})},VT=[{threshold:.2,radius:4,opacity:.1},{threshold:.4,radius:8,opacity:.2},{threshold:.6,radius:12,opacity:.4},{threshold:.8,radius:16,opacity:.6},{threshold:.9,radius:20,opacity:.8},{threshold:1,radius:24,opacity:1}],PCe=({coordinates:e,isDataLoading:t,mediaData:n,valueToShow:r,valuePerConversion:s})=>{const{engagementCurrency:i}=pe(),o=Re(),{chartBrand:l}=o.palette,c=m.useMemo(()=>{if(t||!e)return[];const b=n.reduce((y,v)=>{const{KPI_MARKET:C,conversions:w,impressions:S,investment:E,roas:k}=v;if(C){const j=y[C],_=e?.[C];if(j)y[C]={...y[C],conversions:(j.conversions||0)+w,impressions:(j.impressions||0)+S,investment:(j.investment||0)+E,roas:(j.roas||0)+(j.roas||0)};else if(_?.[0]&&_?.[1]){const[D,M]=_;y[C]={name:C,coordinates:[M,D],conversions:w,impressions:S,investment:E,roas:k||0}}}return y},{});return Object.values(b)},[t,n,e]),d=m.useMemo(()=>c.reduce((b,y)=>{const{conversions:v,impressions:C,investment:w}=y;if(v!==0){const S=ege({conversions:v,impressions:C,investment:w,valuePerConversion:s,valueToShow:r});b.push({...y,metric:S})}return b},[]),[c,s,r]),u=m.useMemo(()=>{let b=1/0,y=-1/0,v=1/0,C=-1/0;if(!d||d.length===0)return{minLat:24.396308,maxLat:49.384358,minLong:-125,maxLong:-66.93457,centerLat:36.890246,distanceLat:24.98805,bufferLat:1.2494025,centerLong:-95.467174,distanceLong:58.06543,bufferLong:8.7098145};d.forEach(D=>{const[M,N]=D.coordinates;b=Math.min(b,M),y=Math.max(y,M),v=Math.min(v,N),C=Math.max(C,N)});const w=(b+y)/2,S=y-b,E=d.length===1?0:S*.05,k=(v+C)/2,j=C-v,_=d.length===1?0:j*.15;return{minLat:b,maxLat:y,minLong:v,maxLong:C,centerLat:w,distanceLat:S,bufferLat:E,
254centerLong:k,distanceLong:j,bufferLong:_}},[d]),p=m.useMemo(()=>d.reduce((b,y)=>(y?.metric&&b<y?.metric&&(b=y.metric),b),-1),[d]),h=m.useCallback(b=>{const y=VT.find(v=>b/p<v.threshold);return y?y.radius:24},[p]),f=m.useCallback(b=>{const y=VT.find(v=>b/p<v.threshold);return y?y.opacity:.9},[p]),g=[[u.minLat-u.bufferLat,u.minLong-u.bufferLong],[u.maxLat+u.bufferLat,u.maxLong+u.bufferLong]];function x({mapLimits:b}){return OH().fitBounds(b),null}return a.jsx(Ve,{children:a.jsxs(Ue,{children:[a.jsxs(I,{variant:"h6",children:[r&&Fr[r]," Map"]}),a.jsx(T,{sx:{width:"100%",height:"600px",mt:4,borderRadius:4,"& .leaflet-top":{zIndex:"400"}},children:a.jsxs(AH,{style:{height:"100%",width:"100%",borderRadius:"8px",overflow:"hidden"},bounds:g,zoomControl:!0,scrollWheelZoom:!1,attributionControl:!1,center:[u.centerLat,u.centerLong],children:[a.jsx(MH,{url:o.palette.mode==="dark"?"https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png":"https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"}),a.jsx(x,{mapLimits:g}),d.length>0&&d.map(b=>a.jsx(RH,{pathOptions:{fillOpacity:.5,stroke:!1,color:l.main.bold,opacity:f(b.metric)},radius:h(b.metric),center:[b.coordinates[0],b.coordinates[1]],children:a.jsx(NH,{children:a.jsxs(T,{children:[a.jsxs($,{flexDirection:"row",gap:.5,children:[a.jsx(I,{variant:"subtitle2",children:"Market:"}),a.jsx(I,{variant:"body1",children:b.name})]}),a.jsx($,{flexDirection:"row",gap:.5,children:r&&a.jsxs(a.Fragment,{children:[a.jsx(I,{variant:"subtitle2",children:`${Fr[r]}:`}),a.jsx(I,{variant:"body1",children:nge({value:b.metric,valueToShow:r,currency:i})})]})})]})})},b.name))]})})]})})},LCe=Ne.memo(PCe),FCe=()=>{const{coordinates:e,coordinatesLoading:t,mediaData:n,mediaDataLoading:r,metaDataLoading:s,state:{includeBase:i,valueToShow:o},valuePerConversion:l}=ba(),c=m.useMemo(()=>yF({mediaData:n,includeBase:i&&o==="conversions",valueToShow:o}
254),[i,n,o]);return a.jsxs($,{rowGap:2,children:[a.jsxs($,{alignItems:"center",direction:"row",justifyContent:"flex-end",children:[a.jsx(bF,{}),a.jsx(I,{sx:{px:2},children:"Show: "}),a.jsx(gCe,{})]}),a.jsx($,{paddingBottom:4,children:a.jsx(LCe,{coordinates:e,mediaData:c,isDataLoading:t||r||s,valueToShow:o,valuePerConversion:l})})]})},$Ce=()=>{const[e,t]=m.useState("0"),n=(r,s)=>{t(s)};return a.jsxs(co,{value:e,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default"},children:a.jsxs(uo,{onChange:n,"aria-label":"conversion-lookback-tabs",children:[a.jsx(_n,{label:"Maps",value:"0"}),a.jsx(_n,{label:"Graphs",value:"1"})]})}),a.jsx(xt,{sx:{p:0},value:"0",children:a.jsx(FCe,{})}),a.jsx(xt,{sx:{p:0},value:"1",children:a.jsx(OCe,{})})]})},zCe=()=>a.jsx(vCe,{children:a.jsxs($,{direction:"column",gap:5,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(mCe,{}),a.jsxs($,{gap:2.5,children:[a.jsx(Xt,{title:"Geography"}),a.jsxs($,{direction:{xs:"column",lg:"row"},justifyContent:"space-between",gap:2,children:[a.jsx(pCe,{}),a.jsx($,{direction:{xs:"column",lg:"row"},gap:2,children:a.jsx(xCe,{})})]}),a.jsx(hCe,{})]}),a.jsx($Ce,{})]})}),wF=m.createContext(null),So=()=>m.useContext(wF),BCe=()=>{const{dataLoading:e,dispatch:t,metaData:n,metaDataLoading:r,state:s,track:i}=So(),{selectedDateRange:o,selectedKpi:l}=s,c=m.useMemo(()=>yg(n),[n]),[d,u]=m.useMemo(()=>Iw({metaData:n,selectedKpi:l}),[n,l]),p=m.useCallback(f=>{const{nextDateRange:g,nextKpi:x}=wi({metaData:n,selectedKpi:f,selectedDateRange:o});t({type:"filtersBar",value:{selectedDateRange:g,selectedKpi:x}}),i("kpi")},[t,n,o,i]),h=m.useCallback(f=>{t({type:"selectedDateRange",value:f}),i("dateRange")},[t,i]);return m.useEffect(()=>{const[f,g]=o;if(n.length&&(!l||!f||!g)){const{nextDateRange:x,nextKpi:b}=wi({metaData:n,selectedDateRange:o,selectedKpi:l});t({type:"filtersBar",value:{selectedDateRange:x,selectedKpi:b}})}},[t,n,o,l]),a.jsx(da,{dataFirstDate:d??void 0,dataLastDate:u??void 0,handleDatePickerOnChange:h,handleKpiOnChange:p,hideTargetAudience:!0,isDataLoading:e,isMetaLoading:r,kpiListOptions:c,selectedDateRange:o,selectedKpi:l})},UCe=()=>{const{dataLoading:e,dispatch:t,mediaClassifications:n,metaData:r,metaDataLoading:s,state:i,track:o}=So(),{selectedMediaAttribute:l}=i,c=m.useCallback(u=>{t({type:"selectedMediaAttribute",value:u}),o("presentBy",{pivot:u})},[t,o]),d=m.useCallback(()=>{const{nextDateRange:u,nextKpi:p}=wi({metaData:r,selectedKpi:"",selectedDateRange:[null,null]});t({type:"reset",value:{selectedDateRange:u,selectedKpi:p}}),o("reset")},[t,r,o]);return a.jsxs($,{gap:2.5,children:[a.jsx(Xt,{title:"Journey"}),a.jsx($,{direction:"row",justifyContent:"flex-end",children:a.jsx(qu,{disabled:e,isLoading:s,onClick:d})}),a.jsx(BCe,{}),a.jsxs($,{direction:"row",justifyContent:"flex-end",spacing:2,children:[a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:"Present By:"}),a.jsx(kw,{dataLoading:e,mediaAttributes:n,metaDataLoading:s,onChange:c,selectedMediaAttribute:l})]})]})},VCe=(e,t)=>t.filter(n=>!e.includes(n)).map(n=>({x:n,y:[0,0]})),WCe=(e,t)=>e.map(n=>{const[r]=t,s=r?.touchpoints||0,i=Array.from({length:t.length+1-s},(l,c)=>String(c+s)),o=[...n.data,...VCe([...new Set(n.data.map(l=>l.x))],i)].sort((l,c)=>Number(l.x)-Number(c.x));return{...n,data:o}}),HCe=e=>e?.colors?{...e,colors:["transparent",...e.colors]}:e,qCe=e=>{const{series:t,options:n,trails:r}=e,s=m.useMemo(()=>WCe(t,r),[t,r]),i=m.useMemo(()=>HCe(n),[n]);return a.jsx(gve,{...e,series:s,options:i,width:"95%"})},GCe=()=>{const{data:e,dataSeries:t,dispatch:n,track:r}=So(),s=Re(),{chartSet:i}=s.palette,o=m.useRef(null),l=m.useCallback(d=>{n({type:"selectedJourneyIndex",value:d})},[n]),c=m.useMemo(()=>fve(l,i,s,r),[l,i,s,r]);return a.jsx("div",{ref:o,children:a.jsx(qCe,{series:t,options:c,type:"rangeBar",height:650,trails:e})})},YCe=()=>a.jsx(T,{height:"100%",flex:"1",children:a.jsx($,{sx:{width:"100%",p:3},ml:4.5,direction:"column",spacing:1.3,alignItems:"flex-start",children:Array.from({length:20},(e,t)=>a.jsx($,{direction:"row",gap:1.35,children:Array.from({length:t},(n,r)=>a.jsx(fe,{variant:"rectangular",sx:{borderRadius:.5},animation:"pulse",width:"14px",height:"18px"},`journey-skeleton-item-${r}`))},`journey-skeleton-stack-${t}`))})}),KCe=()=>{const{data:e,dataLoading:t}=So(),n=e.length===0;return a.jsxs($,{direction:"column",width:"100%",children:[a.jsx($,{direction:"row",children:a.jsx(I,{variant:"h5",flex:"1",children:"Highe
254st Converting Journeys"})}),t?a.jsx(YCe,{}):a.jsx(gs,{isDataEmpty:n,children:a.jsx(GCe,{})})]})},QCe=(e,t)=>{const n={};return e.forEach(r=>{r.journey.forEach((s,i)=>{s&&(n[s]||(n[s]=[]),n[s].push({position:i,touchpoints:r.touchpoints}))})}),Object.keys(n).map((r,s)=>{const i=n[r];return{name:r,data:i.map(o=>({x:`${o.touchpoints}`,y:[o.position+.6,o.position+1.2]})),color:t[s]}})},JCe=(e,t,n)=>t.find(s=>s.name===e)?.color||n,WT=(e,t,n,r)=>{const s={};let i=0,o=e||[];if(t){const l=e.find(c=>c.touchpoints===t);l&&(o=[{...l}])}return o.forEach(l=>{l.journey.forEach(c=>{s[c]=(s[c]||0)+1,i+=1})}),Object.entries(s).map(([l,c])=>{const d=Math.round(c/i*100);return{name:l,data:[{x:l,y:d,fillColor:JCe(l,n,r)}],percentage:d}}).filter(l=>l.percentage>0).map(({name:l,data:c})=>({name:l,data:c}))},XCe=-26,ZCe=()=>{const e=Re(),{data:t,dataSeries:n,state:r,track:s}=So(),{selectedJourneyIndex:i}=r,o=e.palette.grey[600],l=m.useMemo(()=>WT(t,null,n,o),[t,n,o]),c=m.useMemo(()=>i?WT(t,i,n,o):l,[l,t,i,n,o]),d=m.useMemo(()=>mve(e,XCe,s),[e,s]);return a.jsx(dF,{options:d,series:c,type:"treemap",height:600,width:"95%"})},e0e=()=>a.jsxs($,{height:"100%",flex:"1",gap:.5,mt:2.5,children:[a.jsx(fe,{variant:"rectangular",animation:"wave",height:300}),a.jsxs($,{sx:{width:"100%",height:"100%"},direction:"row",gap:.5,flex:"1",children:[a.jsx(fe,{variant:"rectangular",animation:"pulse",height:"200px",sx:{flex:1}}),a.jsx(fe,{variant:"rectangular",animation:"pulse",height:"200px",sx:{flex:1}}),a.jsx(fe,{variant:"rectangular",animation:"pulse",height:"200px",sx:{flex:1}})]})]}),t0e=()=>{const{data:e,dataLoading:t,dispatch:n,state:r}=So(),{selectedJourneyIndex:s}=r,i=e.length===0,o=m.useCallback(()=>{n({type:"selectedJourneyIndex",value:null})},[n]);return a.jsxs($,{direction:"column",width:"100%",children:[a.jsxs($,{direction:"column",mb:-2,children:[a.jsx(I,{variant:"h5",children:"Media Type Touchpoint Percentages"}),a.jsxs($,{width:"100%",direction:"row",alignItems:"center",justifyContent:"space-between",children:[a.jsx(I,{variant:"body2",children:s?`(Journey ${Number(s)})`:"(Total Journeys)"}),a.jsx(re,{disabled:!s,variant:"text",onClick:o,sx:{mr:7},children:"Reset"})]})]}),t?a.jsx(e0e,{}):a.jsx(gs,{isDataEmpty:i,children:a.jsx(ZCe,{})})]})},n0e=()=>{const{dataLoading:e,metaDataLoading:t}=So();return a.jsxs($,{direction:"column",gap:5,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(ho,{loading:t||e}),a.jsx(UCe,{}),a.jsx(Ve,{variant:"outlined",sx:{flex:1},children:a.jsx(Ue,{children:a.jsxs($,{direction:{lg:"column",xl:"row"},children:[a.jsx(KCe,{}),a.jsx(t0e,{})]})})})]})},SF="GL_TYPE_NAME",r0e={selectedDateRange:[null,null],selectedJourneyIndex:null,selectedKpi:"",selectedMediaAttribute:SF},s0e=(e,t)=>t.type==="filtersBar"?{...e,...t.value}:t.type==="reset"?{...e,selectedMediaAttribute:SF,...t.value}:t.type in e?{...e,[t.type]:t.value}:e,i0e=({length:e=20,selectedDateRange:t,selectedKpi:n,selectedMediaAttribute:r,where:s})=>{const[i,o]=t,{engagementNiceId:l}=pe(),{kpiScalar:c}=Zm(n),{data:d=[],isFetching:u,isUninitialized:p}=VA({engagementNiceId:l}),{activeKpiNiceIds:h,kpisLoading:f}=Ol(),g=m.useMemo(()=>!d.length||!h.size?[]:d.filter(S=>h.has(S.kpiNiceId)),[d,h]),x=m.useMemo(()=>{const S={column:r,end_date:o?.format("YYYY-MM-DD")??"",engagement_nice_id:l,kpi_nice_id:n,length:e,start_date:i?.format("YYYY-MM-DD")??"",kpi_scalar:c??null};return s&&(S.where=s),S},[o,l,c,e,n,r,i,s]),b=u||f||p||!n||!i||!o,{data:y=[],isFetching:v,isUninitialized:C}=d3({body:x},{skip:b});return{data:y,dataLoading:v||C,metaData:g,metaDataLoading:f||u}},a0e=()=>{const e=Hu("journey"),[t,n]=m.useReducer(s0e,r0e),{selectedDateRange:r,selectedKpi:s,selectedMediaAttribute:i}=t,{data:o,dataLoading:l,metaData:c,metaDataLoading:d}=i0e({selectedDateRange:r,selectedKpi:s,selectedMediaAttribute:i}),u=ww(),{chartSet:p}=Re().palette,h=m.useMemo(()=>QCe(o,p),[p,o]),f=m.useMemo(()=>({data:o,dataLoading:l,dataSeries:h,dispatch:n,mediaClassifications:u,metaData:c,metaDataLoading:d,state:t,track:e}),[o,l,h,u,c,d,t,e]);return a.jsx(wF.Provider,{value:f,children:a.jsx(n0e,{})})},jF=m.createContext(null),vg=()=>m.useContext(jF),o0e=()=>{const{dispatch:e,state:{selectedDateRange:t,selectedKpi:n},metaData:r,track:s}=vg(),i=r.map(p=>({kpiName:p.kpiName,kpiNiceId:p.kpiNiceId,maxEventDate:p.maxDate,maxMediaDate:p.maxDate,minEventDate:p.minDate,minMediaDate:p.minDate})),o=m.useMemo(()=>yg(i),[i]),[l,c]=m.useMemo(()=>Iw({metaData:i,selectedKpi:n}),[i,n]),d=m.useCallback(p=>{const{nextDateRange:h,nextKpi:f}=wi({metaData:i,selectedKpi:p,selectedDateRange:t});e({type:"filtersBar",value:{selectedDateRange:h,selectedKpi:f}}),s("kpi")},[e,i,t,s]),u=m.useCallback(p=>{const[h,f]=p,[,g]=t;h&&f||!h&&!f?(e({type:"selectedDateRange",value:p}),s("dateRange")):h&&!f&&g&&h.isAfter(g)?(e({type:"selectedDateRange",value:[h,h]}),s("dateRange")):e({type:"selectedDateRange",value:t})},[e,t,s]);return m.useEffect(()=>{if(i.length&&!n){const{nextDateRange:p,nextKpi:h}=wi({metaData:i,selectedDateRange:t,selectedKpi:n});e({type:"filtersBar",value:{selectedDateRange:p,selectedKpi:h}})}},[e,i,t,n]),a.jsx(da,{dataFirstDate:l??void 0,dataLastDate:c??void 0,handleDatePickerOnChange:u,handleKpiOnChange:d,isDataLoading:!1,isMetaLoading:!1,kpiListOptions:o,selectedDateRange:t,selectedKpi:n,hideTargetAudience:!0})},l0e=()=>{const{dispatch:e,metaData:t,metaDataLoading:n,track:r}=vg(),s=!1,i=()=>{const o=t.map(d=>({kpiName:d.kpiName,kpiNiceId:d.kpiName,maxEventDate:d.maxDate,maxMediaDate:d.maxDate,minEventDate:d.minDate,minMediaDate:d.minDate})),{nextDateRange:l,nextKpi:c}=wi({metaData:o,selectedDateRange:[null,null],selectedKpi:""});e({type:"resetFilters",value:{selectedDateRange:l,selectedKpi:c}}),r("reset")};return a.jsx(qu,{disabled:s,isLoading:n,onClick:i})},c0e=()=>{const[e,t]=m.useState(!0);return m.useEffect(()=>{let n=!0;const r=()=>{n&&t(!document.hidden)};return document.addEventListener("visibilitychange",r),()=>{n=!1,document.removeEventListener("visibilitychange",r)}},[]),e},d0e={value:1,unit:"minute"},kF=(e,{skip:t=!1,throttleInterval:n=d0e}={})=>{const[r,s]=m.useState(Z()),i=c0e();m.useEffect(()=>{const o=Z();
254!t&&i&&r.add(n.value,n.unit).isBefore(o)&&(s(o),e())},[i])},u0e=e=>{const[t,n]=m.useState(null),r=()=>n(null);return{downloadFile:m.useCallback(i=>{const o=e.current?.getEchartsInstance();if(!o){n("ECharts instance not found.");return}const c=o.getDom().querySelector("svg");if(!c){n("SVG not found. Ensure ECharts is using the SVG renderer.");return}const u=new XMLSerializer().serializeToString(c),p=document.createElement("canvas"),h=p.getContext("2d");if(!h){n("Canvas 2D context not available.");return}const f=new Image,g=new Blob([u],{type:"image/svg+xml;charset=utf-8"}),x=URL.createObjectURL(g);f.onload=()=>{p.width=c.clientWidth,p.height=c.clientHeight,h.fillStyle="#fff",h.fillRect(0,0,p.width,p.height),h.drawImage(f,0,0);const b=p.toDataURL("image/png"),y=document.createElement("a");y.href=b,y.download=`${i}.png`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(x)},f.onerror=()=>{n("Error loading SVG as an image.")},f.src=x},[e]),error:t,clearError:r}},p0e=e=>{const[t,n]=m.useState(null),r=()=>n(null);return{downloadFile:m.useCallback(i=>{const o=e.current?.getEchartsInstance();if(!o){n("ECharts instance not found.");return}const c=o.getDom().querySelector("svg");if(!c){n("SVG not found. Ensure ECharts is using the SVG renderer.");return}const u=new XMLSerializer().serializeToString(c),p=new Blob([u],{type:"image/svg+xml;charset=utf-8"}),h=URL.createObjectURL(p),f=document.createElement("a");f.href=h,f.download=`${i}.svg`,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(h)},[e]),error:t,clearError:r}},h0e=e=>{const[t,n]=m.useState(null),r=()=>n(null);return{downloadFile:m.useCallback(i=>{const o=e.current?.getEchartsInstance();if(!o){n("ECharts instance not found.");return}const{series:l=[],xAxis:c=[]}=o.getOption(),d=Go(l)?l:[l],u=Go(c)?c[0]:c;if(!u||!("data"in u)||!Go(u.data)){n("Echarts has not available data");return}const p=d.map(b=>b.data),h=d.map(b=>b.name)??[];let f="data:text/csv;charset=utf-8,";f+=`${["Category",...h].join(",")} 255`,u.data.forEach((b,y)=>{const v=[b,...p.map(C=>{const w=C[y];return w&&typeof w=="object"&&"value"in w?w.value:w})];f+=`${v.join(",")} 256`});const g=encodeURI(f),x=document.createElement("a");x.href=g,x.download=`${i}.csv`,document.body.appendChild(x),x.click(),document.body.removeChild(x)},[e]),error:t,clearError:r}},f0e=e=>{const t=u0e(e),n=p0e(e),r=h0e(e);return{downloadFile:(i,o)=>{switch(o){case"png":return t.downloadFile(i);case"svg":return n.downloadFile(i);case"csv":return r.downloadFile(i);default:return()=>console.log(`Downloader for ${String(o)} not implemented`)}},error:t.error??n.error??r.error,clearError:()=>{t.clearError(),n.clearError(),r.clearError()}}},EF=({chartRef:e,fileName:t,onDownload:n,disabled:r})=>{const[s,i]=m.useState(null),{downloadFile:o,clearError:l,error:c}=f0e(e),d=f=>{i(f.currentTarget)},u=()=>{i(null)};m.useEffect(()=>{c&&(console.error(c),l())},[c,l]);const p=()=>{const f=new Date,g=f.getMonth()+1,x=f.getDate(),b=f.getFullYear();return`${t}_${g}_${x}_${b}`},h=f=>{o(p(),f),n?.(f),u()};return a.jsxs(a.Fragment,{children:[a.jsx(Ie,{onClick:d,disabled:r,children:a.jsx(bl,{})}),a.jsxs(dr,{anchorEl:s,open:!!s,onClose:u,children:[a.jsx(Se,{onClick:()=>h("svg"),children:"Download SVG"}),a.jsx(Se,{onClick:()=>h("png"),children:"Download PNG"}),a.jsx(Se,{onClick:()=>h("csv"),children:"Download CSV"})]})]})},Sn={barGap:"-100%",barCategoryGap:"15%",borderRadius:[4,4,0,0],grid:{left:"3%",right:"4%",bottom:"8%",top:"10%",containLabel:!0},xAxis:{axisLabel:{rotate:45,padding:0,fontSize:12,width:100,overflow:"truncate",verticalAlign:"top",interval:0}},legend:{data:["Positive Impact","Negative Impact"],selectedMode:!1,top:0,right:24,textStyle:{fontSize:12},itemGap:24,itemWidth:12,itemHeight:12,orient:"horizontal",icon:"circle"},series:{barMinHeight:1}},m0e=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:0}).format(e),g0e=e=>{const t=e>=0?"+":"-",n=Math.abs(e),r=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1});return`${t}${r.format(n)}`},x0e=(e,t,n)=>{const r=new Date(e),s=r.getUTCDate();if(![1,15].includes(s))return"weekly";if(s===1){const i=t||n;if(i)switch(new Date(i).getUTCDate()){case 15:return"bimonthly";case 1:return"monthly";default:return"weekly"}return"monthly"}if(s===15){const i=t||n;return i?new Date(i).getUTCDate()===1?"bimonthly":"weekly":r.getUTCDay()===0?"weekly":"bimonthly"}return"weekly"},b0e=(e,t)=>{const n=new Date(e);
256return t==="weekly"||t==="bimonthly"?n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}):n.toLocaleString("en-US",{month:"short",year:"numeric",timeZone:"UTC"})},y0e=e=>{const t=Array.from(new Set(e.map(i=>i.modelDate).sort())),n=new Map(t.map((i,o)=>[i,o])),s=[...e].sort((i,o)=>{const l=n.get(i.modelDate)??-1,c=n.get(o.modelDate)??-1;return l-c}).reduce((i,o)=>{const l=n.get(o.modelDate)??-1,c=l<t.length-1?t[l+1]:void 0,d=l>0?t[l-1]:void 0,u=x0e(o.modelDate,c,d),p=b0e(o.modelDate,u);return i[p]||(i[p]=[]),i[p].push(o),i},{});return Object.entries(s).reduce((i,[o,l])=>(i[o]=[...l].sort((c,d)=>c.extfactorName==="Base"?-1:d.extfactorName==="Base"||c.extfactorName==="Unexplained"?1:d.extfactorName==="Unexplained"?-1:(c.extfactorName||"").localeCompare(d.extfactorName||"")),i),{})},v0e=(e,t)=>{const n=[],r=[],s=[];let i=0,o=0,l=null;const c=(p,h,f)=>{const g=p.find(x=>x.extfactorName==="Base");g&&(o=g.conversions||0,f&&(l=o)),p.forEach(x=>{const b=x.conversions||0;if(x.extfactorName==="Base"){n.push(`${h} Base`),r.push({value:o,originalValue:o,itemStyle:{color:t.grey[500],borderRadius:[4,4,0,0]}}),s.push(0),i=o;return}if(b===0)return;n.push(x.extfactorName||""),b<0?(r.push({value:-b,originalValue:b,itemStyle:{color:t.primary.light,borderRadius:[4,4,0,0]}}),s.push(i+b)):(r.push({value:b,originalValue:b,itemStyle:{color:t.primary.dark,borderRadius:[4,4,0,0]}}),s.push(i)),i+=b})},d=Object.keys(e);let u=!0;return d.forEach(p=>{const h=e[p];h?.length&&(c(h,p,u),u=!1)}),{xAxisLabels:n||[],mainData:r||[],assistData:s||[],firstMonthBaseValue:l}},_F=(e,t,n,r=0,s=e.length)=>{const i=e.slice(r,s),o=t.slice(r,s),l=n.slice(r,s);if(i.length===0)return 0;const c=[];i.forEach((u,p)=>{const h=l[p];if(!h||h.includes("Base"))return;const f=u.originalValue,g=o[p]??0;f!==0&&c.push(f+g)});const d=c.length>0?Math.min(...c):0;return Math.max(0,d*.95)},C0e=U.object({data:U.array(U.unknown()).optional()}),w0e=U.object({data:U.array(U.string()).optional()}),S0e=U.object({start:U.number().optional(),end:U.number().optional()}),j0e=U.object({series:U.array(C0e),xAxis:U.array(w0e),dataZoom:U.array(S0e).optional()}),k0e=U.object({value:U.number(),originalValue:U.number(),itemStyle:U.record(U.unknown()).optional()});function E0e(e){return j0e.safeParse(e)}const _0e=(e,t,{start:n,end:r}={})=>
256{if(!e)return;const s=e.getOption(),i=E0e(s);if(!i.success||!i.data)return;const{series:o,xAxis:l,dataZoom:c=[]}=i.data;if(!o[0]?.data||!l[0]?.data)return;const d=c[0],u=d?.start??n??0,p=d?.end??r??100,h=l[0].data?.length||0,f=Math.round(h*u/100),g=Math.ceil(h*p/100),x=o[1]?.data??[],b=o[0]?.data??[],y=l[0]?.data??[],v=x.map(S=>{const E={originalValue:0,value:0,itemStyle:{color:t.palette.grey[300],borderRadius:[4,4,0,0]}};if(typeof S=="number")return{...E,originalValue:S,value:S};const k=k0e.safeParse(S);return k.success?{...E,originalValue:k.data.originalValue,value:k.data.value,itemStyle:{...E.itemStyle,...k.data.itemStyle}}:E}),C=b.map(S=>typeof S=="number"?S:0),w=_F(v,C,y,f,g);e.setOption({yAxis:[{min:w}]})};function T0e(e,t){const{typography:n}=t,r=y0e(e),{xAxisLabels:s,mainData:i,assistData:o}=v0e(r,t.palette),{positiveImpactData:l,negativeImpactData:c}=i.reduce((u,p,h)=>{const f=s[h]||"",g=f.includes("Base")||f.includes("Total"),{originalValue:x}=p;return g||(x>0&&(u.positiveImpactData[h]=x),x<0&&(u.negativeImpactData[h]=x)),u},{positiveImpactData:Array(i.length).fill(0),negativeImpactData:Array(i.length).fill(0)});return{tooltip:{trigger:"axis",axisPointer:{type:"shadow"},formatter:u=>{const p=Array.isArray(u)?u[1]:u;if(!p||typeof p!="object"||!("data"in p))return"";const h=p.data;if(!h||typeof h!="object"||h instanceof Date)return"";const f=typeof p.name=="string"?p.name:"";let g=0;"originalValue"in h&&typeof h.originalValue=="number"?g=h.originalValue:"value"in h&&(g=Number(h.value)||0);const x=g0e(g),b=f.includes("Base")?"Total":"Change";return`<strong>${f}</strong><br/>${b}: ${x}`},backgroundColor:t.palette.background.paper,borderColor:t.palette.divider,textStyle:{color:t.palette.text.primary,fontSize:12,fontFamily:t.typography.fontFamily},padding:[8,12],extraCssText:"box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);"},legend:{show:!0,top:Sn.legend.top,right:Sn.legend.right,data:Sn.legend.data.map(u=>({name:u,icon:Sn.legend.icon,itemStyle:{color:u==="Positive Impact"?t.palette.chartBrand.main.bolder:u==="Negative Impact"?t.palette.chartBrand.main.light:t.palette.grey[500],borderWidth:0}}
256)),selectedMode:Sn.legend.selectedMode,orient:Sn.legend.orient,textStyle:{...Sn.legend.textStyle,color:t.palette.text.primary,fontFamily:t.typography.fontFamily,padding:[0,0,0,4],rich:{a:{color:t.palette.chartBrand.main.bolder,fontWeight:500},b:{color:t.palette.chartBrand.main.light,fontWeight:500},c:{color:t.palette.grey[500],fontWeight:500}}},itemGap:Sn.legend.itemGap,itemWidth:Sn.legend.itemWidth,itemHeight:Sn.legend.itemHeight,formatter:u=>u==="Positive Impact"?`{a|${u}}`:u==="Negative Impact"?`{b|${u}}`:`{c|${u}}`},grid:{...Sn.grid,left:Sn.grid.left,right:Sn.grid.right,bottom:Sn.grid.bottom,top:Sn.grid.top,containLabel:Sn.grid.containLabel},dataZoom:[{type:"inside",xAxisIndex:[0],start:0,end:Math.min(25/s.length*100,100),zoomOnMouseWheel:!1,moveOnMouseMove:!0,moveOnMouseWheel:!0,preventDefaultMouseMove:!0},{type:"slider",show:!0,xAxisIndex:[0],start:0,end:100,bottom:10,height:20,borderColor:"transparent",backgroundColor:t.palette.action.hover,handleIcon:"path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6V24.4z M13.3,22H6.7v-1.2h6.6V22z M13.3,19.6H6.7v-1.2h6.6V19.6z",handleSize:"80%",fillerColor:t.palette.action.selected,emphasis:{handleStyle:{color:t.palette.primary.main}},handleStyle:{color:t.palette.primary.main,shadowBlur:3,shadowColor:"rgba(0, 0, 0, 0.3)",shadowOffsetX:2,shadowOffsetY:2},textStyle:{color:t.palette.text.secondary,fontSize:12}}],xAxis:{type:"category",data:s,axisLabel:{color:t.palette.text.secondary,fontFamily:t.typography.fontFamily,...Sn.xAxis.axisLabel,formatter:u=>{if(u.length<=20)return u;const h=u.split(" ");let f="",g="",x=!1;return h.forEach(b=>{if(!x){if(f.length===0&&b.length>20){f=`${b.substring(0,17)}...`,x=!0;return}(f+b).length<=20?f+=(f?" ":"")+b:g.length===0?g+=b:`${g} ${b}`.length<=20?g+=` ${b}`:(g+=` ${b.substring(0,20-g.length-1)}...`,x=!0)}}),g?f?`${f} 257${g}`:g:f}},axisLine:{lineStyle:{color:t.palette.divider}},axisTick:{alignWithLabel:!0,lineStyle:{color:t.palette.divider}}},yAxis:{type:"value",axisLine:{show:!0,lineStyle:{color:t.palette.divider}},splitLine:{lineStyle:{color:t.palette.divider,type:"dashed"}},axisTick:{show:!0,lineStyle:{color:t.palette.divider}},axisLabel:{show:!0,fontSize:11,fontFamily:n.fontFamily,color:t.palette.text.secondary,fontWeight:400,formatter:m0e},min:()=>{const u=_F(i,o,s);return Math.floor(u/1e3)*1e3},offset:10},series:[{name:"Assist",type:"bar",stack:"total",barMinHeight:Sn.series.barMinHeight,itemStyle:{borderColor:"transparent",color:"transparent"},emphasis:{itemStyle:{color:"transparent"}},data:o,silent:!0},{name:"Waterfall",type:"bar",stack:"total",barGap:Sn.barGap,barCategoryGap:Sn.barCategoryGap,barMinHeight:Sn.series.barMinHeight,itemStyle:{borderRadius:[...Sn.borderRadius],color:u=>{const p=typeof u.value=="number"?u.value:0,h=typeof u.name=="string"?u.name:"";return h.includes("Base")||h.includes("Total")?t.palette.grey[300]:p>0?t.palette.chartBrand.main.bolder:t.palette.chartBrand.main.light}},label:{show:!1},emphasis:{itemStyle:{opacity:.9}},data:i},{name:"Positive Impact",type:"bar",stack:"export",data:l,itemStyle:{color:"transparent"},label:{show:!1}},{name:"Negative Impact",type:"bar",stack:"export",data:c,itemStyle:{color:"transparent"},label:{show:!1}}]}}const I0e=()=>{const e=m.useRef(null),t=Re(),{data:n,dataLoading:r,metaData:s,metaDataLoading:i,track:o}=vg(),l=m.useMemo(()=>T0e(n||[],t),[n,t]),c=!i&&s.length===0,d=m.useMemo(()=>`ExFactorsTrend_Waterfall_${n?.[0]?.kpiNiceId?`${n[0].kpiNiceId}_`:"_"}`,[n]),u=m.useCallback(p=>{o("download",{fileType:p,chartName:`ExFactorsTrend_Waterfall_${d}`})},[o,d]);return a.jsx(Ve,{sx:{height:"650px",minWidth:"60%",maxWidth:"100%"},children:a.jsxs(Ue,{sx:{p:"20px 24px",height:"100%",display:"flex",flexDirection:"column"},children:[a.jsxs($,{direction:"row",justifyContent:"space-between",alignItems:"center",mb:2,children:[a.jsxs($,{direction:"row",alignItems:"center",spacing:1,children:[a.jsx(I,{variant:"h6",children:"External Factors' Impact On Base Conversions"}),a.jsx(be,{title:"This chart shows how each external factor contributed to the change in base conversions during the selected time period. The grey bars represent the total base conversions for each month (as selected in the calendar picker). The light and dark purple bars reflect the modeled increase or decrease in base conversions attributed to each factor, with any remaining change labeled as 'Unexplained'.",placement:"bottom",children:a.jsx(Si,{height:16,width:16})})]}),a.jsx($,{direction:"row",alignItems:"center",spacing:2,children:r&&!c?a.jsx(fe,{variant:"rounded",width:40,height:28}):a.jsx(EF,{chartRef:e,fileName:d,onDownload:u,disabled:n?.length===0})})]}),r&&!c?a.jsx(fe,{variant:"rounded",width:"100%",height:400,sx:{flex:1}}):a.jsx(T,{sx:{flex:1,minHeight:0,position:"relative",width:"100%"},children:a.jsx(gs,{isDataEmpty:c||n&&n.length===0,children:a.jsx(T,{sx:{height:"100%",width:"100%",overflow:"hidden"},children:a.jsx(Fl,{option:l,ref:e,style:{height:"100%",width:"100%"},opts:{renderer:"svg"},onEvents:{click:p=>{p.componentType==="series"&&o("extfactorsWaterfallSelection",{extFactorsNames:[p.name]})},datazoom:p=>{const h=e.current?.getEchartsInstance();h&&_0e(h,t,p)}}})})})})]})})}
257,D0e={type:"bar",barGap:0,barCategoryGap:"20%",z:1},A0e={type:"line",symbol:"circle",symbolSize:8,z:10,zlevel:1},HT=e=>{if(e==null||Number.isNaN(e))return"N/A";if(e===0)return"0";const t=Math.abs(e);if(t>=1e12)return e.toExponential(2);if(t>=1e9)return`${(e/1e9).toFixed(1)}B`;if(t>=1e6)return`${(e/1e6).toFixed(1)}M`;if(t>=1e3)return`${(e/1e3).toFixed(1)}K`;const n=e.toString();return n.includes(".")?n.replace(/\.?0+$/,""):n},M0e=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?"Invalid Date":t.toLocaleString("en-US",{month:"short",year:"numeric",timeZone:"UTC"})};U.object({name:U.string(),value:U.number()});const R0e=U.object({axisValue:U.string().optional(),name:U.string(),value:U.union([U.number(),U.tuple([U.string(),U.number()])]),seriesName:U.string(),marker:U.string(),color:U.string().optional(),dimensionNames:U.array(U.string()).optional(),encode:U.record(U.unknown()).optional(),dataIndex:U.number().optional(),dataType:U.string().optional(),seriesId:U.string().optional(),seriesType:U.string().optional()}),N0e=e=>e.reduce((t,n)=>{const r=M0e(n.modelDate);return t[r]||(t[r]=[]),t[r].push(n),t},{}),O0e=(e,t)=>{const n=Object.keys(e).sort((i,o)=>new Date(i).getTime()-new Date(o).getTime()),r=[],s=[];return n.forEach(i=>{const l=(e[i]||[]).find(c=>c.extfactorName===t);r.push({name:i,value:l?.conversions??0}),s.push({name:i,value:l?.extfactorValue??0})}),{conversionsData:r,factorValueData:s,months:n}},P0e=(e,t,n)=>{const{palette:r,typography:s}=t,{fontFamily:i=""}=s,o=N0e(e),{conversionsData:l,factorValueData:c,months:d}=O0e(o,n),u=[{...D0e,name:"Conversions",yAxisIndex:0,data:l,itemStyle:{color:r.chartBrand.main.light,borderRadius:[4,4,0,0],opacity:.8},emphasis:{itemStyle:{opacity:1}},label:{show:!0,position:"insideTop",distance:5,formatter:h=>{if(typeof h=="object"&&h!==null&&"value"in h){const f=Number(h.value);return Number.isNaN(f)?"0":Math.floor(f).toString()}return"0"},fontSize:11,fontFamily:i,color:r.common.white,fontWeight:"bold",align:"center",verticalAlign:"top"},labelLayout:{hideOverlap:!0,moveOverlap:"shiftY",draggable:!1}},{...A0e,name:`${n} Value`,yAxisIndex:1,symbol:"circle",symbolSize:12,lineStyle:{width:2,color:r.chartBrand.main.bolder},itemStyle:{color:r.chartBrand.main.bolder,borderColor:r.background.paper,borderWidth:2},emphasis:{itemStyle:{borderWidth:2},scale:1.25},data:c,label:{show:!1}}];return{grid:{left:"8%",right:"8%",bottom:"10%",top:"15%",containLabel:!0},legend:{show:!1},tooltip:{trigger:"axis",axisPointer:{type:"shadow"},formatter:h=>{if(!Array.isArray(h)||h.length===0)return"";const f=h.reduce((y,v)=>{const C=R0e.safeParse(v);return C.success&&y.push(C.data),y},[]);if(f.length===0)return"";const g=f[0],x=g?.axisValue||g?.name||"";let b=x?`${x}<br/>`:"";return f.forEach(y=>{let v,C;if(typeof y.value=="number")C=y.value;else if(Array.isArray(y.value)&&y.value.length>1){const w=Number(y.value[1]);C=Number.isNaN(w)?0:w}else C=0;y.seriesName?.includes("Value")?v=C.toFixed(2):v=HT(C),b+=`${y.marker||""} ${y.seriesName||""}: ${v}<br/>`}),b},backgroundColor:r.background.paper,borderColor:r.divider,textStyle:{color:r.text.primary,fontFamily:i,fontSize:12},padding:[8,12]},xAxis:{type:"category",data:d,axisLabel:{show:!0,interval:0,overflow:"truncate",width:80,color:r.text.secondary,fontSize:11,fontFamily:i,hideOverlap:!0,formatter:h=>{const f=h.split(" ");return f.length>1?`${f[0]} 258${f.slice(1).join(" ")}`:h}},axisLine:{show:!1},axisTick:{show:!1}},yAxis:[{type:"value",name:"Conversions Driven by Factor",position:"left",nameLocation:"middle",nameGap:50,nameTextStyle:{color:r.chartBrand.main.light,fontSize:11,fontFamily:i,fontWeight:500},axisLabel:{formatter:h=>HT(h),color:r.chartBrand.main.light,fontSize:11,fontFamily:i,margin:8},axisLine:{show:!0,lineStyle:{color:r.chartBrand.main.light,width:2}},axisTick:{show:!0,lineStyle:{color:r.chartBrand.main.light}},splitLine:{show:!1}},{type:"value",name:`${n} Value`,position:"right",nameLocation:"middle",nameGap:50,nameTextStyle:{color:r.chartBrand.main.bolder,fontSize:11,fontFamily:i,fontWeight:500},axisLabel:{formatter:h=>h.toFixed(2),color:r.chartBrand.main.bolder,fontSize:11,fontFamily:i,margin:8}
258,axisLine:{show:!0,lineStyle:{color:r.chartBrand.main.bolder,width:2}},axisTick:{show:!0,lineStyle:{color:r.chartBrand.main.bolder}},splitLine:{show:!1}}],animation:!0,animationDuration:1e3,animationEasing:"cubicInOut",series:u}},L0e=()=>{const e=m.useRef(null),t=Re(),{data:n,dataLoading:r,metaData:s,metaDataLoading:i,track:o}=vg(),[l,c]=m.useState(""),d=!i&&s.length===0,u=m.useMemo(()=>{const b=new Set;return n.forEach(y=>{y.extfactorName!=="Unexplained"&&y.extfactorName!=="Base"&&b.add(y.extfactorName)}),Array.from(b)},[n]),p=b=>{c(b.target.value),o("extfactorsTrendSelection",{extFactorsNames:b.target.value})};m.useEffect(()=>{u.length>0&&c(u[0]||"")},[n,u]);const h=m.useMemo(()=>n?n.filter(b=>b.extfactorName===l):[],[n,l]),f=m.useMemo(()=>P0e(h,t,l),[h,t,l]),g=m.useMemo(()=>`ExFactorsTrend_${l}`,[l]),x=m.useCallback(b=>{o("download",{chartName:"ExFactors_Trend",fileType:b})},[o]);return a.jsx(Ve,{sx:{height:"570px",display:"flex",flexDirection:"column"},children:a.jsxs(Ue,{sx:{p:"20px 32px",display:"flex",flexDirection:"column",flex:1,height:"100%"},children:[a.jsxs($,{direction:{xs:"column",lg:"row"},alignItems:{xs:"flex-start",lg:"center"},justifyContent:"space-between",spacing:2,sx:{mb:{xs:2,lg:0}},children:[a.jsxs($,{direction:"row",alignItems:"center",spacing:1,children:[a.jsxs(I,{variant:"h6",children:[l||"External Factor"," Over Time"]}),a.jsx(be,{title:"This chart shows how the selected external factor and its attributed base conversions have changed over time. The left y-axis represents total base conversions attributed to the factor, while the right y-axis shows the factorâs actual value.",placement:"bottom",children:a.jsx(Si,{height:16,width:16})})]}),a.jsx($,{direction:"row",alignItems:"center",spacing:1,sx:{width:{xs:"100%",md:"auto"}},children:r&&!d?a.jsxs($,{direction:"row",alignItems:"center",spacing:1,children:[a.jsx(fe,{variant:"rounded",width:260,height:28}),a.jsx(fe,{variant:"rounded",width:40,height:28})]}):a.jsxs($,{direction:"row",alignItems:"center",spacing:1,children:[a.jsx(I,{variant:"body1",children:"Show:"}),a.jsx(Qe,{children:a.jsx(tt,{sx:{width:260,height:40},value:l,onChange:p,disabled:!n?.length||u.length===0,children:u.map(b=>a.jsx(Se,{value:b,children:b},b))})}),a.jsx(EF,{chartRef:e,fileName:g,onDownload:x,disabled:n?.length===0})]})})]}),a.jsx(T,{sx:{flex:1,display:"flex",position:"relative",minHeight:0,mt:2},children:r&&!d?a.jsx($,{sx:{flex:1,width:"100%"},justifyContent:"center",alignItems:"center",children:a.jsx(fe,{variant:"rounded",width:"100%",height:"100%"})}):a.jsx(T,{sx:{flex:1,width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(gs,{isDataEmpty:d||n&&n.length===0,children:a.jsx(bg,{sx:{flex:1,width:"100%",height:"100%"},children:a.jsx(Fl,{notMerge:!0,option:f,opts:{renderer:"svg"},ref:e,style:{height:"100%",width:"100%"}})})})})})]})})},F0e={selectedDateRange:[null,null],selectedKpi:"",selectedMediaAttribute:"GL_TYPE_NAME"},$0e=(e,t)=>t.type in e?{...e,[t.type]:t.value}:t.type==="filtersBar"||t.type==="resetFilters"?{...e,...t.value}:e,z0e=({selectedKpi:e,selectedDateRange:t})=>{const{engagementNiceId:n}=pe(),{kpiScalar:r}=Zm(e),{data:s=[],isFetching:i}=u3({engagementNiceId:n}),o=m.useMemo(()=>({engagement_nice_id:n,kpi_nice_id:e,start_date:t?.[0]?.format("YYYY-MM-DD")??"",end_date:t?.[1]?.format("YYYY-MM-DD")??"",kpi_scalar:r??null}),[n,r,t,e]),l=!e||!t,{data:c=[],isFetching:d,isUninitialized:u}=p3({body:o},{skip:l}),p=d||u;return{data:m.useMemo(()=>c.filter(f=>f.conversions!=null),[c]),dataLoading:p,metaData:s,metaDataLoading:i}},B0e=({children:e})=>{const[t,n]=m.useReducer($0e,F0e),r=Hu("externalFactors"),{selectedDateRange:s,selectedKpi:i}=t,{data:o,dataLoading:l,metaData:c,metaDataLoading:d}=z0e({selectedDateRange:s,selectedKpi:i}),u=m.useMemo(()=>({dispatch:n,state:t,data:o,dataLoading:l,metaData:c,metaDataLoading:d,track:r}),[o,l,c,d,t,r]);return a.jsx(jF.Provider,{value:u,children:e})},U0e=()=>a.jsx(B0e,{children:a.jsx($,{direction:"column",gap:5,minWidth:"600px",height:"100%",sx:{minHeight:"100vh",width:"100%"},children:a.jsxs($,{gap:2.5,sx:{height:"100%",display:"flex",flexDirection:"column"},children:[a.jsx(Xt,{title:"External Factors"}),a.jsxs($,{direction:"row",alignItems:"center",justifyContent:"space-between",children:[a.jsx(I,{variant:"subtitle2",fontWeight:400,children:"A look at how non-media factors, such as economic conditions and the weather, affect base conversions"}),a.jsx(l0e,{})]}),a.jsx(o0e,{}),a.jsxs(T,{sx:{display:"flex",flexDirection:"column",gap:2.5},children:[a.jsx(I0e,{}),a.jsx(L0e,{})]})]})})}),TF=m.createContext(null),jo=()=>m.useContext(TF),La=e=>typeof e=="string"||typeof e=="number"?String(e):"",qT=1e9,GT=1e6,YT=1e3,nu=e=>{let t;if(typeof e=="number")t=e;else if(typeof e=="string"){const n=Number(e);if(Number.isNaN(n))return"";t=n}else return"";return t>=qT?`${(t/qT).toFixed(1)}B`:t>=GT?`${(t/GT).toFixed(1)}M`:t>=YT?`${(t/YT).toFixed(0)}K`:t.toFixed(0)},Cg=(e,t="USD")=>`${new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:0}).format(0).replace(/[0-9.,]/g,"")}${nu(e)}`,Vs=(e,t="USD")=>{const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:2,maximumFractionDigits:2}).format(n):""},V0e=1e6,KT=5e4,QT=2,W0e=["day","week","month"],H0e=e=>W0e.some(t=>t===e),q0e=(e,t,n)=>{if(!H0e(e)||!t||!n)return 0;const r=t.startOf(e),s=n.startOf(e);return Math.max(0,s.diff(r,e))+1},G0e=({columns:e,endDate:t,metrics:n,pivot:r,startDate:s})=>Math.max(0,r?e.length-1+q0e(r.buckets,s,t):e.length+(n?.length??0)),Y0e=e=>{const t=e.toString().length;if(t<=QT)return e;const n=10**(t-QT);return Math.floor(e/n)*n},K0e=e=>{const t=G0e(e);if(t<=0)return KT;const n=Y0e(Math.floor(V0e/t));return Math.min(KT,Math.max(1,n))},Q0e=/^attribute_\d+$/,J0e=e=>e.filter(({active:t})=>t).map(({dimension:t,dimension_type:n,title:r})=>Q0e.test(t)?{label:r,value:`${n}_${t}`}:{label:r,value:t}).sort((t,n)=>t.label.localeCompare(n.label)),Nc=({isLoading:e,label:t,value:n})=>a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default",flex:1,minWidth:120},children:a.jsxs(Ue,{sx:{"&:last-child":{pb:2},py:1.5},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:10,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase"},children:t}),e?a.jsx(fe,{height:36,width:"60%"}):a.jsx(I,{sx:{fontSize:"1.5rem",fontWeight:700},children:n})]})}),ya=({height:e=120,message:t="Couldn't load this data."})=>a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center",color:"text.secondary",height:e,justifyContent:"center"},children:[a.jsx(lA,{size:16}),a.jsx(I,{color:"text.secondary",variant:"body2",children:t})]}),IF=({abbreviateSpend:e=!0,isError:t=!1,isLoading:n,kpis:r})=>{const{engagementCurrency:s}=pe(),i=e?Cg(r.spend,s):Vs(r.spend,s),o=m.useMemo(()=>new Intl.NumberFormat("en-US",{style:"currency",currency:s,minimumFractionDigits:2,maximumFractionDigits:2}).format(r.cpm),[r.cpm,s]);return t?a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default"},children:a.jsx(Ue,{sx:{"&:last-child":{pb:2},py:1.5},children:a.jsx(ya,{height:56})})}):a.jsxs($,{direction:"row",gap:2,sx:{flexWrap:"wrap"},children:[a.jsx(Nc,{isLoading:n,label:"Total Spend",value:i}),a.jsx(Nc,{isLoading:n,label:"Impressions",value:nu(r.impressions)}),a.jsx(Nc,{isLoading:n,label:"Clicks",value:nu(r.clicks)}),a.jsx(Nc,{isLoading:n,label:"CPM",value:o}),a.jsx(Nc,{isLoading:n,label:"CTR",value:`${r.ctr.toFixed(2)}%`})]})},X0e=[{label:"Total",value:"total"},{label:"Month",value:"month"},{label:"Week",value:"week"},{label:"Day",value:"day"}],Mw=[{label:"Spend",value:"total_investment"},{label:"Impressions",value:"total_impressions"},{label:"Clicks",value:"clicks"}],Z0e=()=>{const{dataExplorer:e,pivotOptions:t,pivotOptionsLoading:n}=jo(),{pivotConfig:r,setPivotConfig:s}=e,i=m.useCallback((l,c)=>{s({rowDimensions:c.map(d=>d.value)})},[s]),o=m.useMemo(()=>t.filter(l=>r.rowDimensions.includes(l.value)),[r.rowDimensions,t]);return a.jsx(gl,{disableCloseOnSelect:!0,disabled:n,getOptionLabel:l=>l.label,multiple:!0,onChange:i,options:t,renderInput:l=>
258a.jsx(De,{...l,label:"Row Dimensions (Multi-Select)",size:"small",variant:"outlined"}),renderOption:(l,c,{selected:d})=>a.jsxs(T,{component:"li",...l,sx:{display:"flex",alignItems:"center",gap:1,"&.MuiAutocomplete-option":{px:2,py:0}},children:[a.jsx(et,{checked:d,sx:{px:0,py:1}}),c.label]},c.value),renderTags:(l,c)=>l.map((d,u)=>m.createElement(ut,{...c({index:u}),key:d.value,color:"primary",label:d.label,size:"small"})),sx:{minWidth:280},value:o})},ewe=()=>{const{dataExplorer:e,dateRange:t,maxDate:n,metadataLoading:r,minDate:s,setDateRange:i}=jo(),{generatePivot:o,isLoading:l,pivotConfig:c,setPivotConfig:d}=e,[u,p]=t,h=m.useCallback(x=>{d({columnDimension:x.target.value})},[d]),f=m.useCallback(x=>{d({metric:x.target.value})},[d]),g=c.rowDimensions.length>0&&c.columnDimension&&c.metric&&u&&p&&!l;return a.jsxs(T,{sx:{bgcolor:"background.paper",border:"1px solid",borderColor:"border.default",borderRadius:2,p:3},children:[a.jsx(I,{sx:{fontWeight:600,mb:.5},variant:"subtitle1",children:"Custom Pivot Table / Crosstab Builder"}),a.jsx(I,{color:"text.secondary",sx:{mb:3},variant:"body2",children:"Choose row and column dimensions, select a metric, and generate your own crosstab view of the data."}),a.jsxs($,{gap:4,children:[a.jsxs($,{direction:"row",gap:2,sx:{alignItems:"flex-start",justifyContent:"flex-start"},children:[a.jsx(ts,{allowManualInput:!0,loading:r,maxDate:n??void 0,minDate:s??void 0,setValue:i,value:t}),a.jsx(Z0e,{})]}),a.jsxs($,{direction:"row",gap:2,sx:{alignItems:"flex-start",justifyContent:"flex-start"},children:[a.jsxs(Qe,{size:"small",sx:{minWidth:160},children:[a.jsx(wt,{children:"Column Dimension"}),a.jsx(tt,{label:"Column Dimension",onChange:h,value:c.columnDimension,children:X0e.map(({label:x,value:b})=>a.jsx(Se,{value:b,children:x},b))})]}),a.jsxs(Qe,{disabled:c.columnDimension==="total",size:"small",sx:{minWidth:160},children:[a.jsx(wt,{children:"Metric"}),a.jsx(tt,{label:"Metric",onChange:f,value:c.columnDimension==="total"?"":c.metric,children:Mw.map(({label:x,value:b})=>a.jsx(Se,{value:b,children:x},b))})]}),a.jsx(re,{disabled:!g,onClick:o,startIcon:a.jsx(du,{size:16}),sx:{height:40,whiteSpace:"nowrap"},variant:"contained",children:"Generate Pivot"})]})]})]})},twe=(e,t)=>t==="month"?Z(e).format("YYYY-MM"):e,nwe=({columnDimension:e,engagementCurrency:t,pivotOptions:n,rowDimensions:r,timeBuckets:s})=>{const i=r.map(l=>({field:l,filterable:!0,flex:1,headerName:(n.find(c=>c.value===l)?.label??l).toUpperCase(),minWidth:140}));if(e==="total"){const l=[{align:"right",field:"total_investment",filterable:!0,headerAlign:"right",headerName:"SPEND",minWidth:120,type:"number",valueFormatter:c=>Vs(Number(c.value)||0,t)},{align:"right",field:"total_impressions",filterable:!0,headerAlign:"right",headerName:"IMPRESSIONS",minWidth:120,type:"number",valueFormatter:c=>(Number(c.value)||0).toLocaleString()},{align:"right",field:"clicks",filterable:!0,headerAlign:"right",headerName:"CLICKS",minWidth:100,type:"number",valueFormatter:c=>(Number(c.value)||0).toLocaleString()}];return[...i,...l]}const o=s.map(l=>({align:"right",field:l,filterable:!0,headerAlign:"right",headerName:twe(l,e),minWidth:100,type:"number",valueFormatter:c=>(Number(c.value)||0).toLocaleString()}));return[...i,...o]},rwe=()=>{const e=zn(),{engagementCurrency:t}=pe(),{dataExplorer:n,pivotOptions:r}=jo(),{isLoading:s,pivotConfig:i,pivotRows:o,timeBuckets:l,totalRows:c}=n,d=!s&&c>o.length,u=i.columnDimension==="total"?"All Metrics":Mw.find(g=>g.value===i.metric)?.label??i.metric,p=i.rowDimensions.map(g=>r.find(x=>x.value===g)?.label??g).join(" à "),h=m.useMemo(()=>nwe({columnDimension:i.columnDimension,engagementCurrency:t,pivotOptions:r,rowDimensions:i.rowDimensions,timeBuckets:l}),[t,i.columnDimension,i.rowDimensions,r,l]),f=m.useCallback(()=>{e.current.exportDataAsCsv({fileName:`media-dashboard-${Z().format("YYYY-MM-DD")}.csv`,delimiter:","})},[e]);return a.jsxs(T,{children:[a.jsxs($,{direction:"row",sx:{alignItems:"center",justifyContent:"space-between",mb:2},children:[a.jsxs(I,{variant:"subtitle1",children:[a.jsx("strong",{children:p}),` by ${i.columnDimension.charAt(0).toUpperCase()+i.columnDimension.slice(1)}`,a.jsxs(I,{color:"text.secondary",component:"span",sx:{ml:1},variant:"body2",children:["· ",u]})]}),a.jsxs($,{direction:"row",gap:2,sx:{alignItems:"center"},children:[d&&a.jsx(I,{color:"text.secondary",variant:"caption",children:`Showing ${o.length.toLocaleStr
258ing()} of ${c.toLocaleString()} rows â the export includes only these rows.`}),a.jsx(re,{onClick:f,size:"small",startIcon:a.jsx(bl,{size:14}),variant:"outlined",children:"Export CSV"})]})]}),a.jsx(T,{sx:{height:600,width:"100%"},children:a.jsx(Mn,{apiRef:e,columns:h,density:"compact",disableRowSelectionOnClick:!0,getRowId:g=>JSON.stringify(i.rowDimensions.map(x=>g[x])),loading:s,rows:s?[]:o})}),a.jsx(I,{color:"text.secondary",sx:{mt:1},variant:"caption",children:`${o.length} rows · ${h.length} columns · grouped by ${p.toLowerCase()}`})]})},swe=()=>{const{dataExplorer:e}=jo();return a.jsxs($,{gap:4,children:[a.jsx(ewe,{}),e.hasGenerated&&(e.isError?a.jsx(ya,{message:"Couldn't generate the pivot table. Adjust your selections and try again."}):a.jsx(rwe,{}))]})};var Pp={};const DF=Yz(d5);var Oc={},JT;function iwe(){if(JT)return Oc;JT=1,Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.pick=void 0;function e(t,n){var r={};return n.forEach(function(s){r[s]=t[s]}),r}return Oc.pick=e,Oc}var Pc={},XT;function awe(){if(XT)return Pc;XT=1,Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.isFunction=void 0;function e(t){return typeof t=="function"}return Pc.isFunction=e,Pc}var Lc={},ZT;function owe(){if(ZT)return Lc;ZT=1,Object.defineProperty(Lc,"__esModule",{value:!0}),Lc.isString=void 0;function e(t){return typeof t=="string"}return Lc.isString=e,Lc}var Fc={},eI;function lwe(){if(eI)return Fc;eI=1,Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.isEqual=void 0;var e=DF,t=(0,e.__importDefault)(YL());return Fc.isEqual=t.default,Fc}var tI;function cwe(){if(tI)return Pp;tI=1,Object.defineProperty(Pp,"__esModule",{value:!0});var e=DF,t=(0,e.__importStar)(SD()),n=GL(),r=iwe(),s=awe(),i=owe(),o=lwe(),l=(function(c){(0,e.__extends)(d,c);function d(u){var p=c.call(this,u)||this;return p.echarts=u.echarts,p.ele=null,p.isInitialResize=!0,p}return d.prototype.componentDidMount=function(){this.renderNewEcharts()},d.prototype.componentDidUpdate=function(u){var p=this.props.shouldSetOption;if(!((0,s.isFunction)(p)&&!p(u,this.props))){if(!(0,o.isEqual)(u.theme,this.props.theme)||!(0,o.isEqual)(u.opts,this.props.opts)||!(0,o.isEqual)(u.onEvents,this.props.onEvents)){this.dispose(),this.renderNewEcharts();return}var h=["option","notMerge","lazyUpdate","showLoading","loadingOption"];(0,o.isEqual)((0,r.pick)(this.props,h),(0,r.pick)(u,h))||this.updateEChartsOption(),(!(0,o.isEqual)(u.style,this.props.style)||!(0,o.isEqual)(u.className,this.props.className))&&this.resize()}},d.prototype.componentWillUnmount=function(){this.dispose()},d.prototype.getEchartsInstance=function(){return this.echarts.getInstanceByDom(this.ele)||this.echarts.init(this.ele,this.props.theme,this.props.opts)},d.prototype.dispose=function(){if(this.ele){try{(0,n.clear)(this.ele)}catch(u){console.warn(u)}this.echarts.dispose(this.ele)}},d.prototype.renderNewEcharts=function(){var u=this,p=this.props,h=p.onEvents,f=p.onChartReady,g=this.updateEChartsOption();this.bindEvents(g,h||{}),(0,s.isFunction)(f)&&f(g),this.ele&&(0,n.bind)(this.ele,function(){u.resize()})},d.prototype.bindEvents=function(u,p){function h(g,x){(0,i.isString)(g)&&(0,s.isFunction)(x)&&u.on(g,function(b){x(b,u)})}for(var f in p)Object.prototype.hasOwnProperty.call(p,f)&&h(f,p[f])},d.prototype.updateEChartsOption=function(){var u=this.props,p=u.option,h=u.notMerge,f=h===void 0?!1:h,g=u.lazyUpdate,x=g===void 0?!1:g,b=u.showLoading,y=u.loadingOption,v=y===void 0?null:y,C=this.getEchartsInstance();return C.setOption(p,f,x),b?C.showLoading(v):C.hideLoading(),C},d.prototype.resize=function(){var u=this.getEchartsInstance();if(!this.isInitialResize)try{u.resize()}catch(p){console.warn(p)}this.isInitialResize=!1},d.prototype.render=function(){var u=this,p=this.props,h=p.style,f=p.className,g=f===void 0?"":f,x=(0,e.__assign)({height:300},h);return t.default.createElement("div",{ref:function(b){u.ele=b},style:x,className:"echarts-for-react "+g})},d})(t.PureComponent);return Pp.default=l,Pp}var dwe=cwe();const Rw=dt(dwe),Nw=Object.freeze(Object.defineProperty({__proto__:null,Axis:TW,ChartView:IW,ComponentModel:DW,ComponentView:AW,List:MW,Model:RW,PRIORITY:NW,SeriesModel:OW,color:PW,connect:LW,dataTool:FW,dependencies:$W,disConnect:zW,disconnect:BW,dispose:UW,env:VW,extendChartView:WW,extendComponentModel:HW,extendComponentView:qW,extendSeriesModel:GW,format:YW,getCoordinateSystemDimensions:KW,getInstanceByDom:QW,getInstanceById:JW,getMap:XW,graphic:ZW,helper:eH,init:tH,innerDrawElementOnCanvas:nH,matrix:rH,number:sH,parseGeoJSON:Aj,parseGeoJson:Aj,registerAction:iH,registerCoordinateSystem:aH,registerLayout:oH,registerLoading:lH,registerLocale:cH,registerMap:dH,registerPostInit:uH,registerPostUpdate:pH,registerPreprocessor:hH,registerProcessor:fH,registerTheme:mH,registerTransform:gH,registerUpdateLifecycle:xH,registerVisual:bH,setCanvasCreator:yH,setPlatformAPI:vH,throttle:CH,time:wH,use:Tm,util:SH,vector:jH,version:kH,zrUtil:EH,zrender:_H},Symbol.toStringTag,{value:"Module"}));Tm([TH,oM,SC,jC]);const uwe=({data:e,totalSpend:t})=>{const{engagementCurrency:n}=pe(),{palette:r}
258=Re(),{chartSet:s}=r,i=m.useMemo(()=>({color:s,legend:{show:!1},series:[{center:["50%","50%"],data:e.map(({name:o,spend:l})=>({name:o,value:l})),label:{show:!1},radius:["60%","90%"],type:"pie"}],tooltip:{confine:!0,trigger:"item",formatter:o=>{const l=o.percent.toFixed(1);return`${o.name}: ${Vs(o.value,n)} (${l}%)`}}}),[s,e,n]);return a.jsxs($,{direction:"row",gap:3,sx:{alignItems:"center"},children:[a.jsxs(T,{sx:{position:"relative",height:180,width:180},children:[a.jsx(Rw,{echarts:Nw,option:i,style:{height:"100%",width:"100%"}}),a.jsxs(T,{sx:{alignItems:"center",display:"flex",flexDirection:"column",inset:0,justifyContent:"center",position:"absolute",pointerEvents:"none"},children:[a.jsx(I,{sx:{fontSize:"1.25rem",fontWeight:700},children:Vs(t,n)}),a.jsx(I,{color:"text.secondary",sx:{fontSize:9,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase"},children:"Total Spend"})]})]}),a.jsx($,{gap:.75,sx:{flex:1},children:e.map(({name:o,spend:l},c)=>{const d=t>0?l/t*100:0;return a.jsxs($,{direction:"row",sx:{alignItems:"center"},children:[a.jsx(T,{sx:{bgcolor:s[c%s.length],borderRadius:"50%",height:10,mr:1,minWidth:10,width:10}}),a.jsx(I,{sx:{flex:1,fontSize:12},children:o}),a.jsx(I,{sx:{fontSize:12,mr:1.5,minWidth:50,textAlign:"right"},children:Vs(l,n)}),a.jsxs(I,{color:"text.secondary",sx:{fontSize:12,minWidth:40,textAlign:"right"},children:[d.toFixed(1),"%"]})]},o)})})]})},pwe=({data:e,isError:t,isLoading:n,totalSpend:r})=>a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default",flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontWeight:600,mb:.5},variant:"subtitle1",children:"Media mix"}),a.jsx(I,{color:"text.secondary",sx:{mb:2},variant:"body2",children:"Share of spend by channel type."}),t?a.jsx(ya,{height:180}):n?a.jsx($,{gap:1,children:a.jsx(fe,{height:180,variant:"rectangular",width:"100%"})}):a.jsx(uwe,{data:e,totalSpend:r})]})}),hwe=({data:e,totalSpend:t})=>{const{engagementCurrency:n}=pe(),{palette:r}=Re(),{chartSet:s}=r;return a.jsx($,{gap:2,children:e.map(({name:i,spend:o},l)=>{const c=t>0?o/t*100:0;return a.jsxs($,{direction:"row",sx:{alignItems:"center"},children:[a.jsx(I,{sx:{fontSize:13,minWidth:120,mr:2},children:i}),a.jsx(T,{sx:{flex:1,mr:2},children:a.jsx(T,{sx:{bgcolor:s[l%s.length],borderRadius:1,height:16,width:`${c}%`}})}),a.jsx(I,{sx:{fontSize:13,minWidth:60,mr:2},children:Vs(o,n)}),a.jsxs(I,{color:"text.secondary",sx:{fontSize:13,minWidth:45},children:[c.toFixed(1),"%"]})]},i)})})},fwe=({data:e,isError:t,isLoading:n,totalSpend:r})=>a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default"},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontWeight:600,mb:.5},variant:"subtitle1",children:"Spend by data source"}),a.jsx(I,{color:"text.secondary",sx:{mb:3},variant:"body2",children:"Where the budget landed across data sources."}),t?a.jsx(ya,{height:100}):n?a.jsxs($,{gap:2,children:[a.jsx(fe,{height:28}),a.jsx(fe,{height:28}),a.jsx(fe,{height:28})]}):a.jsx(hwe,{data:e,totalSpend:r})]})}),nI=({data:e,isError:t,isLoading:n,isNegative:r=!1,subtitle:s,title:i})=>{const{engagementCurrency:o}=pe();return a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default",flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontWeight:600,mb:.5},variant:"subtitle1",children:i}),a.jsx(I,{color:"text.secondary",sx:{mb:2},variant:"body2",children:s}),t?a.jsx(ya,{height:88}):n?a.jsxs($,{gap:1,children:[a.jsx(fe,{height:24}),a.jsx(fe,{height:24}),a.jsx(fe,{height:24})]}):a.jsxs($,{gap:1.5,children:[e.map(({cpm:l,name:c,spend:d},u)=>a.jsxs($,{direction:"row",sx:{alignItems:"center"},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:12,mr:1.5,width:16},children:u+1}),a.jsx(I,{sx:{flex:1,fontSize:13,fontWeight:500},children:c}),a.jsx(I,{sx:{fontSize:13,mr:2},children:Vs(d,o)}),a.jsxs(I,{sx:{color:r?"error.main":"success.main",fontSize:13,fontWeight:600},children:[Cg(l,o)," CPM"]})]},c)),!e.length&&a.jsx(I,{color:"text.secondary",variant:"body2",children:"No data available"})]})]})})},mwe=({data:e,isError:t,isLoading:n})=>{const{engagementCurrency:r}=pe(),s=e.reduce((c,{spend:d})=>Math.max(c,d),1),i=e.reduce((c,{spend:d})=>c+d,0),o=e.length>0?i/e.length:0,l=e.reduce((c,d)=>d.spend>c.spend?d:c,{spend:0,week:""});return a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default",flex:1},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontWeight:600,mb:.5},variant:"subtitle1",children:"Weekly spend"}),a.jsx(I,{color:"text.secondary",sx:{mb:2},variant:"body2",children:"Trend with peak + average."}),t?a.jsx(ya,{height:120}):n?a.jsx(fe,{height:120,variant:"rectangular"}):a.jsxs(a.Fragment,{children:[a.jsx($,{direction:"row",gap:.5,sx:{alignItems:"flex-end",height:120},children:e.map(({spend:c,week:d})=>a.jsx(be,{title:`${d}: ${Vs(c,r)}`,placement:"top",arrow:!0,children:a.jsx(T,{sx:{bgcolor:"primary.main",borderRadius:"2px 2px 0 0",cursor:"pointer",flex:1,height:`${c/s*100}%`,minHeight:2,transition:"height 0.3s","&:hover":{opacity:.8}}})},d))}),a.jsx($,{direction:"row",gap:.5,sx:{borderTop:"1px solid",borderColor:"divider",mb:2,pt:.5},children:e.map(({week:c},d)=>{const u=e.length<=12||d%Math.ceil(e.length/8)===0;return a.jsx(T,{sx:{flex:1,textAlign:"center"},children:u&&a.jsx(I,{color:"text.secondary",sx:{fontSize:9,whiteSpace:"nowrap"},children:c})},c)})}),a.jsxs($,{direction:"row",gap:4,children:[a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:10,fontWeight:600,textTransform:"uppercase"},children:"Peak Week"}),a.jsxs(I,{sx:{fontSize:14,fontWeight:600},children:[l.week," · ",Vs(l.spend,r)]})]}),a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:10,fontWeight:600,textTransform:"uppercase"},children:"Avg Weekly"}),a.jsx(I,{sx:{fontSize:14,fontWeight:600},children:Vs(o,r)})]}),a.jsxs(T,{children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:10,fontWeight:600,textTransform:"uppercase"},children:"Weeks"}),a.jsx(I,{sx:{fontSize:14,fontWeight:600},children:e.length})]})]})]})]})})},gwe=()=>{const{dateRange:e,maxDate:t,metadataLoading:n,minDate:r,overview:s,setDateRange:i}=jo(),{byDatasource:o,kpis:l,mediaMix:c,topPerformers:d,weeklySpend:u}=s,p=m.useMemo(()=>{const b=l.rows[0]??{},y=Number(b.total_investment)||0,v=Number(b.total_impressions)||0,C=Number(b.clicks)||0;return{clicks:C,cpm:v>0?y/v*1e3:0,ctr:v>0?C/v*100:0,impressions:v,spend:y}},[l.rows]),h=m.useMemo(()=>c.rows.map(b=>({name:La(b.gl_type_name)||"Other",spend:Number(b.total_investment)||0})).sort((b,y)=>y.spend-b.spend),[c.rows]),f=m.useMemo(()=>u.rows.map(b=>({spend:Number(b.total_investment)||0,weekStart:La(b.week)})).filter(({weekStart:b})=>b).sort((b,y)=>b.weekStart.localeCompare(y.weekStart)).map(({spend:b,weekStart:y})=>({spend:b,week:Z(y).format("MMM DD")})),[u.rows]),g=m.useMemo(()=>d.rows.map(b=>{const y=Number(b.total_investment)||0,v=Number(b.total_impressions)||0;return{cpm:v>0?y/v*1e3:0,name:La(b.vendor_nice_id)||"Unknown",spend:y}}).filter(({spend:b})=>b>0).sort((b,y)=>b.cpm-y.cpm),[d.rows]),x=m.useMemo(()=>o.rows.map(b=>({name:La(b.datasource_name)||"Unknown",spend:Number(b.total_investment)||0})).sort((b,y)=>y.spend-b.spend),[o.rows]);return a.jsxs($,{gap:4,children:[a.jsx(ts,{allowManualInput:!0,maxDate:t??void 0,minDate:r??void 0,loading:n,setValue:i,value:e}),a.jsx(IF,{abbreviateSpend:!1,isError:l.isError,isLoading:l.isLoading,kpis:p}),a.jsxs($,{direction:{md:"column",lg:"row"},gap:3,children:[a.jsx(pwe,{data:h,isError:c.isError,isLoading:c.isLoading,totalSpend:p.spend}),a.jsx(mwe,{data:f,isError:u.isError,isLoading:u.isLoading})]}),a.jsxs($,{direction:{md:"column",lg:"row"},gap:3,children:[a.jsx(nI,{data:g.slice(0,5),isError:d.isError,isLoading:d.isLoading,title:"Top performers",subtitle:"Lowest CPM vendors â where every dollar bought the most reach."}),a.jsx(nI,{data:g.slice(-5).reverse(),isError:d.isError,isLoading:d.isLoading,title:"Needs attention",subtitle:"Highest CPM vendors â worth a closer look.",isNegative:!0})]}),a.jsx(fwe,{data:x,isError:o.isError,isLoading:o.isLoading,totalSpend:p.spend})]})};Tm([IH,lM,oM,SC,jC]);const xwe={clicks:"Clicks",total_impressions:"Impressions",total_investment:"Spend"},bwe=(e,t,n)=>t==="total_investment"?Cg(e,n):nu(e),ywe=({groupBy:e,groupByOptions:t,isError:n,isLoading:r,metric:s,rows:i})=>{const{engagementCurrency:o}=pe(),{palette:l,typography:c}=Re(),{chartSet:d}=l,{secondary:u}=l.text,{fontFamily:p=""}=c,h=xwe[s]??s,f=t.find(x=>x.value===e)?.label??e,g=m.useMemo(()=>{const x={},b=new Set;
258i.forEach(w=>{const S=La(w.week);if(!S)return;const E=La(w[e])||"Other";b.add(E),x[S]||(x[S]={}),x[S][E]=Number(w[s])||0});const y=Object.keys(x).sort(),v=[...b].sort(),C=v.map(w=>({data:y.map(S=>x[S]?.[w]??0),name:w,stack:"total",type:"bar"}));return{color:d,grid:{bottom:92,left:70,right:20,top:20},legend:{bottom:0,data:v,pageIconColor:u,pageTextStyle:{color:u,fontFamily:p},textStyle:{color:u,fontFamily:p},type:"scroll"},series:C,tooltip:{confine:!0,trigger:"axis"},xAxis:{axisLabel:{color:u,fontFamily:p,rotate:45},data:y,type:"category"},yAxis:{axisLabel:{color:u,fontFamily:p,formatter:w=>bwe(w,s,o)},type:"value"}}},[e,s,i,o,d,u,p]);return a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default"},children:a.jsxs(Ue,{children:[a.jsxs(I,{sx:{fontWeight:600,mb:2},variant:"subtitle1",children:[h," by ",f," â Weekly Trend"]}),n?a.jsx(ya,{height:350}):r?a.jsx(fe,{height:350,variant:"rectangular"}):a.jsx(T,{sx:{height:350},children:a.jsx(Rw,{echarts:Nw,option:g,style:{height:"100%",width:"100%"}})})]})})},vwe=({groupBy:e,groupByOptions:t,metric:n,onGroupByChange:r,onMetricChange:s})=>a.jsxs($,{direction:"row",gap:3,sx:{alignItems:"center",flexWrap:"wrap"},children:[a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center"},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:11,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase"},children:"Metric"}),Mw.map(({label:i,value:o})=>a.jsx(ut,{color:n===o?"primary":"default",label:i,onClick:()=>s(o),size:"small",variant:n===o?"filled":"outlined"},o))]}),a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center"},children:[a.jsx(I,{color:"text.secondary",sx:{fontSize:11,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase"},children:"Group By"}),t.map(({label:i,value:o})=>a.jsx(ut,{color:e===o?"primary":"default",label:i,onClick:()=>r(o),size:"small",variant:e===o?"filled":"outlined"},o))]})]});Tm([DH,lM,SC,jC]);const Cwe=(e,t,n)=>t==="total_investment"?Cg(e,n):nu(e),wwe=({data:e,isError:t,isLoading:n,metric:r})=>{const{engagementCurrency:s}=pe(),{palette:i}=Re(),{chartSet:o}=i,l=m.useMemo(()=>({color:o,grid:{bottom:60,left:70,right:20,top:20},series:[{data:e.map(({value:c})=>c),lineStyle:{width:2},smooth:!0,symbol:"none",type:"line"}],tooltip:{confine:!0,trigger:"axis"},xAxis:{axisLabel:{rotate:45},data:e.map(({week:c})=>c),type:"category"},yAxis:{axisLabel:{formatter:c=>Cwe(c,r,s)},type:"value"}}),[e,r,s,o]);return a.jsx(Ve,{sx:{border:"1px solid",borderColor:"border.default"},children:a.jsxs(Ue,{children:[a.jsx(I,{sx:{fontWeight:600,mb:2},variant:"subtitle1",children:"Overall Weekly Trend (Filtered)"}),t?a.jsx(ya,{height:250}):n?a.jsx(fe,{height:250,variant:"rectangular"}):a.jsx(T,{sx:{height:250},children:a.jsx(Rw,{echarts:Nw,option:l,style:{height:"100%",width:"100%"}})})]})})},Swe=()=>{const{dateRange:e,groupByOptions:t,maxDate:n,metadataLoading:r,minDate:s,setDateRange:i,trends:o}=jo(),{groupBy:l,kpis:c,metric:d,setGroupBy:u,setMetric:p,stacked:h,weekly:f}=o,g=m.useMemo(()=>{const b=c.rows[0]??{},y=Number(b.total_investment)||0,v=Number(b.total_impressions)||0,C=Number(b.clicks)||0;return{clicks:C,cpm:v>0?y/v*1e3:0,ctr:v>0?C/v*100:0,impressions:v,spend:y}},[c.rows]),x=m.useMemo(()=>f.rows.map(b=>({value:Number(b[d])||0,weekStart:La(b.week)})).filter(({weekStart:b})=>b).sort((b,y)=>b.weekStart.localeCompare(y.weekStart)).map(({value:b,weekStart:y})=>({value:b,week:Z(y).format("MMM DD")})),[d,f.rows]);return a.jsxs($,{gap:4,children:[a.jsx(ts,{allowManualInput:!0,loading:r,maxDate:n??void 0,minDate:s??void 0,setValue:i,value:e}),a.jsx(IF,{isError:c.isError,isLoading:c.isLoading,kpis:g}),a.jsx(vwe,{groupBy:l,groupByOptions:t,metric:d,onGroupByChange:u,onMetricChange:p}),a.jsx(ywe,{groupBy:l,groupByOptions:t,isError:h.isError,isLoading:h.isLoading,metric:d,rows:h.rows}),a.jsx(wwe,{data:x,isError:f.isError,isLoading:f.isLoading,metric:d})]})},jwe=()=>{const{activeTab:e,setActiveTab:t}=jo(),n=(r,s)=>{t(s)};return a.jsxs($,{sx:{minWidth:600,rowGap:3,width:"100%"},children:[a.jsx(Xt,{title:"Media Dashboard"}),a.jsx(T,{sx:{borderBottom:1,borderColor:"divider"},children:a.jsxs(Vv,{onChange:n,value:e,children:[a.jsx(_n,{label:"Overview"}),a.jsx(_n,{label:"Trends & Analysis"}),a.jsx(_n,{label:"Data Explorer"})]})}),e===0&&a.jsx(gwe,{}),e===1&&a.jsx(Swe,{}),e===2&&a.jsx(swe,{})]})},Lp=["total_investment","total_impressions","clicks"],kwe={columnDimension:"total",metric:"total_investment",rowDimensions:["datasource_name","type_name"]},Mi=e=>({isError:e.isError,isLoading:e.isUninitialized||e.isFetching,rows:e.data?.rows??[]}),Ewe=({attributes:e,attributesLoading:t,dataSources:n,metadataList:r,metadataLoading:s})=>{const{engagementNiceId:i}=pe(),{pushNotification:o}
258=jt(),[l,c]=m.useState(0),[d,u]=m.useState([null,null]),[p,h]=m.useState("type_name"),[f,g]=m.useState("total_investment"),[x,b]=m.useState(kwe),[y,v]=m.useState(null),[C,w]=m.useState(!1),S=m.useRef(!1),E=m.useMemo(()=>J0e(e),[e]),k=E,j=m.useMemo(()=>n.filter(({active:ae})=>ae).map(({id:ae})=>ae).join(","),[n]),{maxDate:_,minDate:D}=m.useMemo(()=>{const ae=r.reduce((me,{max_date:ve})=>{if(ve){const Me=Z(ve);if(!me||Me.isAfter(me))return Me}return me},null),je=r.reduce((me,{min_date:ve})=>{if(ve){const Me=Z(ve);if(!me||Me.isBefore(me))return Me}return me},null);return{maxDate:ae,minDate:je}},[r]);m.useEffect(()=>{if(!S.current&&D&&_){S.current=!0;const ae=_.subtract(3,"month").startOf("month"),je=ae.isBefore(D)?D:ae;u([je,_])}},[D,_]);const M=m.useCallback(ae=>{u(ae),w(!1)},[]),N=m.useCallback(ae=>{b(je=>({...je,...ae})),v(null),w(!1)},[]),O=m.useCallback(()=>{v(x),w(!0)},[x]),[R,L]=d,P=R?.format("YYYY-MM-DD")??"",F=L?.format("YYYY-MM-DD")??"",z=m.useMemo(()=>j?j.split(",").map(Number):[],[j]),B=!!(R&&L&&j),W=(ae,je,me)=>({body:{columns:ae,datasource_ids:z,end_date:F,limit:K0e({columns:ae,endDate:L,metrics:je,pivot:me,startDate:R}),...je?{metrics:je}:{},offset:0,...me?{pivot:me}:{},start_date:P},engagementNiceId:i}),H=!B||l!==0&&l!==1,V=wa(W([],Lp),{skip:H}),G=wa(W(["week"],Lp),{skip:H}),X=wa(W(["gl_type_name"],["total_investment"]),{skip:!B||l!==0}),K=wa(W(["vendor_nice_id"],["total_investment","total_impressions"]),{skip:!B||l!==0}),ie=wa(W(["datasource_name"],["total_investment"]),{skip:!B||l!==0}),le=wa(W([p,"week"],Lp),{skip:!B||l!==1}),ce=wa(y&&y.columnDimension!=="total"?W([...y.rowDimensions,y.columnDimension],void 0,{buckets:y.columnDimension,value:y.metric}):W(y?.rowDimensions??[],Lp),{skip:!B||l!==2||!C||!y}),J=m.useRef(!1);m.useEffect(()=>{ce.isError&&!J.current?(J.current=!0,o({content:"Failed to generate the pivot table.",severity:"error"})):ce.isError||(J.current=!1)},[ce.isError,o]);const he=m.useMemo(()=>y&&ce.data?.rows||[],[y,ce.data]),ne=m.useMemo(()=>y&&ce.data?.buckets||[],[y,ce.data]),Y=y&&ce.data?.total||0;return m.useEffect(()=>{if(!t&&k.length){const ae=k.find(je=>je.value==="gl_type_name"||je.value==="type_name");ae&&h(ae.value)}},[t,k]),m.useEffect(()=>{if(!t&&E.length){const ae=E.find(ve=>ve.value==="datasource_name"),je=E.find(ve=>ve.value==="gl_type_name"||ve.value==="type_name"),me=[ae,je].filter(Boolean).map(ve=>ve.value);me.length&&N({rowDimensions:me})}},[t,E,N]),m.useMemo(()=>({activeTab:l,dataExplorer:{generatePivot:O,hasGenerated:C,isError:ce.isError,isLoading:ce.isFetching,pivotConfig:x,pivotRows:he,setPivotConfig:N,timeBuckets:ne,totalRows:Y},dateRange:d,groupByOptions:k,maxDate:_,metadataLoading:s,minDate:D,overview:{byDatasource:Mi(ie),kpis:Mi(V),mediaMix:Mi(X),topPerformers:Mi(K),weeklySpend:Mi(G)},pivotOptions:E,pivotOptionsLoading:t,setActiveTab:c,setDateRange:M,trends:{groupBy:p,kpis:Mi(V),metric:f,setGroupBy:h,setMetric:g,stacked:Mi(le),weekly:Mi(G)}}),[l,t,ie,d,O,k,C,V,_,X,s,D,x,E,ce.isError,ce.isFetching,he,ne,Y,M,N,K,p,f,le,G])},_we=()=>{const{engagementId:e,engagementNiceId:t}=pe(),{data:n=[]}=Qs(e),r=n[0]?.brand_nice_id??"",{data:s=[],isFetching:i,isUninitialized:o}=wm({brandNiceId:r,engagementNiceId:t},{skip:!t||!r}),{data:l=[]}=RA(e),{data:c=[],isFetching:d,isUninitialized:u}=$A({engagementNiceId:t},{skip:!t}),p=Ewe({attributes:s,attributesLoading:i||o,dataSources:l,metadataList:c,metadataLoading:d||u});return a.jsx(TF.Provider,{value:p,children:a.jsx(jwe,{})})},AF=m.createContext(null),wg=()=>m.useContext(AF),rI={parsedFile:void 0,uploadPercentageComplete:0,optimizationPercentageComplete:0,superconductorPercentageComplete:0,plannedMetaId:null,optMetaId:null,plannedJobId:null,optJobId:null,optError:null,scError:null},Twe=2e4,Ow=e=>typeof e[0]>"u",Th=e=>{for(;e.length>0;){const t=e.shift();if(typeof t[0]<"u"){e.unshift(t);break}}},Iwe=e=>{const t={};e.shift(),e.shift();const n=e.shift();e.shift();const r={};for(n.forEach((s,i)=>{r[s]=i});e.length>0;){const s=e.shift();if(Ow(s))break;const i=s[r.media_id];t[i]={};for(let o=0;o<n.length;o+=1){const l=n[o];let c=s[r[l]];(c===""||typeof c>"u"||c==="undefined")&&(c=null),t[i][l]=c}
258t[i].cpm_edit=t[i].cpm,t[i].spend_edit=t[i].spend,t[i].min_spend_edit=t[i].min_spend,t[i].max_spend_edit=t[i].max_spend}return t},Dwe=e=>{const t=[],n=e.shift();if(n[0]==="Touchpoint")return e.unshift(n),t;const r=n[1],s=n[2];e.shift();const i=e.shift();e.shift();const o=i.indexOf("min_spend")===-1?i.indexOf("original_min_spend"):i.indexOf("min_spend"),l=i.indexOf("max_spend")===-1?i.indexOf("original_max_spend"):i.indexOf("max_spend"),c=i.indexOf("min_spend")===-1?i.indexOf("current_min_spend"):i.indexOf("min_spend"),d=i.indexOf("max_spend")===-1?i.indexOf("current_max_spend"):i.indexOf("max_spend"),u=i.indexOf("category_name"),p=i.indexOf("type_name"),h=i.indexOf("platform_name"),f=i.indexOf("vehicle_name"),g=i.indexOf("tactic_name"),x=i.indexOf("market_name"),b=i.indexOf("country_name"),y=i.indexOf("datasource_name"),v=i.indexOf("vendor_nice_id"),C=i.indexOf("account_name"),w=i.indexOf("account_id"),S=i.indexOf("adgroup_id"),E=i.indexOf("adgroup_name"),k=i.indexOf("theme_1"),j=i.indexOf("theme_2"),_=i.indexOf("theme_3"),D=i.indexOf("theme_4"),M=i.indexOf("theme_5"),N=i.indexOf("theme_6"),O=i.indexOf("theme_7"),R=i.indexOf("theme_8"),L=i.indexOf("media_attribute_1"),P=i.indexOf("media_attribute_2"),F=i.indexOf("media_attribute_3"),z=i.indexOf("media_attribute_4"),B=i.indexOf("media_attribute_5"),W=i.indexOf("media_attribute_6"),H=i.indexOf("media_attribute_7"),V=i.indexOf("media_attribute_8"),G=i.indexOf("cpm")===-1?i.indexOf("original_cpm"):i.indexOf("cpm"),X=i.indexOf("spend")===-1?i.indexOf("original_spend"):i.indexOf("spend"),K=i.indexOf("cpm")===-1?i.indexOf("current_cpm"):i.indexOf("cpm"),ie=i.indexOf("spend")===-1?i.indexOf("current_spend"):i.indexOf("spend"),le=i.indexOf("impressions")===-1?i.indexOf("current_impressions"):i.indexOf("impressions"),ce=i.indexOf("media_id_level_lock");for(;e.length>0;){const J=e.shift(),he={category_name:J[u],type_name:J[p],platform_name:J[h],vehicle_name:J[f],tactic_name:J[g],market_name:J[x],country_name:J[b],datasource_name:J[y],vendor_nice_id:J[v],account_name:J[C],account_id:J[w],adgroup_id:J[S],adgroup_name:J[E],theme_1:J[k],theme_2:J[j],theme_3:J[_],theme_4:J[D],theme_5:J[M],theme_6:J[N],theme_7:J[O],theme_8:J[R],media_attribute_1:J[L],media_attribute_2:J[P],media_attribute_3:J[F],media_attribute_4:J[z],media_attribute_5:J[B],media_attribute_6:J[W],media_attribute_7:J[H],media_attribute_8:J[V]};if(Ow(J))break;const ne=r.split(",").map(Y=>he[Y]).join(",");t.push({aggs:r,ids:s,media_ids:[],values:J[0],aggValues:ne,active:J[X]>0?"T":"F",cpm:J[G],cpm_edit:J[K],min_spend:J[o],min_spend_edit:J[c],max_spend:J[l],max_spend_edit:J[d],spend:J[X],spend_edit:J[ie],impressions:J[le],media_id_level_lock:J[ce]})}return t},Awe=e=>{const t={levers:{}};Th(e);for(let n=0;n<Twe;n+=1){const r=e.shift();if(Ow(r))break;const s=r[0];let i=null;r[1]?i={name:r[1],id:r[2]}:i=r[2],t[s]=i}if(Th(e),t.levers.aggregates=Dwe(e),Th(e),t.levers.media=Iwe(e),t.levers.aggregates&&t.levers.aggregates.length>0){const n=t.levers.aggregates[0].aggs.split(",");Object.entries(t.levers.media).forEach(([r,s])=>{const i=n.map(c=>s[c]).join(","),o=t.levers.aggregates.find(c=>c.aggValues&&c.aggValues===i),l=!(parseFloat(Object.prototype.hasOwnProperty.call(s,"current_spend")?s.current_spend:s.spend_edit)===0&&parseFloat(Object.prototype.hasOwnProperty.call(s,"current_min_spend")?s.current_min_spend:s.min_spend_edit)===0&&parseFloat(Object.prototype.hasOwnProperty.call(s,"current_max_spend")?s.current_max_spend:s.max_spend_edit)===0);o&&l&&(o.media_ids?o.media_ids.push(s.media_id):o.media_ids=[s.media_id])})}return t},Mwe=e=>{const t=[];let n,r,s;const i=Mj.decode_range(e["!ref"]);for(r=i.s.r;r<=i.e.r;r+=1){for(n=[],s=i.s.c;s<=i.e.c;s+=1){const o=e[Mj.encode_cell({r,c:s})];typeof o>"u"?n.push(void 0):n.push(o.w)}t.push(n)}return t},Rwe=e=>{const t=Mwe(e);return Th(t),t.shift(),Awe(t)},Nwe=e=>{let t={};for(let n=0;n<e.SheetNames.length;n+=1)t=Rwe(e.Sheets[e.SheetNames[n]]);return t}
258,Owe=e=>{const n=new FileReader;return new Promise((r,s)=>{let i;n.onload=function(o){let l=o.target.result;const c=PH(l,{type:"binary"});i=Nwe(c),r(i)};try{n.readAsBinaryString(e)}catch(o){s(o)}})},Pwe=(e,t=2)=>{if(e===0)return"0 Bytes";const n=1024,r=t<0?0:t,s=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(n));return`${parseFloat((e/n**i).toFixed(r))} ${s[i]}`},Pw=e=>e.uploadPercentageComplete===100,Lw=e=>e.optimizationPercentageComplete===100&&e.superconductorPercentageComplete===100,Lwe=e=>e.every(t=>t.uploadPercentageComplete===100)&&e.length>0,MF=e=>e.every(t=>t.optimizationPercentageComplete===100&&t.superconductorPercentageComplete===100||t.optError||t.scError),Fw=e=>e.optError!==null||e.scError!==null,Fwe=({createPlanClicked:e,planFileData:t})=>{const n=Pw(t),r=Fw(t),s=Lw(t);return n?n&&!e?"Ready to run optimization":r?`Optimization failed 259⢠${t.optError}`:n&&!s&&e&&!r?"Running optimization":n&&s?"Complete":"":"Uploading"},$we=({createPlanClicked:e,planFileData:t})=>Pw(t)&&!Lw(t)&&e&&!Fw(t),$n={Private:2,Shared:3,Actioned:4},RF=e=>{const{state_id:t}=e,{plan_start:n,plan_end:r,duration_start:s,duration_end:i}=e,o=Z().format("YYYY-MM-DD"),l=n||s,c=r||i;switch(t){case $n.Private:return{planStatus:"Private",planProgress:null};case $n.Shared:return{planStatus:"Shared",planProgress:null};case $n.Actioned:return o<l?{planStatus:"Actioned",planProgress:"Pending"}:c<o?{planStatus:"Actioned",planProgress:"Completed"}:l<=o&&o<=c?{planStatus:"Actioned",planProgress:"In Progress"}:{planStatus:"Actioned",planProgress:null};default:return{planStatus:"Private",planProgress:null}}},zwe=e=>{switch(e){case $n.Private:case $n.Shared:case $n.Actioned:return e;default:return $n.Private}},Bwe=e=>{switch(e){case $n.Private:return"Private";case $n.Shared:return"Shared";case $n.Actioned:return"Actioned";default:return"unknown"}},Uwe=e=>e.map(t=>({AGG_NAMES:[String(t?.aggs||"")],AGG_VALUES:[String(t?.values||"")],
259CPM_EDITED:t?.cpm!==t?.cpm_edit,CURRENT_CPM:t?.cpm_edit?parseFloat(t.cpm_edit):0,CURRENT_IMPRESSIONS:t?.impressions?parseFloat(t.impressions):0,CURRENT_MAX_SCALAR:t?.spend_edit&&t?.max_spend_edit?t.max_spend_edit/t.spend_edit:0,CURRENT_MAX_SPEND:t?.max_spend_edit?parseFloat(t.max_spend_edit):0,CURRENT_MIN_SCALAR:t?.spend_edit&&t?.min_spend_edit?t.min_spend_edit/t.spend_edit:0,CURRENT_MIN_SPEND:t?.min_spend_edit?parseFloat(t.min_spend_edit):0,CURRENT_SPEND:t?.spend_edit&&!(t.min_spend_edit===0&&t.max_spend_edit===0)?parseFloat(t.spend_edit):0,EXCLUDE:parseFloat(t?.spend_edit)===0&&parseFloat(t?.min_spend_edit)===0&&parseFloat(t?.max_spend_edit)===0,ID:t.ids.toString(),IMPRESSIONS_EDITED:!0,LOCKED:t?.spend_edit===t?.min_spend_edit===t?.max_spend_edit,MEDIA_IDS:t.media_ids,MEDIA_ID_LEVEL_LOCK:t?.media_id_level_lock?t.media_id_level_lock==="TRUE"||t.media_id_level_lock==="True"||t.media_id_level_lock==="true":!1,ORIGINAL_CPM:t?.cpm?parseFloat(t.cpm):0,ORIGINAL_IMPRESSIONS:t?.impressions?parseFloat(t.impressions):0,ORIGINAL_MAX_SPEND:t?.max_spend?parseFloat(t.max_spend):0,ORIGINAL_MIN_SPEND:t?.min_spend?parseFloat(t.min_spend):0,ORIGINAL_SPEND:t?.spend?parseFloat(t.spend):0,SPEND_EDITED:t?.spend!==t?.spend_edit,TRPS:0})),Vwe=(e,t,n=0)=>Object.values(e).map(r=>({meta_id:n,active:r?.active?r.active==="T":r?.current_spend>0,media_id:r?.media_id?parseInt(r.media_id,10):0,engagement_nice_id:t||" ",cpm:r?.cpm||r?.original_cpm?parseFloat(r.cpm||r.original_cpm):0,cpm_edit:r?.cpm_edit||r?.current_cpm?parseFloat(r.cpm_edit||r.current_cpm):0,max_spend:r?.max_spend||r?.original_max_spend?parseFloat(r.max_spend||r.original_max_spend):0,max_spend_edit:r?.max_spend_edit||r?.current_max_spend?parseFloat(r.max_spend_edit||r.current_max_spend):0,min_spend:r?.min_spend||r?.original_min_spend?parseFloat(r.min_spend||r.original_min_spend):0,min_spend_edit:r?.min_spend_edit||r?.current_min_spend?parseFloat(r.min_spend_edit||r.current_min_spend):0,spend:r?.spend||r?.original_spend?parseFloat(r.spend||r.original_spend):0,spend_edit:r?.spend_edit||r?.current_spend?parseFloat(r.spend_edit||r.current_spend):0,impressions:r?.impressions||r?.current_impressions?parseFloat(r.impressions||r.current_impressions):0,override_impact:r?.override_impact?parseFloat(r.override_impact):null})),Wwe=(e,t=1e4)=>{const n=[];let r=0;for(;r<e.length/t;){const s=r*t,i=(r+1)*t;n.push(e.slice(s,i)),r+=1}return n},Hwe=()=>{const[e]=f3();return async(n,r)=>{const s=Wwe(n.map(i=>(i.meta_id=r,i)));if(await e({data:s[0],metaId:r,shouldDelete:!0}),s.length>1){const i=s.slice(1).map(o=>e({data:o,metaId:r,shouldDelete:!1}));await Promise.all(i)}}},qwe=()=>{const{userId:e}=gt(),{engagementNiceId:t}=pe(),[n]=WA(),[r]=h3(),s=Hwe(),[i]=HA(),[o]=qA(),l=async({aggData:u,createScenarioData:p,mediaData:h})=>{const f=await n(p);let g=null;const x=null;if("data"in f){const{id:b,version:y}=f.data;await r({metaId:b,constraints:u}),await s(h,b);const v=await i({engagementNiceId:t,metaId:b,version:y});return"data"in v&&(g=v.data.job_id),await o(g),{plannedJobId:g,plannedMetaId:b}}return{plannedJobId:g,plannedMetaId:x}},c=async({aggData:u,createScenarioData:p,mediaData:h,optId:f,plannedMetaId:g})=>{const x={...p,master_id:g,parent_id:g,optimization_type_id:2};f&&(x.id=f);const b=await n(x);let y=null;const v=null;if("data"in b){const{id:C,version:w}=b.data;await r({constraints:u,metaId:C}),await s(h,C);const S=await i({engagementNiceId:t,metaId:C,version:w});return"data"in S&&(y=S.data.job_id),await o(y),{optJobId:y,optimizedMetaId:C}}return{optJobId:y,optimizedMetaId:v}};return async({calcId:u=null,optId:p=null,aggregates:h,media:f,planData:g})=>{const{brandId:x,budget:b,clientId:y,conversionTargetValue:v,engagementId:C,name:w,objectives:S,selectedModels:E,startDate:k,endDate:j,modelReferenceStartDate:_,modelReferenceEndDate:D,planStart:M,planEnd:N}=g,O={active:!0,brand_id:Number(x),budget:Number(b),client_id:Number(y),conversion_target:Number(v),duration_start:k||_,duration_end:j||D,plan_start:M,plan_end:N,engagement_id:Number(C),identity_id:e,master_id:null,model_info:E,name:w,notes:"",objectives:S,optimization_type_id:1,parent_id:null,
259state_id:$n.Private,version:5};u&&(O.id=u);const R=Uwe(h),L=Vwe(f,t);let P=null,F=null,z=null,B=null;return{plannedJobId:P,plannedMetaId:F}=await l({aggData:R,createScenarioData:O,mediaData:L}),F&&({optJobId:z,optimizedMetaId:B}=await c({aggData:R,createScenarioData:O,mediaData:L,optId:p,plannedMetaId:F})),{plannedJobId:P,plannedMetaId:F,optJobId:z,optimizedMetaId:B,name:w}}},Gwe=e=>{const t=ct(),{message:n}=fu("Planner"),[r]=GA(),[s,i]=m.useState({}),o=m.useMemo(()=>e.every(c=>c in s)&&Object.values(s).every(({status:c})=>Object.values(c).every(d=>d==="Done")),[e,s]);m.useEffect(()=>{if(!n)return;const{metaId:c,plan:d}=n.data,{status:u}=d;e.length&&e.includes(c)&&i(p=>({...p,[c]:u}))},[n]);const l=m.useCallback(async()=>{const c=e.map(u=>r(u).then(({data:p})=>p?.status?[u,p.status]:null)),d=(await Promise.all(c)).filter(u=>u!==null);t()&&i(u=>{const p={...u};return d.forEach(([h,f])=>{p[h]=f}),p})},[t,r,e]);return kF(l,{skip:o}),s},sI=["FAILED","TIMED_OUT","ABORTED","NOTFOUND"],Ywe=e=>{const t=e.reduce((r,s)=>{const{plannedJobId:i,plannedMetaId:o,optJobId:l,optMetaId:c}=s,d=r;return o&&i&&(d[o]=i),c&&l&&(d[c]=l),d},{}),n=Object.keys(t).map(Number);return{plansMap:t,planIds:n}},Kwe=(e,t)=>{const{status:n}=e,{status:r}=t;return n.complete==="Done"&&r.complete==="Done"?85:n.post==="Done"&&r.post==="Done"?75:n.optimization==="Done"&&r.optimization==="Done"?65:n.process==="Done"&&r.process==="Done"?50:n.init==="Done"&&r.init==="Done"?35:null},Qwe=({dataOpt:e,dataPlanned:t,plan:n})=>{if(t&&e){const r=Object.values(t.status),s=Object.values(e.status);if(r.every(o=>o==="Done")&&s.every(o=>o==="Done"))return{...n,optimizationPercentageComplete:100};if(r.some(o=>o==="Failed"))return{...n,optError:t?.error_msg||"Unknown Error"};if(s.some(o=>o==="Failed"))return{...n,optError:e?.error_msg||"Unknown Error"};const i=Kwe(t,e);if(i)return{...n,optimizationPercentageComplete:i}}return n},Jwe=({optJobStatus:e,plan:t,plannedJobStatus:n})=>{if(n&&e){if(n==="SUCCEEDED"&&e==="SUCCEEDED")return{...t,superconductorPercentageComplete:100};if(sI.includes(n))return{...t,scError:`SuperConductor error: ${n.toLowerCase()}`};if(sI.includes(e))return{...t,scError:`SuperConductor error: ${e.toLowerCase()}`}}return t},Xwe=()=>{const[e,t]=m.useState([]),[n]=m3(),r=MF(e),{planIds:s,plansMap:i}=m.useMemo(()=>Ywe(e),[e]),o=Gwe(s),{data:l=null}=g3(i,{pollingInterval:15e3,skip:!s.length||r});return m.useEffect(()=>{e.length&&t(c=>c.map(d=>{const{optMetaId:u,plannedMetaId:p}=d,h=o[u||0],f=o[p||0];return Qwe({plan:d,dataOpt:h,dataPlanned:f})}))},[e.length,o,t]),m.useEffect(()=>{l&&t(c=>c.map(d=>{const{optMetaId:u,plannedMetaId:p}=d,h=l[u||0],f=l[p||0];return Jwe({plan:d,optJobStatus:h,plannedJobStatus:f})}))},[t,l]),m.useEffect(()=>{r&&n(null)},[r,n]),{planFilesData:e,setPlanFilesData:t}},Zwe=e=>{const{brand_id:{id:t},budget:n,client_id:{id:r},conversion_target:s,engagement_id:{id:i},levers:{aggregates:o,media:l},name:c,notes:d,objectives:u,selected_models:p,start_date:h,end_date:f,reference_start_date:g,reference_end_date:x,plan_start_date:b,plan_end_date:y}=e,v=Object.values(l),C=JSON.parse(u),w=JSON.parse(p);return{aggregates:o,media:v,planData:{brandId:t,budget:n,clientId:r,conversionTargetValue:s,engagementId:i,name:c,notes:d,objectives:C,selectedModels:w,startDate:h,endDate:f,modelReferenceStartDate:g,modelReferenceEndDate:x,planStart:b,planEnd:y}}},eSe=async({planFilesData:e,createPlanFromXlsx:t})=>{const n=e.map(i=>{const{parsedFile:o}=i;if(!o)return null;const l=Zwe(o);return t(l).then(c=>{const{plannedMetaId:d,optimizedMetaId:u,plannedJobId:p,optJobId:h}=c;return{...i,plannedJobId:p,plannedMetaId:d,optJobId:h,optMetaId:u,optimizationPercentageComplete:20}})});return(await Promise.all(n)).filter(i=>i!==null)},NF=({handleClose:e,trackCreatePlan:t})=>{const n=ct(),{planFilesData:r,setPlanFilesData:s}=Xwe(),i=qwe();return{onClose:()=>{e()},onCreatePlan:async()=>{t(),s(f=>f.map(g=>({...g,optimizationPercentageComplete:10})));const h=await eSe({createPlanFromXlsx:i,planFilesData:r});n()&&s(h)},onRemovePlan:h=>{s(f=>f.filter(({rawFile:g})=>g.name!==h.name))},onTransitionExit:()=>{s([])},onUploadComplete:async h=>{n()&&s(h.map(({parsedFile:f,rawFile:g})=>({...rI,parsedFile:f,rawFile:g,uploadPercentageComplete:100})))},onUploadStart:h=>{s(h.map(f=>({...rI,rawFile:f})))},planFilesData:r}};Z.extend(Nm);const $c="An unknown error has occurred.",iI=e=>{if(!e)return{externalErrorMsg:$c,hasError:!0,internalErrorMsg:$c,steps:null};const{error_msg:t,external_msg:n,internal_msg:r}=e,{complete:s,init:i,optimization:o,post:l,process:c}=e.status,d=[t,n,r].some(g=>g&&g!==" "),u=[s,i,o,l,c].some(g=>g==="Failed");if(!d&&!u)return{externalErrorMsg:"",hasError:!1,internalErrorMsg:"",steps:e.status};if(!d)return{externalErrorMsg:$c,hasError:!0,internalErrorMsg:$c,steps:e.status};const p=t&&t!==" "?t:$c;return{externalErrorMsg:r&&r!==" "?r:p,hasError:!0,internalErrorMsg:n&&n!==" "?n:p,steps:e.status}},tSe=({data:e,isInternalUser:t,userId:n,kpiScalarMap:r})=>{const s=t?e:e.filter(({identity_id:c,state_id:d})=>c===n||d===$n.Shared||d===$n.Actioned),i=new Map;
259return s.forEach(c=>{c.parent_id!==null&&i.set(c.parent_id,{metaId:c.id,status:c.status})}),s.filter(({parent_id:c})=>c===null).map(c=>{const{budget:d,conversion_target:u,created_at:p,id:h,identity_id:f,objective_name:g,plan_name:x,state_id:b,status:y,username:v}=c,C=u||d,w=u?"conversion":"budget",S=Z(p).format("ll"),E=Z(c.plan_start||c.duration_start).format("ll"),k=Z(c.plan_end||c.duration_end).format("ll"),j=`${E} - ${k}`,{planStatus:_}=RF(c),D=i.get(h),M=D?[h,D.metaId]:[h],N={[h]:iI(y)};D&&(N[D.metaId]=iI(D.status));const O=r.get(g)??null;return{budgetOrConversionValue:C,createdAt:p,creationDate:S,dateRange:j,id:h,identityId:f,ids:M,kpiScalar:O,objectiveName:g,optStatus:N,planName:x,stateId:b,stateName:_,type:w,username:v}}).sort((c,d)=>c.createdAt>d.createdAt?-1:1)},Ku=e=>Object.values(e.optStatus).some(({hasError:t})=>t),OF=()=>{const{engagementId:e}=pe(),{userIsInternal:t,userId:n}=gt(),{data:r,isFetching:s}=xC(e),{data:i=[],isFetching:o}=hu(e),l=m.useMemo(()=>{const d=new Map;return i.forEach(u=>{d.set(u.objective_name,u.kpi_scalar??null)}),d},[i]);return{plans:m.useMemo(()=>r?tSe({data:r,isInternalUser:t,userId:n,kpiScalarMap:l}):[],[t,r,n,l]),isLoading:s||o,isInternalUser:t,userId:n}},nSe={delete:"Delete Plan",duplicate:"Duplicate Plan",edit:"Edit Plan",status:"Status Change"},rSe=()=>{const{engagementNiceId:e}=pe(),t=en(),[n]=x3(),r=async i=>{const[o,l]=i,c=o?.toString()??"",d=l?.toString()??"";t("/planning/new-plan",{searchParams:{calcId:c,optId:d}})};return{editPlanData:r,duplicatePlanData:async({duplicateId:i})=>{const o=await n({engagementNiceId:e,metaId:i});if("error"in o)return{error:o.error};const{data:l}=o;if(!l)return{error:"duplicate"};const{calcId:c,optId:d}=l;return c&&d&&r([c,d]),{data:l}}}},PF=e=>{const t=en(),n=pr({actionMap:nSe,eventName:e}),{editPlanData:r,duplicatePlanData:s}=rSe(),[i]=YA(),[o]=KA(),l=h=>{n("edit",{metaIds:h}),r(h)},c=async h=>{const[f]=h;return f?(n("duplicate",{metaIds:h}),s({duplicateId:f})):{error:"duplicate"}},d=m.useCallback(()=>t("/planning/my-plans"),[t]),u=m.useCallback(async h=>{try{return n("delete",{metaIds:h}),{data:await i(h)}}catch(f){return{error:f}}finally{d()}},[i,d,n]),p=m.useCallback(async({metaIds:h,stateId:f})=>{const g=Bwe(f);n("status",{metaIds:h,planStatus:g}),await Promise.all(h.map(x=>{const b={columnName:"state_id",metaId:x,newValue:String(f)};return o(b)}))},[n,o]);return{handleDeletePlans:u,handleDuplicatePlan:c,handleEditPlan:l,handleUpdatePlanState:p}},sSe=()=>{const{plans:e,isLoading:t}=OF(),n=m.useMemo(()=>e.filter(r=>r.username!=="Orchestration User"||Ku(r)),[e]);return{isLoading:t,plans:n}},iSe={conversionType:"Conversion Type Change",dateRange:"Date Range Change",kpi:"KPI Change",targetAudience:"Target Audience Change",sentQuestion:"Widget Question Sent",newPlan:"Clicked Create New Plan",suggestionClick:"Clicked Suggestion Button"},aSe=()=>pr({actionMap:iSe,eventName:"overview"}),LF=m.createContext(null),Qu=()=>m.useContext(LF),oSe=["suggestion-skeleton-1","suggestion-skeleton-2","suggestion-skeleton-3"],lSe=()=>{const{chatExamples:e,chatExamplesLoading:t,handleClickSuggestion:n}=Qu(),{palette:r}=Re(),[s,i]=m.useState([]),o=m.useCallback(()=>{const l=e.examples.toSorted(()=>Math.random()-.5).slice(0,4);i(l)},[e.examples]);return m.useEffect(()=>{o()},[e.examples]),a.jsxs($,{direction:"row",alignItems:"center",gap:1,sx:{flexWrap:"wrap"},children:[t?oSe.map(l=>a.jsx(fe,{variant:"rounded",width:140,height:30,sx:{bgcolor:Wl(r.common.white,.15),borderRadius:999}},l)):s.map(l=>a.jsx(re,{onClick:()=>n({id:l.id,text:l.prompt}),sx:{bgcolor:Wl(r.common.white,.12),border:"1px solid",borderColor:Wl(r.common.white,.3),borderRadius:999,color:"common.white",fontSize:"0.8125rem",fontWeight:500,px:1.75,py:.5,textTransform:"none","&:hover":{bgcolor:Wl(r.common.white,.22),borderColor:Wl(r.common.white,.5)}},children:l.title},l.id||l.title)),!t&&e.examples.length>0&&a.jsx(Ie,{onClick:o,size:"small","aria-label":"Shuffle suggestions",sx:{color:"common.white",opacity:.8,"&:hover":{opacity:1}},children:a.jsx(wR,{fontSize:"small"})})]})},cSe={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:"1px"},dSe=({onClick:e,pinned:t=!1,subtitle:n,title:r})=>a.jsxs(He,{onClick:e,sx:{alignItems:"stretch",borderRadius:2,display:"flex",gap:1.5,minHeight:48,p:1.5,width:"100%","&:hover":{bgcolor:"background.brand.subtlest.hovered"}},children:[a.jsx(T,{"aria-hidden":!0,sx:{bgcolor:t?"primary.main":"transparent",borderRadius:1,flexShrink:0,width:3}}),a.jsxs($,{sx:{flex:1,gap:.25,minWidth:0},children:[a.jsxs($,{direction:"row",alignItems:"center",gap:.5,sx:{minWidth:0},children:[t&&a.jsxs(a.Fragment,{children:[a.jsx(T,{"aria-hidden":!0,
259component:"span",sx:{color:"primary.main",display:"flex",flexShrink:0},children:a.jsx(_U,{size:12})}),a.jsx(T,{component:"span",sx:cSe,children:"Pinned"})]}),a.jsx(be,{title:r,placement:"top",enterDelay:500,leaveDelay:200,children:a.jsx(I,{sx:{fontSize:"0.875rem",fontWeight:500,overflow:"hidden",textAlign:"left",textOverflow:"ellipsis",whiteSpace:"nowrap",width:"100%"},children:r})})]}),!!n&&a.jsx(I,{sx:{color:"text.secondary",fontSize:"0.75rem",textAlign:"left"},children:n})]})]}),aI=5,uSe=()=>{const{handleClickSession:e,metaData:t,metaDataLoading:n}=Qu(),[r,s]=m.useState(!1),i=m.useMemo(()=>[...t].sort((d,u)=>d.pinned!==u.pinned?d.pinned?-1:1:ch(u.updatedAt).valueOf()-ch(d.updatedAt).valueOf()),[t]),o=m.useMemo(()=>{const d=Z().startOf("month");return t.filter(({updatedAt:u})=>!ch(u).isBefore(d)).length},[t]),l=r?i:i.slice(0,aI),c=i.length>aI;return a.jsxs($,{sx:{maxHeight:480,minHeight:0,width:320},children:[a.jsx($,{sx:{px:1,py:.5},children:a.jsx(I,{variant:"subtitle2",children:"Recent conversations"})}),a.jsx($,{sx:{flex:1,minHeight:0,mt:1,overflow:"auto"},children:n?a.jsx(I,{variant:"body2",color:"text.secondary",sx:{px:1.5},children:"Loading..."}):i.length?l.map(d=>a.jsx(dSe,{onClick:()=>e(d),pinned:d.pinned,subtitle:CM(d.updatedAt),title:d.sessionTitle},d.sessionId)):a.jsx(I,{variant:"body2",color:"text.secondary",sx:{px:1.5},children:"No chats yet"})}),!n&&!!i.length&&a.jsxs($,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{borderTop:"1px solid",borderColor:"border.default",mt:1,pt:1,px:1},children:[a.jsxs(I,{variant:"caption",sx:{color:"text.secondary"},children:[o," ",o===1?"chat":"chats"," this month"]}),c&&a.jsx(re,{color:"primary",onClick:()=>s(d=>!d),size:"small",variant:"text",children:r?"Show less":"See all"})]})]})},pSe=e=>e.toLowerCase()==="high",hSe=({alert:e})=>{const[t,n]=m.useState(!1),{handleSendPrompt:r}=Qu(),{palette:s}=Re(),i=pSe(e.severity),o=i?s.error.main:s.warning.main,l=i?"HIGH":"WATCH";return a.jsxs(a.Fragment,{children:[a.jsx(He,{onClick:()=>n(!0),sx:{alignItems:"stretch",bgcolor:"background.paper",border:"1px solid",borderColor:"border.default",borderLeft:`4px solid ${o}`,borderRadius:1.5,display:"flex",flex:"1 1 0",minWidth:220,overflow:"hidden",p:2,textAlign:"left",transition:"all 0.2s ease-in-out","&:hover":{transform:"translateY(-2px)",boxShadow:2}},children:a.jsxs($,{sx:{flex:1,gap:1,minWidth:0},children:[a.jsxs($,{direction:"row",alignItems:"center",justifyContent:"space-between",children:[a.jsx(ut,{label:l,size:"small",sx:{bgcolor:i?"error.light":"warning.light",color:i?"error.dark":"warning.dark",fontSize:"0.6875rem",fontWeight:700,height:20,letterSpacing:"0.04em"}}),a.jsx(yl,{color:s.text.secondary,size:16})]}),a.jsx(I,{sx:{color:"text.primary",display:"-webkit-box",fontSize:"0.9375rem",fontWeight:600,lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",WebkitBoxOrient:"vertical",WebkitLineClamp:"2"},children:e.title}),a.jsxs(I,{sx:{color:"text.secondary",fontSize:"0.75rem"},children:[CM(e.createdAt)," · ",e.type]})]})}),a.jsx(mt,{title:e.title,body:a.jsx(T,{sx:{"& p":{mb:1.5},"& ul":{ml:2,mt:1}},children:a.jsx(ms,{markdownText:e.description})}),open:t,hideClose:!e.darwinPrompt,acceptLabel:e.darwinPrompt?"Ask Darwin For More":"Close",handleAccept:()=>{e.darwinPrompt&&r(e.darwinPrompt,{jsonContext:[{type:"alert",id:e.alertId}]}),n(!1)},handleClose:()=>n(!1)})]})},oI=3,fSe=["activity-skeleton-1","activity-skeleton-2","activity-skeleton-3"],mSe=()=>{const{alerts:e,alertsLoading:t}=Qu(),[n,r]=m.useState(!1),s=e.length>oI,i=n?e:e.slice(0,oI),o=e.length;return a.jsx(Ve,{children:a.jsx(Ue,{children:a.jsxs($,{sx:{gap:2.5},children:[a.jsxs($,{direction:"row",alignItems:"center",justifyContent:"space-between",children:[a.jsxs($,{direction:"row",alignItems:"center",gap:1.5,children:[a.jsx(T,{"aria-hidden":!0,sx:{alignItems:"center",bgcolor:"background.brand.subtle.default",borderRadius:1.5,color:"primary.main",display:"flex",height:36,justifyContent:"center",width:36},children:a.jsx(TU,{size:18})}),a.jsxs($,{children:[a.jsx(I,{sx:{color:"primary.main",fontSize:"0.6875rem",fontWeight:700,letterSpacing:"0.08em"},children:"RECENT ACTIVITY"}),t?a.jsx(fe,{variant:"text",width:220,height:28}):a.jsxs(I,{sx:{fontSize:"1.125rem",fontWeight:600},children:[o," ",o===1?"item needs":"items need"," your attention"]})]})]}),!t&&s&&a.jsx(re,{color:"primary",onClick:()=>r(l=>!l),size:"small",variant:"text",children:n?"Show less":"View all"})]}
259),a.jsx($,{direction:"row",sx:{display:"flex",flexWrap:"wrap",gap:2},children:t?fSe.map(l=>a.jsx(fe,{variant:"rounded",height:96,sx:{flex:"1 1 0",minWidth:220}},l)):i.map(l=>a.jsx(hSe,{alert:l},l.alertId))})]})})})},gSe="Instant insights, forecasts, and what-if analysis for every channel and segment.",xSe=()=>{const{handleSendPrompt:e,llmAssistantName:t,textBoxRef:n}=Qu(),r=t.toLowerCase()==="darwin"?`${t} AI`:t;return a.jsxs($,{sx:{gap:2.5},children:[a.jsx(ar,{authorized:"Chat.MevoDemo",children:a.jsx(mSe,{})}),a.jsxs($,{direction:"row",sx:{display:"flex",flexWrap:"wrap",gap:2.5,minHeight:340},children:[a.jsx(cA,{sparkles:!0,sx:{flex:"1 1 360px",minWidth:0},children:a.jsxs(Ue,{sx:{display:"flex",flexDirection:"column",gap:2,height:"100%",p:3,position:"relative"},children:[a.jsxs($,{direction:"row",alignItems:"center",gap:1.5,children:[a.jsx(ut,{label:r.toUpperCase(),size:"small",sx:{bgcolor:"darwinSurface.accent",color:"darwinSurface.text",fontSize:"0.6875rem",fontWeight:700,height:22,letterSpacing:"0.04em","& .MuiChip-label":{color:"darwinSurface.text"}}}),a.jsx(I,{sx:{fontSize:"0.8125rem",opacity:.85},children:"Your marketing copilot"}),a.jsxs($,{direction:"row",alignItems:"center",gap:.5,children:[a.jsx(T,{"aria-hidden":!0,sx:{bgcolor:"success.main",borderRadius:"50%",height:8,width:8}}),a.jsx(I,{sx:{fontSize:"0.8125rem",opacity:.85},children:"online"})]})]}),a.jsxs(T,{children:[a.jsxs(I,{sx:{fontSize:"2.5rem",fontWeight:700,lineHeight:1.15},children:["Ask anything about your"," ",a.jsx(T,{component:"span",sx:{fontStyle:"italic"},children:"performance."})]}),a.jsx(I,{sx:{mt:1,opacity:.85},children:gSe})]}),a.jsx(T,{sx:{mt:"auto","& .MuiInputBase-root":{backgroundColor:"darwinSurface.wash",borderRadius:"10px"},"& .MuiInputBase-input":{color:"darwinSurface.text"},"& .MuiInputBase-input::placeholder":{color:"darwinSurface.text",opacity:.7},"& .MuiIconButton-root":{backgroundColor:"darwinSurface.accent",opacity:1,"&:hover":{backgroundColor:"darwinSurface.accentHovered"}},"& .MuiIconButton-root svg":{color:"darwinSurface.icon"}},children:a.jsx(yR,{ref:n,hideDisclaimer:!0,handleSendQuestion:e,llmAssistantName:t})}),a.jsx(lSe,{})]})}),a.jsx(Ve,{sx:{display:"flex",flexShrink:0},children:a.jsx(Ue,{sx:{display:"flex",height:"100%",width:"100%"},children:a.jsx(uSe,{})})})]})]})},bSe=({alerts:e,alertsLoading:t,chatExamples:n,chatExamplesLoading:r,llmAssistantName:s,metaData:i,metaDataLoading:o})=>{const{loadSession:l,sendPrompt:c}=Fm(),{track:d}=wg(),u=m.useRef(null),p=m.useCallback(x=>{l({sessionId:x.sessionId})},[l]),h=m.useCallback((x,b)=>{c({prompt:x,options:b}),d("sentQuestion",{question:x}),u.current?.setText("")},[c,d]),f=m.useCallback(({id:x,text:b})=>{d("suggestionClick",{buttonId:x}),u.current?.setText(b),u.current?.focus()},[d,u]),g=m.useMemo(()=>({alerts:e,alertsLoading:t,chatExamples:n,chatExamplesLoading:r,handleClickSession:p,handleClickSuggestion:f,handleSendPrompt:h,llmAssistantName:s,metaData:i,metaDataLoading:o,textBoxRef:u}),[e,t,n,r,p,f,h,s,i,o,u]);return a.jsx(LF.Provider,{value:g,children:a.jsx(xSe,{})})},ySe=()=>{const{engagementId:e}=pe(),{llmAssistantName:t}=jt(),{data:n=[],isLoading:r}=vA(e,{skip:!e}),{data:s={examples:[],error:""},isLoading:i}=CA({engagement_id:e,include_inactive:!0}),{data:o=[],isLoading:l}=b3(e);return a.jsx(bSe,{alerts:o,alertsLoading:l,chatExamples:s,chatExamplesLoading:i,llmAssistantName:t,metaData:n,metaDataLoading:r})},xv={Shared:{background:"background.info.default",icon:IU},Actioned:{background:"primary.light",icon:Yv},Private:{background:"background.neutral.default",icon:rA}},vSe=({acceptDisabled:e,acceptText:t,body:n,onAccept:r,onClose:s,onTransitionExit:i,open:o})=>a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",open:o,TransitionProps:{onExited:i},children:[a.jsx(vt,{variant:"h6",sx:{pt:4},children:a.jsxs($,{direction:"row",justifyContent:"space-between",height:24,children:["Create from .xlsx",a.jsx(He,{"aria-label":"Close dialog","data-testid":"plan-file-upload:close:button",disableRipple:!0,onClick:s,sx:{color:"text.secondary"},children:a.jsx(Jt,{size:24})})]})}),a.jsx(Ct,{sx:{pb:2},children:n}),a.jsx(un,{sx:{py:2,px:3},children:a.jsxs($,{direction:"row",gap:1,height:36,children:[a.jsx(re,{color:"secondary","data-testid":"plan-file-upload:cancel:button",variant:"outlined",onClick:s,children:"Close"}),a.jsx(re,{"data-testid":"plan-file-upload:accept:button",disabled:e,variant:"contained",onClick:r,children:t})]})})]}),CSe=async e=>{try{const t=e.map(r=>Owe(r).then(s=>({parsedFile:s,rawFile:r})));return await Promise.all(t)}catch(t){return We(t),[]}},wSe=({createPlanClicked:e,planFileData:t})=>{const{name:n,size:r}=t.rawFile,s=$we({planFileData:t,createPlanClicked:e}),i=a.jsxs(a.Fragment,{children:[Pwe(r)," ⢠",Fwe({createPlanClicked:e,planFileData:t})]}),o=Pw(t),l=Lw(t),c=!o,d=e||l,u=Fw(t);let p=0;return e?p=l?100:t.optimizationPercentageComplete-5:p=o?100:0,{disabled:c,error:u,hideButton:d,isOptimizing:s,planName:n,progressValue:p,statusBarNode:i}},SSe=e=>{const t=Re(),{getRootProps:n,getInputProps:r,isDragActive:s}=fw({accept:{"text/*":[".xlsx"]},maxFiles:5,...e});return a.jsxs(T,{sx:{alignItems:"center",border:1,borderRadius:2.5,borderStyle:"dashed",borderColor:aA.alpha(t.palette.secondary.main,.2),display:"flex",flexWrap:"wrap",justifyContent:"center",outline:"none",py:4,px:3,...s&&{backgroundColor:"background.brand.subtlest.hovered"},"&:hover":{backgroundColor:"background.brand.subtlest.hovered",cursor:"pointer"}},...n(),children:[a.jsx("input",{...r()}),a.jsxs($,{alignItems:"center",direction:"row",sx:{py:3.75},gap:2,children:[a.jsx(as,{sx:{height:64,width:64,backgroundColor:"background.brand.subtle.default"},children:a.jsx(Mt,{sx:{color:"icon.brand.main"},children:a.jsx(tC,{})})}),a.jsxs($,{spacing:1,children:[a.jsxs(I,{sx:{"& span":{textDecoration:"underline"}},variant:"subtitle1",children:[a.jsx("span",{children:"Click to upload"})," or drag and drop"]}),a.jsx(I,{variant:"body2",color:"text.secondary",children:".xlsx file only"})]})]})]})},jSe=({disabled:e,error:t,hideButton:n,isOptimizing:r,onClick:s,planName:i,progressValue:o,statusBarNode:l})=>a.jsxs(T,{children:[a.jsxs($,{direction:"row",children:[a.jsx(Mt,{color:"primary",sx:{height:48,width:48},children:a.jsx(DU,{fileType:"spreadsheet"})}),a.jsxs($,{direction:"row",justifyContent:"space-between",width:"100%",sx:{pl:2},children:[a.jsxs($,{children:[a.jsx(I,{variant:"subtitle2",children:i}),a.jsx(I,{variant:"caption",color:"text.secondary",sx:r?{"&:after":{"@keyframes dots":{"0%":{content:'""'},"25%":{content:'"."'},"50%":{content:'".."'},"75%":{content:'"..."'},"100%":{content:'""'}},display:"inline-block",animation:"dots steps(1,end) 1s infinite",content:'""'}}:{},children:l})]}),a.jsx(be,{title:"Remove file",children:a.jsx("span",{style:{marginTop:10},children:!n&&a.jsx(He,{disabled:e,disableRipple:!0,onClick:s,sx:{color:e?"text.disabled":"text.secondary"},children:a.jsx(Jt,{size:19})})})})]})]}),a.jsx(lo,{color:t?"error":"primary",sx:{mx:8,mb:1},value:o,variant:"determinate"})]}),kSe=({disabled:e,onClick:t})=>a.jsxs(T,{sx:{alignItems:"center",backgroundColor:"background.brand.subtle.default",borderRadius:1,color:"primary.main",display:"flex",gap:1.5,py:1.5,px:2},children:[a.jsx(Si,{height:16,width:16}),a.jsxs(T,{children:[a.jsx(I,{color:"primary",variant:"body2",sx:{dis
259play:"flex",alignItems:"center",mb:1,height:40},children:"If you do not have an .xlsx plan file, click here to get a secure email containing a formatted plan file."}),a.jsx(re,{color:"secondary","data-testid":"plan-file-upload:send-email:button",variant:"outlined",disabled:e,onClick:t,children:"Send Email"})]})]}),ESe=({createPlanClicked:e,onRemovePlan:t,onSendEmail:n,onUpload:r,planFilesData:s,sendEmailDisabled:i,showSendEmail:o})=>a.jsxs(a.Fragment,{children:[o&&a.jsx(kSe,{disabled:i,onClick:n}),a.jsx(T,{sx:{mt:2},children:s.length>0?s.map(l=>{const{name:c}=l.rawFile;return a.jsx(jSe,{onClick:()=>{t(l.rawFile)},...wSe({createPlanClicked:e,planFileData:l})},c)}):a.jsx(SSe,{onDrop:r})})]}),FF=({onClose:e,onCreatePlan:t,onRemovePlan:n,onSendEmail:r=()=>{},onTransitionExit:s,onUploadComplete:i,onUploadStart:o,open:l,planFilesData:c,sendEmailDisabled:d=!1,showSendEmail:u=!1})=>{const[p,h]=m.useState(!1),f=MF(c),x=!Lwe(c)||p&&!f,b=()=>{e(),h(!1)},y=()=>{p&&f?e():p||(h(!0),t())},v=m.useCallback(async S=>{o(S);const E=await CSe(S);i(E)},[o,i]),C=()=>{s(),h(!1)},w=m.useMemo(()=>a.jsx(ESe,{createPlanClicked:p,onRemovePlan:n,onSendEmail:r,onUpload:v,planFilesData:c,sendEmailDisabled:d,showSendEmail:u}),[p,v,n,r,c,d,u]);return a.jsx(vSe,{acceptDisabled:x,acceptText:p?"Done":"Create Plan",body:w,onAccept:y,onClose:b,onTransitionExit:C,open:l})},_Se={label:"Private",value:$n.Private,description:"Changing the status to private will make this plan only viewable to you."},TSe={label:"Shared",value:$n.Shared,description:"Changing the status to shared will make this plan viewable to other users."},ISe={label:"Actioned",value:$n.Actioned,description:"Changing the status to actioned indicates that you are implementing this plan."},DSe=({includeActioned:e,includePrivate:t})=>{const n=[TSe];return t&&n.unshift(_Se),e&&n.push(ISe),n},ASe=e=>{const t=xv[e].icon;return a.jsxs($,{direction:"row",alignItems:"center",gap:.5,children:[a.jsx(t,{size:18}),a.jsx(I,{variant:"subtitle2",children:e})]})},MSe=({handleClose:e,handleUpdate:t,includeActioned:n,includePrivate:r,open:s,planStateId:i})=>{const[o,l]=m.useState(!1),c=zwe(i),[d,u]=m.useState(c),p=DSe({includeActioned:n,includePrivate:r}),h=()=>{l(!0),t(d)},f=x=>{u(Number(x.target.value))},g=()=>{l(!1),u(c)};return m.useEffect(()=>{u(c)},[c]),a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",open:s,TransitionProps:{onExited:g},children:[a.jsxs(vt,{component:"h6",sx:{pt:4},children:["Plan Status",a.jsx(Ie,{"aria-label":"close",disabled:o,onClick:e,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})})]}),a.jsx(Ct,{sx:{pb:3},children:a.jsx($,{direction:"row",gap:3,justifyContent:"space-between",paddingTop:3,children:a.jsx(Qe,{component:"fieldset",children:a.jsx(Wv,{"aria-label":"plan-access",name:"plan-access",value:d.toString(),onChange:f,children:p.map(x=>a.jsxs($,{direction:"column",justifyContent:"space-between",borderRadius:3,paddingX:2,paddingY:1.5,border:"1px solid",borderColor:d===x.value?"primary.main":"transparent",sx:b=>({backgroundColor:d===x.value?b.palette.mode==="dark"?"background.brand.subtle.default":"primary.light":"transparent"}),children:[a.jsx(sn,{value:x.value.toString(),control:a.jsx(Xa,{}),label:ASe(x.label),disabled:o},x.value),a.jsx(AD,{sx:{paddingLeft:4},children:x.description})]},x.value))})})})}),a.jsx(un,{sx:{px:3,py:2},children:a.jsxs($,{display:"flex",direction:"row",gap:1,height:36,children:[a.jsx(re,{color:"secondary",variant:"outlined",disabled:o,onClick:e,children:"Close"}),a.jsx(Dt,{disabled:i===d,loading:o,onClick:h,variant:"contained",sx:{py:.75,px:2},children:"Update"})]})})]})},lI={outlined:{color:"icon.secondary",border:"solid 1px",borderColor:"border.default",borderRadius:"8px"},text:{color:"icon.secondary",":hover":{backgroundColor:"background.brand.subtlest.hovered"}}},$F=({disabled:e=!1,disableDuplicate:t=!0,disableEdit:n=!0,handleEditPlan:r,handleDeletePlans:s,handleDuplicatePlan:i,handleUpdatePlanState:o,isInternalUser:l,row:c,userId:d,variant:u="outlined"})=>{const p=ct(),h=yn({authorized:"Planning.ActionPlan"}),[f,g]=m.useState(null),[x,b]=m.useState(!1),[y,v]=m.useState(!1),[C,w]=m.useState(!1),[S,E]=m.useState(!1),k=!!f,j=d===c.identityId,_=async L=>{await o({metaIds:c.ids,stateId:L}
259),p()&&b(!1)},D=()=>{r(c.ids)},M=async()=>{await i(c.ids),p()&&w(!1)},N=async()=>{v(!0)},O=()=>{E(!0)},R=()=>{w(!0)};return a.jsxs(a.Fragment,{children:[a.jsx(Ie,{"aria-label":`Plan actions for ${c.planName}`,"data-testid":`plan-list:actions-menu:${c.id}`,disabled:e,onClick:L=>{L.stopPropagation(),g(L.currentTarget)},sx:u==="outlined"?lI.outlined:lI.text,color:"secondary",children:a.jsx(vl,{size:u==="outlined"?16:24})}),a.jsxs(dr,{anchorEl:f,open:k,onClick:()=>{g(null)},onClose:()=>{g(null)},children:[a.jsx(Se,{"data-testid":`plan-list:actions:access:${c.id}`,onClick:()=>{g(null),b(!0)},children:"Access"}),a.jsx(ar,{authorized:"Planning.NewPlan",children:a.jsx(Se,{"data-testid":`plan-list:actions:edit:${c.id}`,disabled:n,onClick:O,children:"Edit"})}),a.jsx(ar,{authorized:"Planning.NewPlan",children:a.jsx(Se,{"data-testid":`plan-list:actions:duplicate:${c.id}`,disabled:t,onClick:R,children:"Duplicate"})}),a.jsx(Se,{"data-testid":`plan-list:actions:delete:${c.id}`,onClick:N,children:"Delete"})]}),a.jsx(MSe,{handleClose:()=>{b(!1)},handleUpdate:_,includeActioned:h,includePrivate:l||j,open:x,planStateId:c.stateId}),a.jsx(Cl,{bodyText:`Are you sure you want to delete "${c.planName}"? This will remove the plan and all its data.`,handleClose:()=>{v(!1)},handleDelete:async()=>{await s(c.ids)},open:y,title:"Delete plan?"}),a.jsx(mt,{bodyText:`Are you sure you want to edit "${c.planName}"?`,handleClose:()=>E(!1),handleAccept:()=>D(),acceptLabel:"Edit",open:S,title:"Edit plan?"}),a.jsx(mt,{bodyText:`Are you sure you want to duplicate "${c.planName}"?`,handleClose:()=>w(!1),handleAccept:()=>M(),acceptLabel:"Duplicate",open:C,title:"Duplicate plan?"})]})},RSe=125,zF=({children:e,dateRangeString:t,kpiString:n,loading:r=!1,modelDatesString:s})=>a.jsxs($,{sx:{rowGap:2},children:[a.jsxs(T,{sx:{display:"flex"},children:[a.jsx(I,{color:"text.secondary",component:"span",variant:"subtitle1",children:"KPI:Â "}),r?a.jsx(fe,{variant:"text",sx:{fontSize:16,width:150}}):a.jsx(be,{title:n.length>RSe?n.length:null,children:a.jsx(I,{component:"span",variant:"subtitle1",sx:{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:n})})]}),a.jsxs($,{direction:"row",justifyContent:"space-between",children:[a.jsxs(T,{sx:{display:"grid",gridTemplateAreas:"'icon dateRange' 'empty modelDates'",gridTemplateColumns:"auto 1fr",gridTemplateRows:"repeat(2, auto)",alignItems:"center",rowGap:1,columnGap:1.5},children:[a.jsx(au,{size:20,style:{gridArea:"icon"}}),r?a.jsxs(a.Fragment,{children:[a.jsx(fe,{variant:"text",sx:{gridArea:"dateRange",fontSize:14,width:180}}),a.jsx(fe,{variant:"text",sx:{gridArea:"modelDates",fontSize:12,width:240}})]}):a.jsxs(a.Fragment,{children:[a.jsx(I,{component:"div",sx:{gridArea:"dateRange"},children:t}),a.jsxs(I,{component:"div",color:"text.secondary",sx:{gridArea:"modelDates",letterSpacing:.5,fontSize:12},children:["Reference Dates: ",s]})]})]}),e]})]}),$w=({stateName:e})=>{if(!e)return null;const t=xv[e].icon,{background:n}=xv[e];return a.jsx(ut,{icon:a.jsx(t,{size:16}),label:e,sx:{backgroundColor:n,borderRadius:1.5,color:"text.default",height:24,px:.75,py:.375,".MuiChip-icon":{color:"text.default",m:0},".MuiChip-label":{pl:.5,pr:.25}}})},NSe={Completed:{background:"neutral.100"},"In Progress":{background:"primary.light"},Pending:{background:"info.light"}},OSe=({stateName:e})=>e?a.jsx(ut,{icon:a.jsx(AU,{size:16}),label:e,sx:{backgroundColor:NSe[e].background,borderRadius:1.5,height:24,px:.75,py:.375,".MuiChip-icon":{m:0},".MuiChip-label":{pl:.5,pr:.25}}}):null,cI={alignItems:"center",display:"flex",fontSize:"12px",fontWeight:"500"},BF=({type:e,value:t,kpiScalar:n})=>{const{engagementCurrency:r}=pe();if(!t)return null;const i=e==="conversion"?(e==="conversion"&&n?n:1)*t:t;return a.jsx(T,{alignItems:"center",display:"flex",flexDirection:"row",gap:1,children:e==="budget"?a.jsxs(a.Fragment,{children:[a.jsx(MU,{size:16}),a.jsx(T,{sx:cI,children:Ci(i,{options:{currency:r}})})]}):a.jsxs(a.Fragment,{children:[a.jsx(dA,{size:16}),a.jsx(T,{sx:cI,children:fg(i)})]})})},UF=({type:e})=>a.jsx(ut,{label:e,sx:{backgroundColor:e==="budget"?"background.info.default":"background.brand.subtle.default",borderRadius:1.5,height:24,px:.75,py:.375,".MuiChip-icon":{m:0},".MuiChip-label":{pl:.5,pr:.25},textTransform:"capitalize"}}),VF=m.createContext(null),In=()=>m.useContext(VF),WF=e=>{const t=e?.model_coverage.map(n=>Z(n)).map(n=>n.format("MMM D, YYYY"));return t?.length===2?t.join(" - "):"Unknown"},PSe=e=>e.map(({objective_id:t,objective_name:n,objective_nice_id:r,kpi_scalar:s})=>({id:t,name:n,niceId:r,kpiScalar:s??null})),zw=e=>{if(!e||e.length!==1)return 1;const t=e[0]?.kpiScalar;return t&&t>0?t:1},Bw=e=>e.reduce((t,{percent:n})=>t+n,0),dI=e=>{const t=e.map(i=>({...i,percent:Math.round(100/e.length)})),n=Bw(t);if(n===100)return t;const r=Math.round(Math.abs(n-100)),s=n<100?1:-1;return t.forEach((i,o)=>
259{if(o<r){const l=i.percent+s;i.percent=l}}),t},HF=e=>{const{calcId:t,loading:n,optId:r}=e;return!(t&&r)||n==="changingPivots"||n==="editing"||n==="initializing"||n==="querying"},LSe=(e,t)=>{const n={...e},{budget:r,conversion_target:s,metaIds:i,name:o,model_info:l,plan_start:c,plan_end:d,duration_start:u,duration_end:p,objectives:h}=t,[f,g]=i;n.budget=r,s&&(n.conversions=s),n.calcId=f,n.optId=g,n.planName=o,n.planType=s?"conversion":"budget",n.modelInfo=l;const x=c||u,b=d||p;return n.selectedDates=[Z(x),Z(b)],n.referenceDateRange=[Z(u),Z(p)],n.selectedKpis=h.map(y=>({id:y.id||0,name:y.name||"",percent:y.percent*100,niceId:y.nice_id||"",kpiScalar:null})),n},qF=e=>{const{activeStep:t,budget:n,calcId:r,conversions:s,loading:i,modelInfo:o,optId:l,planName:c,planType:d,selectedDates:u,selectedKpis:p,tableState:h}=e,[f,g]=u,{editActions:x}=h;switch(t){case 0:if(!c.length)return"Please enter a plan name";if(!p.length)return"Please select a KPI";if(Bw(p)!==100)return"Total weighting distribution must be 100%";break;case 1:if(!f||!g)return"Please select a date range";if(d==="budget"){if(n===0)return"Please enter a budget";if(!o)return"Model data loading..."}if(d==="conversion"){if(!o)return"Conversion data loading...";if(!s)return"Please enter a conversion target";if(o.min_conversion&&o.max_conversion&&(s<o.min_conversion||s>o.max_conversion))return"Conversion target must be within the valid range"}break;case 2:if(i==="initializing"||!(r&&l))return"Plan table initializing";if(i==="editing")return"Saving edited values";if(i==="querying"||i==="changingPivots")return"Loading data";if(x.size!==0)return"Please save your edits";if(e.planType==="budget"&&Math.abs(e.budget-e.allocatedBudget.current)>1)return"Allocated budget must match the target budget";break}return null},FSe=e=>{const{activeStep:t,calcId:n,loading:r,optId:s,tableState:i}=e,{editActions:o}=i,l=t===2&&!!n&&!!s&&r!=="optimizing";return{editIsDisabled:o.size===0||!!r,editIsVisible:l}},$Se=e=>{const{activeStep:t}=e,n=qF(e),{editIsDisabled:r,editIsVisible:s}=FSe(e);let i=oA,o="Close",l=uA,c="Next";switch(t){case 0:i=null,o="Close",c="Next: Plan Goals";break;case 1:c="Next: Set Plan",o="Back: Plan Details";break;case 2:o="Back: Plan Goals",l=null,c="Run Optimization";break}return{BackIcon:i,backText:o,editIsDisabled:r,editIsVisible:s,NextIcon:l,nextText:c,nextTooltip:n}},zSe=({handleTryExit:e=()=>{}})=>{const{createPlanMpTrack:t,dispatch:n,editing:r,editValues:s,handleClickSaveEdits:i,handleUpdateScenario:o,runOptimization:l,state:c}=In(),{activeStep:d,budget:u,calcId:p,conversions:h,loading:f,optId:g,planName:x,planType:b,referenceDatesUpdatedByUser:y,selectedDates:v,selectedKpis:C,tableState:w,userClickedValidRangeModal:S}=c,[E,k]=v,{pivotTableRef:j}=w,{BackIcon:_,backText:D,editIsDisabled:M,editIsVisible:N,NextIcon:O,nextText:R,nextTooltip:L}=$Se(c),P=r&&!!s&&!!p&&!!g,F=()=>{d<=0?e():(n({type:"decrementStep"}),t(d===2?"backPage2":"backPage1"))},z=m.useCallback(async()=>{P&&(x!==s.name&&await o({columnName:"name",metaIds:s.metaIds,newValue:x}),u!==s.budget&&await o({columnName:"budget",metaIds:s.metaIds,newValue:u}),h!==s.conversion_target&&await o({columnName:"conversion_target",metaIds:s.metaIds,newValue:h}))},[P,x,u,h,s,o]),B=V=>{V===0?t("nextPage2",{multiKpi:C.length!==1,selectedKpis:C}):t("nextPage3",{planType:b,amount:u||h,startDate:E?E.format("ll"):void 0,endDate:k?k.format("ll"):void 0,referenceDatesUpdatedByUser:y,userClickedValidRangeModal:S})},W=()=>{if(d<=1)n({type:"incrementStep"}),B(d);else if(d===2&&p&&g&&j?.current.state.selectedPivots){const{selectedPivots:V}=j.current.state;n({type:"incrementStep"}),n({type:"updateLoading",value:"optimizing"}),l({calcId:p,optId:g,pivots:V}),t("runop",{calcId:p,optId:g}),z()}},H=()=>{n({type:"tableState",subType:"resetEdits"})};return a.jsxs(un,{sx:{height:36,justifyContent:"space-between",mx:4,my:2,p:0},children:[d<2||r?a.jsx(re,{"data-testid":"create-plan:nav:back:button",disabled:!!f,color:"secondary",variant:"outlined",onClick:F,startIcon:_?a.jsx(_,{size:16}):void 0,children:D}):a.jsx("div",{}),a.jsxs($,{direction:"row",gap:2,children:[N?a.jsxs(a.Fragment,{children:[a.jsx(be,{title:"Undo edits since last save.",children:a.jsx("span",{children:a.jsx(re,{color:"error","data-testid":"create-plan:nav:undo:button",disabled:M,onClick:H,variant:"contained",children:"Undo Current Changes"})})}),a.jsx(re,{"data-testid":"create-plan:nav:save:button",disabled:M,onClick:i,variant:"contained",children:"Save Changes"})]}):null,a.jsx(be,{placement:"top",title:L,children:a.jsx("span",{children:a.jsx(Dt,{"data-testid":"create-plan:nav:next:button",disabled:!!L,endIcon:O?a.jsx(O,{size:16}):void 0,loading:f==="optimizing",onClick:W,variant:"contained",children:R})})})]})]})},bv=rt(aB)(({activeStep:e,theme:t})=>{const n=t.palette.neutral[200],{light:r}=t.palette.primary,s=`1px dashed ${n}`,i=`1px solid ${r}`;return{".MuiStep-root:nth-of-type(odd)":{flexGrow:0,".MuiStepLabel-labelContainer":{width:78}},".MuiStep-root:nth-of-type(2)":{"> .MuiStepConnector-root":{left:20,right:317},".MuiStepConnector-line":{border:e!==0?i:s}},".MuiStep-root:nth-last-of-type(1)":{"> .MuiStepConnector-root":{left:-207,right:98},".MuiStepConnector-line":{border:e===2?i:s}}}});bv.defaultProps={...bv.defaultProps,alternativeLabel:!0};const BSe=["Plan Details","Plan Goals","Set Plan"],USe=({activeStep:e})=>a.jsx(bv,{activeStep:e,children:BSe.map((t,n)=>a.jsx(oB,{sx:{p:0},children:a.jsx(lB,{sx:{".MuiStepLabel-label":{color:e===n?"text.primary":"text.disabled",mt:1.5}},children:t})},t))}),uI=({leftDescription:e,leftValue:t,rightDescription:n,rightValue:r})=>a.jsxs($,{sx:{flexDirection:"row",height:36,width:"fit-content",gap:2,p:2,borderRadius:1.5,alignItems:"center",backgroundColor:"surface.tertiary"},children:[a.jsxs(T,{children:[a.jsxs(I,{component:"span",sx:{color:"text.secondary"},children:[e,":"," "]}),a.jsx(I,{component:"span",children:t})]}),!!n&&!!r&&a.jsxs(a.Fragment,{children:[a.jsx(T,{sx:{height:"100%",py:1.25,width:0,borderRight:"1px solid",borderColor:"text.disabled"}}),a.jsxs(T,{children:[a.jsxs(I,{component:"span",sx:{color:"text.secondary"},children:[n,":"," "]}),a.jsx(I,{component:"span",children:r})]})]})]}),VSe=()=>{const{createPlanExport:e,createPlanMpTrack:t,state:n}=In(),{calcId:r,optId:s,tableState:i}=n,{pivotTableRef:o}=i,[l,c]=m.useState(!1),[d,u]=m.useState(!1),p=qF(n),h=()=>
259{if(r!==null&&s!==null&&o){const{selectedPivots:C}=o.current.state;e({calcId:r,optId:s,selectedPivots:C}),t("email"),u(!0)}},f=()=>{c(!0)},g=()=>{c(!1)},x=()=>{t("batch")},{onClose:b,...y}=NF({handleClose:g,trackCreatePlan:x}),v=()=>{b(),u(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(be,{placement:"top",title:p,children:a.jsx("span",{children:a.jsx(re,{color:"secondary","data-testid":"create-plan:step3:import-export:button",variant:"outlined",onClick:f,disabled:!!p,startIcon:a.jsx(RU,{}),endIcon:a.jsx(nC,{color:"disabled"}),children:"Import / Export .xlsx"})})}),a.jsx(FF,{...y,onClose:v,onSendEmail:h,open:l,sendEmailDisabled:d,showSendEmail:!0})]})},WSe=({kpi:e})=>{const{dispatch:t}=In(),{id:n,name:r,percent:s}=e,i=({floatValue:o})=>{t({type:"updateKpiPercent",value:{id:n,nextPercent:o||0}})};return a.jsxs($,{direction:"row",justifyContent:"space-between",gap:3,children:[a.jsxs(T,{sx:{width:"100%",border:"1px solid",borderColor:"neutral.100",borderRadius:1.5,py:"5px",px:"15px",display:"flex",justifyContent:"space-between",height:48},children:[a.jsx(I,{variant:"body2",sx:{alignSelf:"center",lineHeight:"22px"},children:r}),a.jsx(Ie,{disableRipple:!1,onClick:()=>{t({type:"removeSelectedKpi",value:n})},sx:{color:"text.primary"},children:a.jsx(Jt,{})})]}),a.jsx(iu,{allowLeadingZeros:!1,allowNegative:!1,customInput:Tl,decimalScale:0,onValueChange:i,suffix:"%",value:s||"",label:"Distribution ratio",sx:{width:210}})]},n)},HSe=()=>a.jsxs($,{sx:{mt:1},spacing:3.5,children:[a.jsx(fe,{height:70,variant:"rounded",width:"100%"}),a.jsxs($,{spacing:4,direction:"row",children:[a.jsx(fe,{height:50,variant:"rounded",width:"50%"}),a.jsx(fe,{height:50,variant:"rounded",width:"50%"})]})]}),qSe=()=>a.jsx(lA,{size:16}),GSe=()=>{const{state:e}=In(),t=Bw(e.selectedKpis),n=t!==100,r=a.jsx(ut,{icon:n?a.jsx(qSe,{}):void 0,label:`Total Distribution: ${t}%`,color:n?"error":"success",sx:{borderRadius:.5,height:"100%",px:.5,py:.375,".MuiChip-icon":{margin:0},".MuiChip-label":{height:18,letterSpacing:"0.16px",px:.75}}});return n?a.jsx(be,{placement:"top",title:"Total weighting distribution must be 100%",children:r}):r},YSe=({event:e,kpiOptions:t})=>{const{value:n}=e.target;if(!(Array.isArray(n)&&n.every(o=>typeof o=="number")))return null;const r=n;return t.filter(({id:o})=>r.includes(o)).map(o=>({...o,percent:0}))},KSe=()=>{const{dispatch:e,editing:t,editInfoLoading:n,engagementName:r,kpiOptions:s,state:i}=In(),{loading:o,planName:l,selectedKpis:c}=i,d=c.map(({id:f})=>f),u=()=>c.map(({name:f})=>f).sort().join(", "),p=f=>{e({type:"updatePlanName",value:f.target.value})},h=async f=>{const g=YSe({event:f,kpiOptions:s});g&&e({type:"updateSelectedKpis",value:g})};return m.useEffect(()=>{s.length===1&&e({type:"updateSelectedKpis",value:s.map(f=>({...f,percent:0}))})},[e,s]),n?a.jsx(HSe,{}):a.jsxs($,{children:[a.jsxs($,{direction:"row",justifyContent:"space-between",children:[a.jsx(Xt,{title:"Plan Details"}),r?a.jsxs(T,{children:[a.jsx(I,{component:"span",sx:{color:"text.disabled"},variant:"subtitle2",children:"Plan for "}),a.jsx(I,{component:"span",variant:"subtitle2",children:r})]}):null]}),a.jsx(I,{variant:"body2",sx:{pt:1,pb:3,color:"text.secondary"},children:"Optimize your spend recommendations to maximize conversions for a user-specified scenario. Please provide the required details below."}),a.jsxs($,{direction:"row",gap:3,children:[a.jsx(Tl,{fullWidth:!0,inputProps:{"data-testid":"create-plan:step1:plan-name:input"},label:"Plan Name",onChange:p,value:l}),a.jsxs(RC,{fullWidth:!0,disabled:t,children:[a.jsx(wt,{children:"KPIs"}),a.jsx(tt,{"data-testid":"create-plan:step1:kpis:select",disabled:o==="kpis"||s.length<=1||t,multiple:!0,onChange:h,renderValue:u,value:d,children:s.map(({id:f,name:g})=>a.jsxs(Wb,{value:f,children:[a.jsx(et,{checked:!!c.find(({id:x})=>x===f),disableRipple:!0}),a.jsx(Kt,{primary:g})]},f))})]})]}),c.length>1?a.jsxs(a.Fragment,{children:[a.jsx(St,{sx:{mt:6,mb:4}}),a.jsxs($,{direction:"row",height:24,justifyContent:"space-between",children:[a.jsx(I,{variant:"subtitle1",children:"Select KPIs Weighting"}),a.jsx(GSe,{})]}),a.jsxs(I,{variant:"body2",sx:{color:"text.secondary",lineHeight:"22px",mt:1,mb:3},children:["Weighting allows you to distribute your KPIs by a relative percentage value.",a.jsx("br",{}),"Total distribution should be 100% to move forward."]}),a.jsx($,{gap:2,children:c.map(f=>a.jsx(WSe,{kpi:f},f.id))})]}):null]})},QSe=({disabled:e,handleChange:t,isCurrency:n,isError:r,label:s,value:i})=>a.jsx(iu,{allowLeadingZeros:!1,allowNegative:!1,customInput:Tl,decimalScale:0,onValueChange:t,thous
259andSeparator:",",value:i,disabled:e,error:r,fullWidth:!0,InputProps:n?{startAdornment:a.jsx(Bn,{position:"start",sx:{mr:0},children:a.jsx(Dl,{sx:{fontSize:14}})})}:void 0,label:s});var Ih={exports:{}},JSe=Ih.exports,pI;function XSe(){return pI||(pI=1,(function(e,t){(function(n,r){e.exports=r()})(JSe,(function(){return function(n,r){r.prototype.isLeapYear=function(){return this.$y%4==0&&this.$y%100!=0||this.$y%400==0}}}))})(Ih)),Ih.exports}var ZSe=XSe();const eje=dt(ZSe);Z.extend(eje);const GF=e=>zw(e.selectedKpis),tje=e=>{const{budget:t,conversions:n,loading:r,planType:s,selectedDates:i}=e,[o,l]=i;if(s==="budget")return{disabled:!1,label:"Budget",value:t};if(r==="dateRange")return{disabled:!0,label:"Loading available date range",value:""};if(r==="modelInfo")return{disabled:!0,label:"Conversion data loading...",value:""};if(!o||!l)return{disabled:!0,label:"Please select a date range",value:""};const c=GF(e);return{disabled:!1,label:"Conversions",value:n*c}},nje=({budget:e,dateRange:t,locale:n,currency:r})=>{const[s,i]=t;if(!s||!i)return"0";const o=Math.abs(i.diff(s,"days")),l=i.isLeapYear()?366:365,c=e*l/o;return new Intl.NumberFormat(n,{style:"currency",currency:r,minimumFractionDigits:0,maximumFractionDigits:2}).format(c)},rje=(e,t,n)=>{const{budget:r,modelInfo:s,planType:i,selectedDates:o}=e,[l,c]=o;if(i==="budget"&&l&&c)return{prefaceText:"Annualized Budget:",showHelperText:!0,valueText:nje({budget:r,dateRange:o,locale:t,currency:n})};if(i==="conversion"&&s&&s.min_conversion&&s.max_conversion){const d=GF(e),u=d*s.min_conversion,p=d*s.max_conversion,h=new Intl.NumberFormat(t).format(u),f=new Intl.NumberFormat(t).format(p);return{prefaceText:"Valid range:",showHelperText:!0,valueText:`${h} - ${f}`}}return{prefaceText:"",showHelperText:!1,valueText:""}},sje=e=>{const{conversions:t,modelInfo:n,planType:r}=e;return r!=="conversion"||!n||!n.min_conversion||!n.max_conversion||t===0?!1:t<n.min_conversion||t>n.max_conversion},ije=({editing:e,hasMultipleKpis:t})=>e?"Plan type changes are not available while editing a plan":t?"Conversion target not available for multi-KPI plans":"",aje=a.jsxs($,{rowGap:2,children:[a.jsx(I,{children:"Valid range displays the number of conversions that may be reasonably achieved given historical levels of the KPI data."}),a.jsx(I,{children:"The intended use is for budget minimization. The optimization engine will identify the most efficient allocation of spend required to reach the KPI objective you choose within this range."}),a.jsx(I,{children:"For example, if you expect lower levels of demand in your planning period, you may opt to enter a value towards the lower limit. Conversely under more optimistic assumptions, you may instead set a target closer to the upper limit."})]}),oje=()=>{const{dispatch:e,locale:t,state:n}=In(),{engagementCurrency:r}=pe(),{planType:s}=n,{prefaceText:i,showHelperText:o,valueText:l}=rje(n,t,r),[c,d]=m.useState(!1),u=()=>{e({type:"validRangeModal",value:!0}),d(!0)},p=()=>{d(!1)};return o?a.jsxs($,{direction:"row",sx:{pl:1.5,pt:"3px",height:20,alignItems:"center",lineHeight:"20px"},children:[a.jsxs(I,{component:"span",variant:"caption",sx:{color:"text.secondary",fontWeight:400,letterSpacing:.4,lineHeight:"inherit"},children:[i,"Â "]}),a.jsx(I,{component:"span",variant:"caption",sx:{letterSpacing:.5,lineHeight:"inherit"},children:l}),s==="conversion"&&a.jsx(re,{onClick:u,variant:"text",sx:{ml:1,p:.5,fontSize:12,fontWeight:400,lineHeight:"inherit"},children:"What Is Valid Range?"}),a.jsx(mt,{acceptLabel:"Ok",body:aje,handleAccept:p,handleClose:p,hideClose:!0,open:c,title:"What Is Valid Range?"})]}):null},lje=["budget","conversion"],cje=()=>{const{dispatch:e,editing:t,state:n}=In(),{planType:r,selectedKpis:s}=n,{disabled:i,label:o,value:l}=tje(n),c=sje(n),d=s.length>1,u=ije({editing:t,hasMultipleKpis:d}),p=(f,g)=>{typeof g=="string"&&Tn(lje,g)&&e({type:"updatePlanType",value:g})},h=({floatValue:f})=>{if(r==="budget")e({type:"updateBudget",value:f||0});else{const g=zw(s),x=(f??0)/g;e({type:"updateConversions",value:x})}};return m.useEffect(()=>{d&&r==="conversion"&&e({type:"updatePlanType",value:"budget"})},[e,d,r]),a.jsxs(a.Fragment,{children:[a.jsxs($,{direction:"row",pb:1,children:[a.jsx(QSe,{disabled:i,handleChange:h,isCurrency:r==="budget",isError:c,label:o,value:l}),a.jsx(be,{title:u,children:a.jsxs(ml,{color:"primary",disabled:!!u,exclusive:!0,onChange:p,sx:{pl:2},value:r,children:[a.jsx(yi,{sx:{width:105},value:"budget",children:"Budget"}),a.jsx(yi,{sx:{width:105},value:"conversion",children:"Conversion"})]})})]}),a.jsx(oje,{})]})};var zc={},hI;function dje(){if(hI)return zc;hI=1;var e=Pt();Object.defineProperty(zc,"__esModule",{value:!0}),zc.default=void 0;var t=e(Lt()),n=Ot();return zc.default=(0,t.default)((0,n.jsx)("path",{d:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75z"}),"Edit"),zc}var uje=dje();const Ju=dt(uje),fI=rt($)(({theme:e})=>({alignItems:"center",backgroundColor:e.palette.surface.tertiary,borderRadius:"6px",flexDirection:"row",height:"36px",lineHeight:"20px",padding:"8px 16px"})),Dh=({sx:e,...t})=>a.jsx(I,{component:"span",variant:"caption",sx:{color:"text.secondary",fontWeight:600,fontSize:"12px",letterSpacing:.4,lineHeight:"inherit",...e},...t}),pje=({sx:e,...t})=>a.jsx(Dh,{sx:{color:"text.primary",fontWeight:500,letterSpacing:"normal",...e},...t}),yv=(e,t,n)=>e&&t&&n?e.subtract(1,"year")>t||e.subtract(1,"year").isBefore(n):!1,hje=(e,t,n)=>{const{modelInfo:r,selectedDates:s,dateRange:i}=e,[o,l]=s,c=WF(r),d=()=>t?"Additional options currently unavailable because you are editing":yv(o,Z(r?.model_coverage[1]),i[0])?"Additional options currently unavailable because earlier historical data does not exist":"";return o===null&&l===null?null:o!==null&&l!==null&&r===null?a.jsxs(fI,{sx:{columnGap:1},children:[a.jsx(Ze,{}),a.jsx(Dh,{children:"Reference period dates are loading..."})]}):r!==null?a.jsxs(fI,{sx:{justifyContent:"space-between",width:"100%"},children:[a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(Dh,{sx:{pr:.25},children:"Reference period for planning:"}),a.jsx(pje,{children:c}),a.jsx(be,{title:a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("b",{children:"Reference Dates:"})," The historical reference period you are using to build or analyze a scenario. These dates serve as the historical foundation for understanding trends, patterns, and insights that inform your decision-making process. Essentially, reference dates represent the timeframe from which your data is drawn to create a scenario."]}),a.jsx("br",{}),a.jsxs("div",{children:[a.jsx("b",{children:"Planning Dates:"})," The dates you are actively planning for in your strategies and actions. These are the peri
259ods for which you are formulating plans, campaigns, or initiatives based on the insights derived from the reference dates period. Planning dates represent the time frame during which you aim to implement your plan. Planning dates will enable tracking of scenario performance."]})]}),placement:"bottom",children:a.jsx(jw,{fontSize:"small",sx:{color:"text.secondary",pl:.5}})})]}),a.jsx(be,{title:d(),children:a.jsx(T,{children:a.jsxs(Ie,{sx:{padding:0,color:"text.primary",display:"flex",alignItems:"center","&:active":{backgroundColor:"common.white"},"&:hover":{backgroundColor:"common.white"}},id:"edit-button",disabled:t||yv(o,Z(r.model_coverage[1]),i[0]),onClick:()=>{n()},children:[a.jsx(Ju,{sx:{height:"16px"}}),a.jsx(Dh,{children:"Change"})]})})})]}):""},fje=({open:e,onClickConfirm:t})=>{const{state:n,dispatch:r}=In(),{modelInfo:s,selectedDates:i,dateRange:o}=n,[l,c]=i,[d,u]=m.useState("0"),[p,h]=m.useState("0"),f=b=>{h(b.target.value)};m.useEffect(()=>{h("0")},[i]);const g=()=>t(),x=()=>{if(d===p){g();return}switch(u(p),p){case"0":r({type:"updateReferenceDateRange",value:{referenceDateRange:[l,c],referenceDatesUpdatedByUser:!0}});break;case"1":l&&c&&r({type:"updateReferenceDateRange",value:{referenceDateRange:[l.subtract(1,"year"),c.subtract(1,"year")],referenceDatesUpdatedByUser:!0}});break}g()};return a.jsx(mt,{open:e,body:a.jsx(Qe,{component:"fieldset",children:a.jsxs(Wv,{"aria-label":"options",name:"row-radio-buttons-group",value:p,onChange:f,sx:{ml:"24px",mt:"16px"},children:[a.jsx(sn,{value:0,control:a.jsx(Xa,{}),label:"Most Recent Reference Period Available"}),a.jsx(sn,{value:1,control:a.jsx(Xa,{}),disabled:s?yv(l,Z(s?.model_coverage[1]),o[0]):!1,label:"Same Period Last Year"})]})}),acceptLabel:"Save",handleAccept:x,handleClose:g,title:"Select Historical Reference Period"})},mje=({onClickConfirm:e})=>{const{state:t,editing:n}=In(),r=hje(t,n,e);return a.jsx(T,{sx:{m:"12px 0px",pt:"3px"},children:r})},gje=()=>{const{dispatch:e,editing:t,state:n}=In(),{dateRange:r,loading:s,selectedDates:i}=n,[o,l]=i,[c,d]=r,u=(t?o:c)??void 0,p=(t?l:d)??void 0,[h,f]=m.useState(!1),g=()=>{f(!1)},x=()=>{f(!0)},b=async y=>{e({type:"updateSelectedDates",value:y}),e({type:"updateReferenceDateRange",value:{referenceDateRange:y,referenceDatesUpdatedByUser:!1}})};return a.jsxs(a.Fragment,{children:[a.jsx(ts,{disabled:t,loading:s==="dateRange",maxDate:p,minDate:u,shortcutItems:[],setValue:b,value:i}),a.jsx(mje,{onClickConfirm:x}),a.jsx(fje,{open:h,onClickConfirm:g})]})},xje=()=>a.jsxs($,{children:[a.jsx(Xt,{title:"Plan Goals"}),a.jsx(I,{variant:"body2",sx:{pt:1,pb:3,color:"text.secondary"},children:"Plan goals allow you to set your budget or conversion goal and the date range for the plan. Please provide these details below."}),a.jsx(gje,{}),a.jsx(St,{sx:{mb:4}}),a.jsx(I,{variant:"subtitle1",children:"Set Plan Goal"}),a.jsx(I,{variant:"body2",sx:{color:"text.secondary",pt:1,pb:3}
259,children:"Plan goal is defined by Budget or Conversions, please select and provide your goal below."}),a.jsx(cje,{})]}),bje=({checked:e,disabled:t,handleSwitch:n,hide:r=!1})=>r?null:a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(Dn,{checked:e,"data-testid":"create-plan:step3:autoscale:switch",disabled:t,inputProps:{"aria-label":"Autoscale"},onChange:n}),a.jsx(be,{placement:"top",title:"Automatically reallocate spend to ensure the collective media spend aligns with the total media budget",children:a.jsx(I,{sx:{color:"text.secondary"},component:"span",children:"Autoscale"})})]}),Fp={CPM:"Baseline CPM for the media line item (upon initial load). This field can be modified by the user to reflect anticipated changes in future media costs.",INITIAL_PLAN_SPEND:"Derived from Brand/Spend combination's previous baseline CPM, multiplied by the number of days included in the forward-looking forecast. This field is a run rate.",MAX_SPEND:"An input that specifies a maximum spend or conservative exploratory limit associated with a media line item.",MIN_SPEND:"An input that specifies a minimum or obligatory spend associated with a media line item."},$p=({params:e})=>{const{id:t,field:n,value:r=0}=e,{budget:s,planType:i}=In().state,{setEditCellValue:o}=CC().current,l=new Intl.NumberFormat("en",{maximumFractionDigits:3}).format(r),c=({floatValue:u})=>{u!==void 0&&o({id:t,field:n,value:u})},d=({floatValue:u})=>u&&n==="current_spend"&&i==="budget"?u<=s:!0;return a.jsx(iu,{allowLeadingZeros:!1,allowNegative:!1,customInput:De,isAllowed:d,onValueChange:c,thousandSeparator:",",value:l,sx:{".MuiInputBase-root":{height:40,py:1},".MuiInputBase-input":{p:1,pl:0,textAlign:"right"}},inputProps:{autoFocus:!0},InputProps:{startAdornment:a.jsx(Bn,{position:"start",sx:{m:"0px !important"},children:a.jsx($D,{sx:{color:"text.disabled"}})}),sx:{pl:.5,pr:1}}})};function YF(e,t){return{...e,current_max_scalar:1,current_max_spend:e.current_spend,current_min_scalar:1,current_min_spend:e.current_spend,locked:!0,media_id_level_lock:t,spend_edited:!0}}function KF(e){return{...e,current_max_scalar:2,current_max_spend:2*e.current_spend,current_min_scalar:.5,current_min_spend:.5*e.current_spend,locked:!1,media_id_level_lock:!1,spend_edited:e.current_spend!==e.original_spend}}function Uw(e){return{...e,current_impressions:0,current_max_spend:0,current_min_spend:0,current_spend:0,exclude:!0,spend_edited:!0}}function Ah(e){return{...e,current_impressions:e.original_impressions,current_max_spend:e.original_max_spend,current_min_spend:e.original_min_spend,current_spend:e.original_spend,exclude:!1,locked:!1,media_id_level_lock:!1,spend_edited:!1}}function yje(e){const t=e.value;if(t===0)return Uw(e.row);const n=t*e.row.current_min_scalar,r=t*e.row.current_max_scalar,s=t*1e3/e.row.current_cpm,i=t!==e.row.original_spend,o=s!==e.row.original_impressions;return{...e.row,current_spend:t,current_min_spend:n,current_max_spend:r,current_impressions:s,spend_edited:i,impressions_edited:o}}function vje(e){const t=e.value,r=e.row.current_spend*1e3/t,s=r!==e.row.original_impressions,i=t!==e.row.original_cpm;return{...e.row,current_cpm:t,current_impressions:r,impressions_edited:s,cpm_edited:i}}function Cje(e){const t=e.value,r=e.row.current_spend===0||e.row.current_spend===null?.5:t/e.row.current_spend;return{...e.row,current_min_spend:t,current_min_scalar:r}}function wje(e){const t=e.value,r=e.row.current_spend===0||e.row.current_spend===null?2:t/e.row.current_spend;return{...e.row,current_max_spend:t,current_max_scalar:r}}const Sje=({row:e})=>{const{updateRows:t}=CC().current,{handleEditRows:n}=In(),{exclude:r}=e,s=()=>{const i=r?Ah(e):Uw(e);t([{...i}]),n([{...i}])};return a.jsx(be,{title:`${r?"Include":"Exclude"} media`,children:a.jsx(Dn,{checked:!r,onChange:s})})},jje=["typeAndPlacement","typeOnly"],kje=({pivotOptions:e,selectedPivots:t})=>{const n=t.map(i=>e.find(({value:l})=>l===i)?.label??Pr(i)).sort((i,o)=>e.findIndex(l=>l.label===i)-e.findIndex(l=>l.label===o)),r=n.length===1?n[0]:n.map((i,o)=>o===n.length-1?`and ${i}`:i).join(", "),s=n.length===1?`${n[0]} and Placement`:`${n.join(", ")}, and Placement`;return{aggsLabel:r,aggsAndPlacementLabel:s}},QF=({open:e,onClose:t,onConfirm:n})=>{const{pivotOptions:r,state:s}=In(),{selectedPivots:i}=s.tableState.pivotTableRef?.current.state||{selectedPivots:[]},[o,l]=m.useState(""),{aggsAndPlacementLabel:c,aggsLabel:d}=kje({pivotOptions:r,selectedPivots:i}),u=()=>{t(),l("")},p=()=>{n(o),l("")},h=f=>{const{value:g}=f.target;l(Tn(jje,g)?g:"")};return a.jsxs(yt,{fullWidth:!0,maxWidth:"sm",open:e,children:[a.jsxs(vt,{component:"h6",sx:{pt:4},children:["How would you like to lock media spends?",a.jsx(Ie,{"aria-label":"close",onClick:u,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})})]}),a.jsx(Ct,{sx:{pb:3},children:a.jsx(Qe,{children:a.jsxs(Wv,{onChange:h,value:o,children:[a.jsx(sn,{value:"typeOnly",control:a.jsx(Xa,{}),label:d}),a.jsx(I,{variant:"body2",sx:{color:"text.secondary",fontStyle:"italic",pl:4,pb:2},children:"Locks spend within this grouping, but allows for reallocation among placements within this grouping."}),a.jsx(sn,{value:"typeAndPlacement",control:a.jsx(Xa,{}),label:c}),a.jsx(I,{variant:"body2",sx:{color:"text.secondary",fontStyle:"italic",pl:4},children:"Locks spend to the placement level and will not be reallocated within this grouping."})]})})}),a.jsxs(un,{sx:{px:3,py:2},children:[a.jsx(re,{color:"secondary",onClick:u,size:"small",variant:"outlined",children:"Cancel"}),a.jsx(re,{disabled:!o,onClick:p,size:"small",variant:"contained",children:"Lock Spends"})]})]})},Eje=({row:e})=>{const{exclude:t,locked:n}=e,{updateRows:r}=CC().current,{handleEditRows:s}=In(),[i,o]=m.useState(!1),l=n?rC:pA,c=()=>{o(!1)},d=()=>
259{if(n){const p=KF(e);r([{...p}]),s([{...p}])}else i||o(!0)},u=p=>{const h=YF(e,p==="typeAndPlacement");r([{...h}]),s([{...h}]),o(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(be,{title:`${n?"Unlock":"Lock"} media spends`,children:a.jsx("span",{children:a.jsx(Ie,{disabled:t,onClick:d,sx:{color:n?"neutral.700":"action.disabled"},children:a.jsx(l,{size:20,strokeWidth:n?2:1.5})})})}),a.jsx(QF,{open:i,onClose:c,onConfirm:u})]})},JF={border:"1px solid",borderColor:"border.input",borderRadius:1,p:1,pr:2,width:"100%",justifyContent:"flex-end"},_je={pr:2},zp=e=>{const{isEditable:t,value:n=0}=e;return a.jsx(ft,{isCurrency:!0,value:n,StackProps:{sx:t?JF:_je},TypographyProps:{sx:{alignSelf:"center"}}})},Tje={alwaysVisible:!1,customType:"pivot",editable:!1,flex:1,minWidth:150,filterOperators:Em().filter(e=>Za.includes(e.value))},Bc={alwaysVisible:!0,customType:"number",editable:!0,flex:1,minWidth:150,type:"number",filterOperators:_m().filter(e=>Lh.includes(e.value))},mI={alwaysVisible:!0,customType:"action",editable:!1,flex:0},Bp=e=>({colDef:t})=>a.jsx(be,{placement:"top",title:e,children:a.jsx(T,{sx:{fontWeight:500},children:t.headerName})}),gI=[{...mI,field:"exclude",headerName:"Include",disableColumnMenu:!0,minWidth:88,width:88,renderCell:e=>a.jsx(Sje,{row:e.row})},{...Bc,editable:!1,field:"current_impressions",headerName:"Impressions",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e?.value||0,StackProps:{sx:{pr:2}}})},{...Bc,field:"current_cpm",headerName:"CPM",minWidth:120,renderCell:zp,renderEditCell:e=>a.jsx($p,{params:e}),renderHeader:Bp(Fp.CPM),valueSetter:vje},{...Bc,field:"current_spend",headerName:"Initial Spend",renderCell:zp,renderEditCell:e=>a.jsx($p,{params:e}),renderHeader:Bp(Fp.INITIAL_PLAN_SPEND),valueSetter:yje},{...mI,field:"locked",headerName:"Lock",minWidth:65,width:65,disableColumnMenu:!0,renderCell:e=>a.jsx(Eje,{row:e.row})},{...Bc,field:"current_min_spend",headerName:"Min Spend",renderCell:zp,renderEditCell:e=>a.jsx($p,{params:e}),renderHeader:Bp(Fp.MIN_SPEND),valueSetter:Cje},{...Bc,field:"current_max_spend",headerName:"Max Spend",renderCell:zp,renderEditCell:e=>a.jsx($p,{params:e}),renderHeader:Bp(Fp.MAX_SPEND),valueSetter:wje}],Ije=e=>({...Tje,field:e.value,headerName:e.label,valueGetter:t=>{const n=`${e.value}_name`;return t.row.agg_object?.[n]||t.row.agg_object?.[e.value]||""}}),Dje=e=>{const t=e.map(n=>Ije(n));return[...gI.slice(0,1),...t,...gI.slice(1)]},Aje=[{label:"Account ID",value:"account_id"},{label:"Account Name",value:"account_name"},{label:"Ad Group ID",value:"adgroup_id"},{label:"Ad Group Name",value:"adgroup_name"},{label:"Campaign Name",value:"campaign_name"},{label:"Country",value:"country"},{label:"Data Source",value:"datasource_name"},{label:"Media Market",value:"market"},{label:"Media Type",value:"type"},{label:"Placement Name",value:"media"},{label:"Platform",value:"platform"},{label:"Tactic",value:"tactic"},{label:"Vehicle",value:"vehicle"},{label:"Vendor",value:"vendor_nice_id"}],xI=rt(sn)(({theme:e})=>({".MuiFormControlLabel-label":{color:e.palette.text.primary,fontSize:16}})),Mje=({anchorEl:e,onApplyEdits:t,onClose:n,selectedCount:r})=>{const[s,i]=m.useState(!0),[o,l]=m.useState(void 0),[c,d]=m.useState(void 0),[u,p]=m.useState(!1),h=m.useMemo(()=>e?.id||"",[e]),f=m.useMemo(()=>e?.innerText||"",[e]),g=m.useMemo(()=>!o&&!c,[o,c]),x=m.useCallback(()=>({value:o||c||0,operator:s?"+":"-",type:o?"$":"%"}),[o,c,s]),b=()=>{t(x(),h)},y=()=>{n()};return a.jsxs($,{sx:{p:2},children:[a.jsx(I,{variant:"subtitle2",sx:{mb:1.5,minHeight:22},children:f}),a.jsx(xI,{control:a.jsx(Xa,{checked:s,id:"radio-add",onChange:()=>{i(!0)},value:"Add"}),label:"Add"}),a.jsx(xI,{control:a.jsx(Xa,{checked:!s,id:"radio-sub",onChange:()=>{i(!1)},value:"Subtract"}),label:"Subtract"}),a.jsxs($,{direction:"row",alignItems:"center",gap:1.5,marginY:2,children:[a.jsx($,{flexGrow:1,children:a.jsx(Gj,{disabled:!1,handleChange:({floatValue:v})=>{l(v),u&&p(!u),c&&d(void 0)},startAdornment:"$",isError:u,value:o||""})}),a.jsx(I,{component:"span",children:"or"}),a.jsx($,{flexGrow:1,children:a.jsx(Gj,{disabled:!1,handleChange:({floatValue:v})=>{d(v),u&&p(!u),o&&l(void 0)},startAdornment:"%",isError:u,value:c||""})})]}),a.jsxs($,{direction:"row",sx:{mt:2,justifyContent:"space-between",height:36,gap:1.5},children:[a.jsx(re,{color:"secondary",onClick:y,sx:{width:130},children:"Cancel"}),a.jsxs(re,{disabled:g,onClick:b,sx:{flexGrow:1},variant:"contained",children:["Update ",r," Selected"]})]})]})},bI={p:0,minWidth:36,height:36},Up=18,Rje=({disabled:e})=>{const[t,n]=m.useState(null),{columns:r,gridApiRef:s,state:i}=xa(),o=i.selectedRows,{handleEditRows:l}=In(),c=m.useMemo(()=>r.filter(j=>j.editable),[r]),[d]=m.useMemo(()=>o,[o]),u=m.useMemo(()=>d&&d.locked||!1,[d]),p=m.useMemo(()=>d&&d.exclude||!1,[d]),[h,f]=m.useState(u),[g,x]=m.useState(!1),[b,y]=m.useState(p);u!==h&&f(u),p!==b&&y(p);const v=j=>{s.current.updateRows([...j]),l(j.map(_=>({..._})))},C=()=>{n(null)},w=()=>{v(o.map(j=>b?Ah(j):Uw(j))),h&&b&&f(!h),y(!b)},S=()=>{v(o.map(j=>KF(j.exclude?Ah(j):j))),f(!h),b&&y(!b)},E=j=>{x(!1),f(!h),v(o.map(_=>YF(_.exclude?Ah(_):_,j==="typeAndPlacement"))),b&&y(!b)},k=(j,_)=>{const{type:D,operator:M,value:N}=j;v(o.map(O=>{const{locked:R,exclude:L}
259=O;let P=O[_]||0;const F=D==="%"?P*(N/100):N;M==="+"?P+=F:P-=F;let z=O;const B=c.find(W=>W.field===_)?.valueSetter;return!R&&!L&&B&&(z=B({value:P,row:O})),z})),n(null)};return a.jsxs($,{direction:"row",gap:1,sx:{alignItems:"center",height:40,mb:3},children:[a.jsxs($,{direction:"row",sx:{pr:1,alignItems:"center",lineHeight:"22px",minWidth:155},children:[a.jsx(I,{component:"span",sx:{color:"text.secondary"},children:"Update:Â "}),a.jsxs(I,{component:"span",children:[o.length," selected rows"]})]}),c.map(({field:j,headerName:_})=>a.jsx(re,{color:"secondary",disabled:e||h||b,id:j,onClick:D=>{n(t?null:D.currentTarget)},sx:{p:"5px 13px 5px 15px",width:140,lineHeight:"24px"},children:a.jsxs($,{sx:{gap:1.25,width:"100%",flexDirection:"row",alignItems:"center",justifyContent:"space-between"},children:[_,a.jsx(vs,{size:16})]})},j)),a.jsx(re,{color:"secondary",disabled:e,sx:bI,onClick:w,children:b?a.jsx(zD,{size:Up}):a.jsx(vm,{size:Up})}),a.jsx(re,{color:"secondary",disabled:e,sx:bI,onClick:()=>{h?S():x(!0)},children:h?a.jsx(rC,{size:Up}):a.jsx(pA,{size:Up})}),a.jsx(QF,{open:g,onClose:()=>x(!1),onConfirm:E}),a.jsx(ED,{anchorEl:t,disableScrollLock:!0,id:"filter-menu",open:!!t,anchorOrigin:{vertical:"bottom",horizontal:"left"},onClose:C,"data-testid":"component-submenu",sx:{zIndex:1e7},children:a.jsx(Br,{sx:{width:400},children:a.jsx(Mje,{onApplyEdits:k,onClose:C,anchorEl:t,selectedCount:o.length})})})]})},Nje={selectedPivots:["type"]},Oje=e=>{const t={...Nje};return e?.initialPivots?.length&&(t.selectedPivots=e.initialPivots),t},Pje=()=>{const e=W0(),{dispatch:t,editValues:n,handleChangePivots:r,handleEditRows:s,handleGetData:i,pivotOptions:o,pivotsLoading:l,state:c}=In(),{tableState:d}=c,{data:u,totalRows:p}=d,h=HF(c),f=Oje(n),g=m.useMemo(()=>Dje(o),[o]);return m.useEffect(()=>{c.tableState.pivotTableRef||t({type:"tableState",subType:"pivotTableRef",value:e})},[t,e,c.tableState.pivotTableRef]),a.jsx(G0,{BatchEdit:Rje,columns:g,controlsChildren:a.jsx(VSe,{}),data:u,loading:h||l,onChangePivots:r,onEditRows:s,onGetData:i,initialState:f,pivotOptions:o,pivotTableRef:e,totalRows:p})},Vp=({children:e,text:t})=>a.jsxs($,{sx:{flexDirection:"row",alignItems:"center"},children:[a.jsx(T,{sx:{width:100,textAlign:"center",mr:5},children:e}),a.jsx(I,{children:t})]}),Lje=a.jsxs($,{direction:"column",mt:4,spacing:4,children:[a.jsx(Vp,{text:"Click within cell to edit.",children:a.jsx(ft,{isCurrency:!0,value:1234.56,StackProps:{sx:JF},TypographyProps:{sx:{alignSelf:"center",lineHeight:"22px"}}})}),a.jsx(Vp,{text:"Toggle to exclude rows from plan.",children:a.jsx(Dn,{sx:{pointerEvents:"none"}})}),a.jsxs(Vp,{text:"Select multiple rows to manage bulk edits.",children:[a.jsx(et,{sx:{position:"absolute",ml:1,mt:0,pointerEvents:"none"},defaultChecked:!0}),a.jsx(et,{sx:{pointerEvents:"none",bottom:10,right:2}})]}),a.jsx(Vp,{text:"Lock function: force plan to accept specific spend amount.",children:a.jsx(rC,{size:22,strokeWidth:2})})]}),Fje=()=>{const[e,t]=m.useState(!1);return a.jsxs(T,{children:[a.jsx(re,{color:"secondary",id:"create-tips-button",variant:"outlined",onClick:()=>t(!0),startIcon:a.jsx(jw,{sx:{height:"14px"}}),children:"Tips"}),a.jsx(mt,{open:e,body:Lje,acceptLabel:"Ok",handleAccept:()=>t(!1),handleClose:()=>t(!1),hideClose:!0,title:"Tips to customize your plan"})]})},$je=()=>{const e=ct(),{didInitAggTable:t,setDidInitAggTable:n,dispatch:r,editing:s,editValues:i,handleGetConversionBudget:o,initPlanData:l,state:c}=In(),{budget:d,conversions:u,loading:p,modelInfo:h,planName:f,planType:g,selectedDates:x,selectedKpis:b,referenceDateRange:y}=c,{initPlanData:v,initEditPlanData:C}=l,w=ZD(),S=10,E=0,[k,j]=x,[_,D]=y,M=s&&!!i,N=w&&!p&&k&&j&&_&&D&&!!h&&!!f&&!!b.length&&(g==="budget"&&!!d||g==="conversion"&&!!u),O=({error:L,data:P})=>{e()&&(L||(r({type:"metaIds",value:{calcId:P.calcId,optId:P.optId}}),r({type:"tableState",subType:"totalRows",value:P.totalRows}),r({type:"tableState",subType:"data",value:P.media}),g==="budget"&&r({type:"updateBudgetCurrent",value:d})),n(!0),r({type:"updateLoading",value:null}))},R=async()=>{if(N){let L=d;if(r({type:"updateLoading",value:"initializing"}),g==="conversion"&&(!d||M&&i.conversion_target!==u)&&h.scaled_conversion_table){const{data:P}=await o({conversion_target:u,scaled_conversion_table:h.scaled_conversion_table});if(P!==null&&e()){const F=Math.round(P);L=F,r({type:"conversionBudget",value:F})}}O(!s&&!t?await v({budget:L,conversions:u,limit:S,modelInfo:h,offset:E,planName:f,referenceDateRange:[_,D],selectedDateRange:[k,j],selectedKpis:b}):M?await C({editValues:i,budget:L,didInit:t,limit:S,offset:E}):{error:"initData",data:null})}};m.useEffect(()=>{R()},[N])},zje=()=>{const{dispatch:e,state:t}=In(),{budget:n,planType:r,tableState:s}=t,{data:i,editActions:o}=s;m.useEffect(()=>{if(r==="conversion"||!n)return;const l=i.reduce((c,d)=>o.has(d.id)?c+(o.get(d.id)?.current_spend??0)-(d.current_spend??0):c,0);e({type:"updateBudgetLocal",value:l})},[n,e,o,r,i])},Bje=()=>{const{dispatch:e,state:t}=In(),{engagementCurrency:n}=pe(),{allocatedBudget:r,autoScale:s,budget:i,modelInfo:o,planType:l,conversions:c,selectedDates:d,selectedKpis:u}=t,[p,h]=d,f=HF(t),g=m.useMemo(()=>WF(o),[o]);$je(),zje();const x=()=>{e({type:"autoScale"})},b=new Intl.NumberFormat("en",{currency:n,maximumFractionDigits:0,style:"currency"}),y=new Intl.NumberFormat("en",{maximumFractionDigits:2}),v=m.useMemo(()=>
259{if(u.length===1){const[D]=u;return D?.name||""}return NU(u.map(D=>({name:D.name||"Unknown",percent:D.percent})))},[u]),C=!p||!h?"":`${p.format("ll")}-${h.format("ll")}`,w=Math.round(i-r.total)||0,S=a.jsxs(a.Fragment,{children:[b.format(r.total)," ",a.jsxs(I,{sx:{color:"text.secondary"},component:"span",children:["/ ",b.format(i)]})]}),E=b.format(w),j=zw(u)*c,_=y.format(j);return a.jsxs($,{children:[a.jsxs($,{sx:{gap:2,pb:4},children:[a.jsxs($,{direction:"row",justifyContent:"space-between",children:[a.jsx(Xt,{title:"Start Planning"}),a.jsx(Fje,{})]}),a.jsx(I,{variant:"body2",children:"Edit values in the table below to customize your optimization."})]}),a.jsx(zF,{dateRangeString:C,kpiString:v,modelDatesString:g,children:a.jsxs($,{direction:"row",spacing:2,alignItems:"center",children:[l==="budget"&&a.jsx(uI,{leftDescription:"Planned Budget",leftValue:S,rightDescription:"Remaining Budget",rightValue:E}),l==="conversion"&&a.jsx(uI,{leftDescription:"Conversion Target",leftValue:_}),a.jsx(bje,{checked:s,disabled:f,handleSwitch:x})]})}),a.jsx(St,{sx:{my:4}}),a.jsx(Pje,{})]})},Ea={complete:{description:"Your plan is complete! Results loading",descriptionSxProps:{textAlign:"none",ml:12,"&:after":{"@keyframes dots":{"0%":{content:'""'},"25%":{content:'"."'},"50%":{content:'".."'},"75%":{content:'"..."'},"100%":{content:'""'}},display:"inline-block",animation:"dots steps(1,end) 1s infinite",content:'""'}},Icon:OU,iconProps:{variant:"determinate",value:100},step:5,title:"Completed"},post:{Icon:PU,step:4,title:"Posting Results"},optimization:{Icon:LU,step:3,title:"Running Optimization"},process:{Icon:FU,step:2,title:"Preparing Data"},init:{Icon:YD,step:1,title:"Initializing"},error:{description:"There was an error running the plan. Please file a support ticket.",descriptionSxProps:{textAlign:"center",ml:5},Icon:()=>a.jsx($U,{color:"error"}),iconProps:{color:"error",variant:"determinate",value:100},step:null,title:"Error"}},Uje=({dataOpt:e,dataPlanned:t})=>!e?.status||!t?.status?Ea.init:Object.values(e.status).some(n=>n==="Failed")||Object.values(t.status).some(n=>n==="Failed")?Ea.error:e.status.post==="Done"&&t.status.post==="Done"?Ea.complete:e.status.optimization==="Done"&&t.status.optimization==="Done"?Ea.post:e.status.process==="Done"&&t.status.process==="Done"?Ea.optimization:e.status.init==="Done"&&t.status.init==="Done"?Ea.process:Ea.init,Vje=({dataOpt:e,dataPlanned:t})=>e?.status&&t?.status&&Object.values(e.status).every(n=>n==="Done")&&Object.values(t.status).every(n=>n==="Done"),Wp={display:"flex",flexDirection:"column",alignItems:"center"},Wje=()=>{const e=en(),{supportLink:t}=jt(),{calcId:n,optId:r}=In().state,{useGetPlanStatus:s}=In(),{dataPlanned:i,dataOpt:o}=s(n,r),{description:l,descriptionSxProps:c,Icon:d,iconProps:u,step:p,title:h}=m.useMemo(()=>Uje({dataOpt:o,dataPlanned:i}),[o,i]);return m.useEffect(()=>{Vje({dataOpt:o,dataPlanned:i})&&(n&&r?e("/planning/view-plan",{searchParams:{calcId:n.toString(),optId:r.toString()},state:{meta_ids:[n,r]}}):e("/planning/my-plans"))},[n,o,i,r,e]),a.jsxs($,{height:600,sx:{...Wp,justifyContent:"space-between",height:"100%"},children:[a.jsxs(T,{sx:{...Wp,justifyContent:"space-between",height:87},children:[a.jsx(Xt,{title:"Running Plan Optimization"}),a.jsxs(T,{sx:{...Wp,flexDirection:"row",backgroundColor:"background.brand.subtle.default",borderRadius:"5px",padding:"5px"},children:[a.jsx(Mt,{children:a.jsx(wl,{})}),a.jsx(I,{sx:{ml:"5px",color:"text.default"},children:"Please do not refresh or close the browser. Setting up your optimized plan can take up to 15 minutes."})]})]}),a.jsx(AM,{icon:a.jsx(d,{}),...u}),a.jsxs(T,{sx:{...Wp,width:"440px"},children:[a.jsx(I,{variant:"h6",children:h}),l?a.jsx(I,{variant:"body2",sx:{color:"text.secondary",margin:"auto",width:"80%",mt:1,...c},children:l}):null]}),p?a.jsxs(I,{variant:"overline",sx:{color:"text.disabled"},children:["STEP ",p,"/5"]}):a.jsx(lu,{href:t})]})},Hje=()=>{const{dispatch:e,editing:t,getDateRange:n,getModelInfo:r,handleClose:s,handleDeletePlans:i,state:o}=In(),{activeStep:l,calcId:c,optId:d,selectedKpis:u,referenceDateRange:p}=o,[h,f]=p,[g,x]=m.useState(!1);let b;switch(l){case 0:b=a.jsx(KSe,{});break;case 1:b=a.jsx(xje,{});break;case 2:b=a.jsx(Bje,{});break;case 3:b=a.jsx(Wje,{});break;default:b=null}const y=()=>{x(!0)},v=()=>{x(!1)},C=async()=>{c&&d&&!t&&await i([c,d]),s()};return m.useEffect(()=>{let w=!0;return(async()=>{const E=u.map(({niceId:k})=>k);if(E.length&&!t){e({type:"updateLoading",value:"dateRange"});const{range:k}=await n(E);w&&(e({type:"updateDateRange",value:k}),e({type:"updateLoading",value:null}))}})(),()=>{w=!1}},[e,n,u,t]),m.useEffect(()=>{let w=!0;return(async()=>
259{if(h&&f&&u&&!t){const E=u.map(({niceId:j})=>j);e({type:"updateLoading",value:"modelInfo"});const{modelInfo:k}=await r({endDate:f,kpiNiceIds:E,startDate:h});w&&(e({type:"updateModelInfo",value:k}),e({type:"updateLoading",value:null}))}})(),()=>{w=!1}},[e,r,u,t,h,f]),a.jsxs(yt,{"data-testid":"create-plan:dialog",fullScreen:!0,open:!0,children:[a.jsxs(vt,{variant:"h6",sx:{m:"32px 24px 76px 24px",p:0,"&.MuiTypography-h6":{fontSize:18,lineHeight:"22px"}},children:["Create a Plan",a.jsx(Ie,{"aria-label":"Close plan creation","data-testid":"create-plan:exit:button",onClick:y,sx:{position:"absolute",right:12,top:24},children:a.jsx(Jt,{})}),a.jsx(mt,{bodyText:"You have unsaved data. If you leave the page, these changes will be lost.",handleClose:v,handleAccept:C,open:g,testId:"create-plan:exit-confirm:dialog",title:"Leave Plan Creation?",acceptLabel:"Yes, Leave"})]}),a.jsx(Ct,{sx:{pb:6.5,display:"flex",justifyContent:"center"},children:a.jsxs($,{gap:6,width:l===2||l===3?1142:680,children:[l<3&&a.jsx(T,{width:680,sx:{alignSelf:"center"},children:a.jsx(USe,{activeStep:l})}),b]})}),l<3&&a.jsx(zSe,{handleTryExit:y})]})},qje=()=>({data:[],editActions:new Map,pivotTableRef:null,totalRows:-1}),vv=()=>({activeStep:0,autoScale:!0,allocatedBudget:{current:0,local:0,total:0},budget:0,calcId:null,conversions:0,dateRange:[null,null],loading:null,modelInfo:null,optId:null,planName:"",planType:"budget",referenceDatesUpdatedByUser:!1,selectedDates:[null,null],referenceDateRange:[null,null],selectedKpis:[],tableState:qje(),userClickedValidRangeModal:!1}),Gje=(e,t)=>{switch(t.type){case"autoScale":return{...e,autoScale:!e.autoScale};case"conversionBudget":return{...e,budget:t.value};case"decrementStep":return{...e,activeStep:e.activeStep-1};case"loadFromEditValues":return{...e,...LSe(e,t.value.editValues)};case"incrementStep":return{...e,activeStep:e.activeStep+1};case"metaIds":return{...e,...t.value};case"removeSelectedKpi":return{...vv(),planName:e.planName,planType:e.planType,selectedKpis:dI(e.selectedKpis.filter(({id:n})=>n!==t.value))};case"updateBudgetCurrent":return{...e,allocatedBudget:{current:t.value,local:0,total:t.value}};case"updateBudgetLocal":return{...e,allocatedBudget:{...e.allocatedBudget,local:t.value,total:e.allocatedBudget.current+t.value}};case"updateBudget":return{...e,budget:t.value,conversions:t.value?0:e.conversions};case"updateConversions":return{...e,budget:t.value?0:e.budget,conversions:t.value};case"updateDateRange":return{...e,conversions:0,dateRange:t.value,modelInfo:null,selectedDates:[null,null]};case"updateReferenceDateRange":return{...e,modelInfo:null,referenceDateRange:t.value.referenceDateRange,referenceDatesUpdatedByUser:t.value.referenceDatesUpdatedByUser};case"updateKpiPercent":return{...e,selectedKpis:e.selectedKpis.map(n=>n.id!==t.value.id?n:{...n,percent:t.value.nextPercent})};case"updateLoading":return{...e,loading:t.value};case"updateModelInfo":return{...e,conversions:0,modelInfo:t.value};case"updatePlanName":return{...e,planName:t.value};case"updatePlanType":return{...e,planType:t.value};case"updateSelectedKpis":return{...vv(),planName:e.planName,planType:e.planType,selectedKpis:dI(t.value)};case"updateSelectedDates":return{...e,conversions:0,modelInfo:null,selectedDates:t.value};case"validRangeModal":return{...e,userClickedValidRangeModal:t.value};case"tableState":switch(t.subType){case"pivotTableRef":case"data":case"totalRows":return{...e,tableState:{...e.tableState,[t.subType]:t.value}};case"addEdit":return{...e,tableState:{...e.tableState,editActions:new Map(e.tableState.editActions.set(t.value.id,t.value))}};case"resetEdits":return{...e,tableState:{...e.tableState,editActions:new Map,data:[...e.tableState.data]}};default:return e}default:return e}},[Yje]=Za,Kje=e=>e.filter(t=>t.operator&&t.value&&Lh.includes(t.operator)).reduce((t,n)=>{const{field:r,value:s,operator:i}=n;return Tn(Lh,i)?{...t,[r]:[...t[r]||[],{value:s,operator:i}]}:t},{}),Qje=e=>e.filter(t=>t.operator&&t.value&&Za.includes(t.operator)).map(t=>({column:t.field,type:Tn(Za,t.operator)?t.operator:Yje,value:t.value})),Jje=e=>e.map(t=>({column:t.field,ascending:t.sort==="asc"})),XF=({filterModelItems:e,sortModel:t})=>({numericalFilters:Kje(e),searchColumns:Qje(e),sort:Jje(t)}),Xje=({filterModelItems:e,limit:t,offset:n,search:r,sortModel:s},i)=>
259({calcId:i,limit:t,offset:n,search:r,...XF({filterModelItems:e,sortModel:s})}),Zje=({filterModelItems:e,limit:t,offset:n,search:r,sortModel:s},{optId:i,includeBudget:o})=>({budget:o,limit:t,offset:n,optId:i,search:r,...XF({filterModelItems:e,sortModel:s})}),eke=({changePivots:e,createPlanMpTrack:t,dispatch:n,handleEditAggData:r,queryAggData:s,state:i})=>{const o=ct(),{autoScale:l,optId:c,planType:d,tableState:u}=i,{editActions:p,pivotTableRef:h}=u,[f,g]=m.useState(!1),x=m.useCallback(async()=>{if(c&&p.size!==0){n({type:"updateLoading",value:"editing"}),t("table",{edits:!0});const{error:w}=await r({auto_scale:l,meta_id:c,updates:Array.from(p.values())});return w||o()&&n({type:"tableState",subType:"resetEdits"}),d==="budget"&&!w}return!1},[l,t,n,p,r,o,c,d]),b=m.useCallback(async w=>{const{filterModelItems:S,limit:E,offset:k,sortModel:j}=w;if(c){const _=await x(),D=Zje(w,{optId:c,includeBudget:f||_}),M={query:!0,limit:E,offset:k};D.search&&(M.search=!0),S.length&&(M.filter=!0),j.length>0&&(M.sort=!0),t("table",M),n({type:"updateLoading",value:"querying"});const{data:N,error:O}=await s(D);return o()&&(n({type:"tableState",subType:"totalRows",value:O?0:N.total_rows}),n({type:"tableState",subType:"data",value:O?[]:N.media}),N&&N.current_budget&&n({type:"updateBudgetCurrent",value:N.current_budget}),g(!1)),n({type:"updateLoading",value:null}),{error:!!O}}return g(!1),n({type:"updateLoading",value:null}),{error:!0}},[t,n,x,f,o,c,s]),y=m.useCallback(async w=>{if(c){const S=await x();t("table",{pivots:!0}),o()&&(g(S),n({type:"updateLoading",value:"changingPivots"}),n({type:"tableState",subType:"totalRows",value:-1}));const{error:E}=await e({pivots:w,optId:c});return o()&&E&&n({type:"updateLoading",value:null}),{error:!!E}}return{error:!0}},[e,t,n,x,o,c]),v=m.useCallback(w=>{w.forEach(S=>{n({type:"tableState",subType:"addEdit",value:S})})},[n]),C=m.useCallback(async()=>{if(h){const{currentPage:w,rowsPerPage:S,sortModel:E,search:k,filterModel:j}=h.current.state,_=S,D=w*S;return b({limit:_,offset:D,search:k,sortModel:E,filterModelItems:j.items})}return{error:!0}},[b,h]);return{handleChangePivots:y,handleClickSaveEdits:C,handleEditRows:v,handleGetData:b}},tke=({didInitAggTable:e,setDidInitAggTable:t,editing:n,editInfoLoading:r,editValues:s,changePivots:i,createPlanExport:o,engagementName:l,getDateRange:c,getModelInfo:d,handleDeletePlans:u,handleClose:p,handleEditAggData:h,handleGetConversionBudget:f,handleUpdateScenario:g,initPlanData:x,kpiOptions:b,locale:y,pivotOptions:v,pivotsLoading:C,queryAggData:w,runOptimization:S,useGetPlanStatus:E,createPlanMpTrack:k})=>{const[j,_]=m.useReducer(Gje,vv()),[D,M]=m.useState(s),{handleChangePivots:N,handleClickSaveEdits:O,handleEditRows:R,handleGetData:L}=eke({changePivots:i,createPlanMpTrack:k,dispatch:_,handleEditAggData:h,queryAggData:w,state:j});D!==s&&(s&&_({type:"loadFromEditValues",value:{editValues:s}}),M(s)),m.useEffect(()=>{b.length&&j.loading==="kpis"&&_({type:"updateLoading",value:null})},[b,j.loading]);const P=m.useMemo(()=>({didInitAggTable:e,setDidInitAggTable:t,editing:n,editInfoLoading:r,editValues:s,changePivots:i,createPlanMpTrack:k,createPlanExport:o,dispatch:_,engagementName:l,getDateRange:c,getModelInfo:d,handleChangePivots:N,handleClickSaveEdits:O,handleClose:p,handleDeletePlans:u,handleEditAggData:h,handleEditRows:R,handleGetConversionBudget:f,handleGetData:L,handleUpdateScenario:g,initPlanData:x,kpiOptions:b,locale:y,pivotOptions:v,pivotsLoading:C,queryAggData:w,runOptimization:S,state:j,useGetPlanStatus:E}),[e,t,n,r,s,i,k,o,_,l,c,d,N,O,p,u,h,R,f,L,g,x,b,y,v,C,w,S,j,E]);return a.jsx(VF.Provider,{value:P,children:a.jsx(Hje,{})})},nke=()=>{const[e]=y3(),[t]=bC(),{engagementId:n,engagementNiceId:r}=pe(),{data:s=[]}=Qs(n),i=s[0]?.id||0,{data:o=[]}=QA({brandId:i,engagementNiceId:r},{skip:!i});return async({calcId:c,optId:d,selectedPivots:u})=>{const p=o.reduce((g,x)=>({...g,[x.dimension]:x.title}),{});return"error"in await t({pivots:u,metaId:d})?{error:!0}:"error"in await e({aggs:u,calcId:c,dimensions:p,engagementNiceId:r,optId:d})?{error:!0}:{error:!1}}},rke={backPage1:"Back: Plan Details",backPage2:"Back: Plan Goals",batch:"Batch Upload",close:"Close",email:"Email Template",nextPage2:"Next: Plan Goals",nextPage3:"Next: Set Plan",runop:"Run Optimization",table:"Table Action"},ske=()=>pr({actionMap:rke,eventName:"createPlan"}),ike=(e,t)=>{const n=ct(),{message:r}=fu("Planner"),[s,i]=m.useState(),[o,l]=m.useState(),[c]=GA(),d=m.useMemo(()=>o&&s&&[o,s].every(({status:p})=>Object.values(p).every(h=>h==="Done")),[o,s]);m.useEffect(()=>{if(!r)return;const{metaId:p,plan:h}=r.data;h.status&&(p===e&&i(h.status),p===t&&l(h.status))},[e,r,t]);const u=m.useCallback(async()=>{const p=async b=>{const{data:y}=await c(b);return y?.status??null};if(!e||!t)return;
259const h=p(e),f=p(t),g=await h,x=await f;n()&&(g&&i(g),x&&l(x))},[e,c,n,t]);return kF(u,{skip:d}),{dataPlanned:s,dataOpt:o}},ab=([e,t])=>{const n=e.format("YYYY-MM-DD"),r=t.format("YYYY-MM-DD");return[n,r]},ake=()=>{const{clientId:e,engagementId:t,engagementNiceId:n}=pe(),{userId:r}=gt(),{data:s=[]}=Qs(t),{id:i,brand_nice_id:o}=s[0]??{id:0,brand_nice_id:""},[l]=WA(),[c]=v3(),[d]=C3(),[u]=w3(),[p]=JA(),h=({budget:x,conversions:b,modelInfo:y,parentId:v=null,planName:C,selectedDateRange:w,referenceDateRange:S,selectedKpis:E})=>{const[k,j]=ab(w),[_,D]=ab(S),M=E.map(({id:N,name:O,percent:R,niceId:L})=>({id:N,model_run_id:"20191001to20191006",name:O,nice_id:L,percent:R/100}));return{brand_id:i,budget:x,client_id:e,conversion_target:b,duration_end:D,duration_start:_,engagement_id:t,identity_id:r,master_id:v,model_info:y,name:C,notes:"",objectives:M,optimization_type_id:v?2:1,parent_id:v,plan_start:k,plan_end:j,state_id:$n.Private}};return{initPlanData:async({budget:x,conversions:b,limit:y,modelInfo:v,offset:C,planName:w,selectedDateRange:S,referenceDateRange:E,selectedKpis:k})=>{const j={budget:x,conversions:b,modelInfo:v,planName:w,selectedDateRange:S,referenceDateRange:E,selectedKpis:k},_=h(j),D=await l(_);if(!("data"in D))return{data:null,error:"createCalcId"};const{id:M}=D.data,N=h({...j,parentId:M}),O=await l(N);if(!("data"in O))return{data:null,error:"createOptId"};const{id:R}=O.data,[L,P]=ab(E);if("error"in await c({budget:x,brandName:o,engagementNiceId:n,maxDate:P,minDate:L,modelInfo:v,optId:R}))return{data:null,error:"initMediaPool"};if("error"in await u({aggs:["type"],metaId:R}))return{data:null,error:"initMediaAgg"};const B=await p({limit:y,offset:C,optId:R});if("error"in B||B?.data===void 0)return{data:null,error:"getAggData"};const{media:W,total_rows:H}=B.data;return{data:{calcId:M,media:W,optId:R,totalRows:H},error:null}},initEditPlanData:async({budget:x,didInit:b,editValues:y,limit:v,offset:C})=>{const[w,S]=y.metaIds;if("error"in await d({engagement_nice_id:y.engagement_nice_id,brand:y.brand_name_slug,meta_id:S,first_run:b?"False":"True",budget:x}))return{data:null,error:"initMediaPoolAggEdit"};const k=await p({limit:v,offset:C,optId:S});if("error"in k||k?.data===void 0)return{data:null,error:"getAggData"};const{media:j,total_rows:_}=k.data;return{data:{calcId:w,media:j,optId:S,totalRows:_},error:null}}}},oke=()=>{const[e]=bC(),[t]=JA(),n=m.useCallback(async({pivots:s,optId:i})=>"error"in await e({pivots:s,metaId:i})?{error:"changePivots"}:{error:null},[e]),r=m.useCallback(async s=>{const i=await t(s);return"error"in i?{data:null,error:"queryAggData"}:{data:i.data,error:null}},[t]);return{changePivots:n,queryAggData:r}},lke=()=>{const{engagementNiceId:e}=pe(),[t]=S3(),[n]=j3(),[r]=HA(),[s]=qA(),[i]=bC();return async({calcId:o,optId:l,pivots:c})=>{if("error"in await i({pivots:c,metaId:l}))return{error:"editMediaPool"};if("error"in await t({calcId:o,optId:l}))return{error:"createAggConstraints"};if("error"in await n({engagementNiceId:e,calcId:o,optId:l}))return{error:"createMediaData"};const h=[o,l].map(async x=>{const b=await r({engagementNiceId:e,metaId:x,version:5});return"error"in b||!b.data.job_id?{error:"sendMetaId",metaId:x}:"error"in await s(b.data.job_id)?{error:"superConductorStatus",metaId:x}:{error:null,metaId:x}}),g=(await Promise.all(h)).filter(({error:x})=>!!x);return g.length?{errors:g}:{error:null}}},cke=()=>{const e=en(),[t]=Jv(),{setRaiseConversationIcon:n}=jt(),{engagementCountry:r,engagementId:s,engagementName:i,engagementNiceId:o}=pe(),{calcId:l,optId:c}=m.useMemo(()=>{const Y=t.get("calcId"),ae=t.get("optId");return{calcId:Y?Number(Y):0,optId:ae?Number(ae):0}},[t]),{data:d=[],isFetching:u,isUninitialized:p}=xC(s,{skip:!(l&&c)}),h=m.useMemo(()=>l?d?.find(Y=>Y.id===l):null,[l,d]);(l&&!c||!l&&c||!p&&!(u||h))&&e("/planning/my-plans");const{data:f=null,isLoading:g,isFetching:x}=XA(Number(c),{skip:!(l&&c),refetchOnMountOrArgChange:!0}),{data:b=[]}=Qs(s),y=b[0]?.brand_nice_id||"",{data:v=[]}=hu(s),C=m.useMemo(()=>PSe(v),[v]),{data:w=[],isFetching:S}=k3(c,{skip:!c}),E=m.useMemo(()=>{const[Y]=w;if(!Y)return;const{AGG_NAMES:ae}=Y;return ae.map(je=>je.replace("_name",""))},[w]),k=m.useMemo(()=>!l||g||S||x||!C.length||!c||!f?null:{...f,metaIds:[l,c],initialPivots:E,objectives:f.objectives.map(ae=>({...ae,nice_id:ae.nice_id?ae.nice_id:C[C.findIndex(je=>je.id===ae.id)]?.niceId||""}))},[l,E,g,S,x,C,c,f]),[j]=E3(),[_]=_3(),D=ake(),M=nke(),[N]=KA(),{pivotsLoading:O,pivotOptions:R}=O0(Aje,{filterFn:({active:Y,dimension_type:ae})=>Y&&ae==="media"}
259),[L]=T3(),P=lke(),{changePivots:F,queryAggData:z}=oke(),[B]=YA(),[W]=I3(),H=ske(),[V,G]=m.useState(!1),X=m.useCallback(async Y=>{const{data:ae=[],error:je,isLoading:me}=await j({brandSlug:y,engagementNiceId:o,kpiNiceIds:Y}),[ve=null,Me=null]=ae.map(Q=>Q?Z(Q):null);return{error:je,isLoading:me,range:[ve,Me]}},[j,y,o]),K=m.useCallback(async({endDate:Y,kpiNiceIds:ae,startDate:je})=>{const{data:me=null,error:ve,isLoading:Me}=await _({brandSlug:y,endDate:Y.format("YYYY-MM-DD"),engagementNiceId:o,kpiNiceIds:ae,startDate:je.format("YYYY-MM-DD")});return{error:ve,isLoading:Me,modelInfo:me}},[y,_,o]),ie=async Y=>"error"in await L(Y)?{error:!0}:{error:!1},le=async Y=>{const ae=await W(Y);return"error"in ae||!ae?.data?{data:null,error:!0}:{data:ae.data,error:!1}},ce=m.useCallback(()=>{H("close"),e("/planning/my-plans")},[e,H]),J=m.useCallback(async Y=>B(Y),[B]),he=m.useCallback(async Y=>{const{columnName:ae,metaIds:je,newValue:me}=Y;await Promise.all(je.map(async ve=>{await N({columnName:ae,metaId:ve,newValue:me})}))},[N]);m.useEffect(()=>(n(!0),()=>n(!1)),[n]);const ne=g||x||S||u;return a.jsx(tke,{didInitAggTable:V,setDidInitAggTable:G,editing:!!c,editInfoLoading:ne,editValues:k,changePivots:F,createPlanExport:M,engagementName:i,getDateRange:X,getModelInfo:K,handleClose:ce,handleDeletePlans:J,handleEditAggData:ie,handleGetConversionBudget:le,handleUpdateScenario:he,initPlanData:D,kpiOptions:C,locale:r,pivotOptions:R,pivotsLoading:O,queryAggData:z,runOptimization:P,useGetPlanStatus:ike,createPlanMpTrack:H})},dke={batchUpload:"Batch Upload",create:"Create Plan",view:"View Plan"},uke=()=>pr({actionMap:dke,eventName:"myPlans"}),pke=({stateName:e="Private"})=>a.jsx($w,{stateName:e}),ZF=m.createContext(null),Sg=()=>m.useContext(ZF),hke=({row:e})=>{const{handleDeletePlans:t,handleDuplicatePlan:n,handleEditPlan:r,handleUpdatePlanState:s,isInternalUser:i,userId:o}=Sg(),l=o===e.identityId,c=e.stateId===$n.Actioned,d=Object.values(e.optStatus).some(({steps:f})=>!!f),p=Ku(e)||!d,h=!d||!i&&!l||c;return a.jsx($F,{disableDuplicate:p,disableEdit:h,handleEditPlan:r,handleDeletePlans:t,handleDuplicatePlan:n,handleUpdatePlanState:s,isInternalUser:i,row:e,userId:o,variant:"text"})},fke=({row:e})=>{const{budgetOrConversionValue:t,type:n,kpiScalar:r}=e,s=n==="budget",i=n==="conversion"&&r&&r>0?r*t:t;return a.jsx(ft,{fractionDigits:0,isCurrency:s,noTooltip:!0,value:i})},Ds=({children:e,sx:t})=>a.jsxs(a.Fragment,{children:[a.jsx(I,{component:"span",variant:"caption",sx:t,children:e}),a.jsx("br",{})]}),mke=({errorMsg:e,id:t,status:n})=>a.jsxs(a.Fragment,{children:[a.jsxs(Ds,{children:["Meta id: ",t]}),a.jsxs(T,{sx:{pl:2},children:[n?a.jsxs(a.Fragment,{children:[a.jsx(Ds,{children:"Steps:"}),a.jsxs(T,{sx:{pl:2},children:[a.jsxs(Ds,{children:["Initializing: ",n.init]}),a.jsxs(Ds,{children:["Fetching Data: ",n.process]}),a.jsxs(Ds,{children:["Running Optimization: ",n.optimization]}),a.jsxs(Ds,{children:["Posting Results: ",n.post]}),a.jsxs(Ds,{children:["Complete: ",n.complete]})]})]}):a.jsx(Ds,{children:"No status info available"}),a.jsx(Ds,{children:"Error message:"}),a.jsx(Ds,{sx:{pl:2},children:e})]})]}),gke=rt(({className:e,...t})=>a.jsx(be,{...t,classes:{popper:e}}))({[`& .${zv.tooltip}`]:{maxWidth:500}}),xke=({row:e})=>{const{optStatus:t,planName:n}=e,{isInternalUser:r}=Sg(),s=Ku(e),i=Object.entries(t).map(([l,c])=>({id:Number(l),status:c})),o=s?a.jsxs(a.Fragment,{children:[a.jsx(I,{variant:"caption",children:`Plan name: "${n}"`}),a.jsx(St,{}),i.map(({id:l,status:c},d)=>{if(!c)return null;const{externalErrorMsg:u,hasError:p,internalErrorMsg:h,steps:f}=c;return a.jsxs(T,{children:[p?a.jsx(mke,{errorMsg:r?h:u,id:l,status:f}):a.jsxs(a.Fragment,{children:[a.jsxs(I,{component:"span",variant:"caption",children:["Meta id: ",l]}),a.jsx("br",{}),a.jsx(I,{variant:"caption",sx:{pl:2},children:"No errors"})]}),d+1===i.length?null:a.jsx(St,{})]},l)})]}):r?`${n} (${e.ids.join(", ")})`:n;return a.jsx(gke,{title:o,children:a.jsx(I,{component:"div",variant:"body2",sx:{color:s?"error.main":"text.primary"},children:n})})},bke=[{field:"planName",headerName:"Plan name",renderCell:e=>a.jsx(xke,{row:e.row}),flex:1,minWidth:175},{field:"dateRange",headerName:"Plan Dates",sortComparator:die,flex:1.5,minWidth:200},{field:"objectiveName",headerName:"KPI(s)",sortable:!1,flex:1,minWidth:150},{field:"type",headerName:"Type",sortable:!1,renderCell:({value:e})=>Pr(e),flex:1,minWidth:90},{field:"budgetOrConversionValue",headerName:"Budget/Conversion",renderCell:e=>
259a.jsx(fke,{row:e.row}),flex:1,minWidth:185},{field:"creationDate",headerName:"Creation date",sortComparator:uie,flex:1,minWidth:145},{field:"username",headerName:"Created by",flex:1,minWidth:150},{field:"stateName",headerName:"Status",renderCell:e=>a.jsx(pke,{stateName:e.value}),sortable:!1,flex:1,minWidth:110},{field:"id",filterable:!1,headerName:"",renderCell:e=>a.jsx(hke,{row:e.row}),sortable:!1,width:70}],am={clickableRow:"row-is-clickable",errorRow:"row-has-error"},yke=({apiRef:e,loading:t})=>{const[n,r]=m.useState(""),s=m.useMemo(()=>gm(o=>{e.current.setQuickFilterValues(o.split(" ").filter(l=>l!==""))},150),[e]),i=o=>{const l=o.target.value;r(l),s(l)};return a.jsxs($,{direction:"row",justifyContent:"space-between",paddingBottom:3,children:[a.jsx(I,{variant:"subtitle1",children:"Plans"}),a.jsx(Qe,{children:a.jsx(ys,{inputProps:{"data-testid":"plan-list:search:input"},disabled:t,startAdornment:a.jsx(Mt,{sx:{color:"text.disabled",fontSize:20},children:a.jsx(er,{})}),onChange:i,placeholder:"Search",sx:{borderRadius:1,height:42,width:228,px:1.5,".MuiInputBase-inputAdornedStart":{pl:1.5,pr:0,height:24},"&.Mui-focused":{".MuiOutlinedInput-notchedOutline":{boxShadow:"none"}}},value:n})})]})},vke=({handleClose:e,open:t})=>{const{planListMpTrack:n}=Sg(),s=NF({handleClose:e,trackCreatePlan:()=>{n("batchUpload")}});return a.jsx(FF,{open:t,...s})},Cv=bs(Mn)(({theme:e})=>{const{action:t,primary:n,text:r,background:s}=e.palette,{spacing:i}=e,o={backgroundColor:s.paper,color:r.default,":hover":{[`&.${am.clickableRow}`]:{cursor:"pointer",backgroundColor:e.palette.mode==="dark"?s.brand.subtlest.hovered:n.light},[`&.${am.errorRow}`]:{cursor:"auto",backgroundColor:s.paper}}};return{border:"none",".MuiDataGrid-cell":{border:"none",paddingLeft:i(2.5),paddingRight:i(1),"&:focus":{outline:"none"},"&:focus-within":{outline:"none"}},".MuiDataGrid-columnHeader":{paddingLeft:i(2),paddingRight:i(2),":focus-within":{outline:"none"}},".MuiDataGrid-columnHeaders":{backgroundColor:s.tableHeader,border:"none",paddingLeft:i(.5)},".MuiDataGrid-columnHeaderTitleContainerContent":{fontSize:12,height:18,textTransform:"uppercase"},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-footerContainer":{border:"none",height:40,minHeight:40},".MuiDataGrid-iconButtonContainer":{paddingLeft:i(1.5)},".MuiDataGrid-row":{borderRadius:i(1),...o},".MuiDataGrid-row:nth-of-type(even)":{...o},".MuiTablePagination-actions":{color:t.active},".MuiTablePagination-displayedRows":{fontSize:12,fontWeight:500},".MuiTablePagination-select":{fontSize:12,fontWeight:500},".MuiTablePagination-selectLabel":{color:r.secondary,fontSize:12,fontWeight:500},".MuiTablePagination-toolbar":{borderRadius:i(1)},".MuiToolbar-root":{height:40,minHeight:40}}});Cv.defaultProps={...Cv.defaultProps,columnHeaderHeight:50,disableColumnMenu:!0,disableColumnPinning:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,getRowSpacing:()=>({top:0,bottom:8}),pageSizeOptions:[10,25,50],pagination:!0,rowHeight:60};const Cke=({data:e})=>{const{handleCreatePlan:t,handleViewPlan:n,plansLoading:r}=Sg(),s=zn(),[i,o]=m.useState({page:0,pageSize:10}),[l,c]=m.useState([]),[d,u]=m.useState(!1),p=()=>{u(!0)},h=g=>{const{row:x}=g;return Ku(x)?am.errorRow:am.clickableRow},f=async()=>{u(!1)};return a.jsxs(T,{"data-testid":"plan-list:page:container",sx:{display:"flex",flexDirection:"column",minWidth:600,width:"100%"},children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",pb:1},children:[a.jsx(Xt,{title:"My Plans"}),a.jsx(ar,{authorized:"Planning.NewPlan",children:a.jsxs(T,{sx:{display:"flex",gap:2,height:36},children:[a.jsx(re,{color:"secondary","data-testid":"plan-list:create-from-xlsx:button",variant:"outlined",onClick:p,startIcon:a.jsx(tC,{size:16}),children:"Create from .xlsx"}),a.jsx(re,{"data-testid":"plan-list:create-plan:button",variant:"contained",onClick:t,sx:{py:.75,px:2},children:"Create a Plan"})]})})]}),a.jsx(I,{variant:"body2",sx:{pb:5},children:"Optimize your spend recommendations with AI support to maximize conversions for user-scenarios."}),a.jsxs(T,{sx:{height:785},children:[a.jsx(yke,{apiRef:s,loading:r&&!e.length}),a.jsx(Cv,{apiRef:s,columns:bke,getRowClassName:h,loading:r&&!e.length,onRowClick:n,onRowSelectionModelChange:g=>{c(g)},onPaginationModelChange:o,paginationModel:i,rows:e,rowSelectionModel:l,slots:{loadingOverlay:Cs}})]}),a.jsx(T,{height:100}),a.jsx(vke,{handleClose:f,open:d})]})},wke=({data:e,handleCreatePlan:t,handleDeletePlans:n,handleDuplicatePlan:r,handleEditPlan:s,handleUpdatePlanState:i,handleViewPlan:o,isInternalUser:l,plansLoading:c,planListMpTrack:d,userId:u})=>{const p=m.useMemo(()=>({handleCreatePlan:t,handleDeletePlans:n,handleDuplicatePlan:r,handleEditPlan:s,handleUpdatePlanState:i,handleViewPlan:o,isInternalUser:l,plansLoading:c,planListMpTrack:d,userId:u}),[t,n,r,s,i,o,l,c,d,u]);return a.jsx(ZF.Provider,{value:p,children:a.jsx(Cke,{data:e})})},Ske=()=>{const e=en(),{plans:t,isLoading:n,isInternalUser:r,userId:s}=OF(),i=uke(),{handleDeletePlans:o,handleDuplicatePlan:l,handleEditPlan:c,handleUpdatePlanState:d}=PF("myPlans"),u=()=>{i("create"),e("/planning/new-plan")},p=async({row:h})=>{i("view");const[f,g]=h.ids;
259Ku(h)||!(f&&g)||e("/planning/view-plan",{searchParams:{calcId:String(f),optId:String(g)}})};return a.jsx(wke,{data:t,handleCreatePlan:u,handleDeletePlans:o,handleDuplicatePlan:l,handleEditPlan:c,handleUpdatePlanState:d,handleViewPlan:p,isInternalUser:r,planListMpTrack:i,plansLoading:n,userId:s})},jke={audience:"Audience Filter",email:"Email Results",tab:"Tab Change",table:"Table Action"},kke=()=>pr({actionMap:jke,eventName:"planResults"}),e$=m.createContext(null),Es=()=>m.useContext(e$),Eke=88,_ke="Ask Darwin how this plan was optimized.",Tke=({briefSummaryText:e,isLoading:t,optimizedMetaId:n,planName:r,plannedMetaId:s})=>{const{loadSession:i,sendPrompt:o,subscribe:l}=Fm(),[c,d]=m.useState(null),u=m.useRef(!1),p=`${s}-${n}`,h=c?.planKey===p,f=h?c.sessionId:null;m.useEffect(()=>l("SESSION_STARTED",({sessionId:x})=>{u.current&&(u.current=!1,d(b=>b&&{...b,sessionId:x}))}),[l]);const g=()=>{if(h){f&&i({sessionId:f});return}const x={type:"plan",op:"explain_reasoning",planned_meta_id:s,optimized_meta_id:n,...r?{plan_name:r}:{}};o({prompt:`Explain the reasoning behind the optimization of ${r?`"${r}"`:"this plan"}.`,options:{jsonContext:[x]}}),u.current=!0,d({planKey:p,sessionId:null})};return t?a.jsx(fe,{height:Eke,variant:"rounded"}):a.jsx(cA,{children:a.jsx(Ue,{children:a.jsxs($,{direction:"row",sx:{alignItems:"center",gap:2,justifyContent:"space-between"},children:[a.jsxs($,{direction:"row",sx:{alignItems:"center",gap:2,minWidth:0},children:[a.jsx(T,{sx:{alignItems:"center",bgcolor:"darwinSurface.accent",borderRadius:1.5,display:"flex",flexShrink:0,height:40,justifyContent:"center",width:40},children:a.jsx(T,{component:zU,sx:{color:"darwinSurface.icon"},size:20})}),a.jsxs($,{sx:{gap:.5,minWidth:0},children:[a.jsx(I,{sx:{color:"darwinSurface.textMuted"},variant:"overline",children:"Darwin AI · Plan Commentary"}),a.jsx(I,{variant:"body1",children:e||_ke})]})]}),a.jsx(re,{endIcon:a.jsx(uA,{size:16}),onClick:g,variant:"contained",sx:{flexShrink:0},children:h?"Asked Darwin":"Explain reasoning"})]})})})},Ike=[["50%","75%"],["33%","40%"],["55%","50%"],["10%","15%"],["40%","45%"]],Dke=()=>a.jsx($,{sx:{height:"375px",width:"100%",ml:"75px",pt:"15px"},direction:"column",spacing:1.5,children:Ike.map(([e,t],n)=>
259a.jsxs(T,{sx:{height:55,display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[a.jsx(fe,{variant:"rounded",animation:"pulse",height:25,width:e}),a.jsx(fe,{variant:"rounded",animation:"wave",height:25,width:t})]},n))}),Ake=rt(ua)(({theme:e})=>({".apexcharts-tooltip":{backgroundColor:`${e.palette.background.paper} !important`,border:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`},".apexcharts-tooltip-title":{backgroundColor:`${e.palette.surface.tertiary} !important`,borderBottom:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`}})),yI=({data:e,isLoading:t=!1,options:n,title:r})=>a.jsx(Ve,{sx:{minHeight:"420px",maxHeight:"650px",minWidth:"49%"},children:a.jsxs(Ue,{sx:{p:"5px !important"},children:[a.jsx(I,{sx:{pl:"19px",pt:"27px"},variant:"subtitle1",component:"div",children:r}),t?a.jsx(Dke,{}):a.jsx(T,{sx:{mt:"-20px"},children:a.jsx(Ake,{height:Math.max(375,Math.min(600,40*(e[0]?.data?.length||0))),options:n,series:e,type:"bar",width:"95%"})})]})}),Mke={budget:0,conversion_target:0,duration_end:"",duration_start:"",plan_end:"",plan_start:"",id:0,identity_id:0,objective_name:"",plan_name:"",state_id:$n.Actioned},Rke=e=>e.map(t=>({...t,deltaConversions:t.optConversions-t.plannedConversions,deltaSpend:t.optSpend-t.plannedSpend})).sort((t,n)=>n.deltaConversions-t.deltaConversions).slice(0,3),Nke=e=>{const t=e.map(l=>({x:l.typeName,y:l.plannedConversions})),n=e.map(l=>({x:l.typeName,y:l.optConversions})),r=[{name:"Planned",data:t},{name:"Optimized",data:n}],s=e.map(l=>({x:l.typeName,y:l.plannedSpend})),i=e.map(l=>({x:l.typeName,y:l.optSpend}));return[r,[{name:"Planned",data:s},{name:"Optimized",data:i}]]},Oke=e=>{const t=e.reduce((d,u)=>d+u.optSpend,0),n=e.reduce((d,u)=>d+u.optConversions,0),r=e.reduce((d,u)=>d+u.plannedConversions,0),s=t/n,o=e.reduce((d,u)=>d+u.plannedSpend,0)/r,l=(n-r)/r,c=(s-o)/o;return{budget:t,projConversions:n,projCPC:s,conversionsPerc:l,cpcPerc:c}},Ks=({options:e,hideZero:t=!1})=>n=>{const r=Number(n);return Number.isNaN(r)||t&&r<=0?"":new Intl.NumberFormat("en",e).format(r)},t$=e=>({chart:{type:"bar",foreColor:e.palette.grey[600],toolbar:{show:!1},zoom:{enabled:!1}},colors:[],dataLabels:{enabled:!1},fill:{opacity:1},grid:{show:!1},legend:{position:"top",horizontalAlign:"right",markers:{radius:8}},noData:{text:"No data available"},plotOptions:{bar:{horizontal:!0,borderRadius:4}},stroke:{colors:["transparent"],width:2.5},tooltip:{x:{formatter:t=>String(t)},y:{formatter:Ks({options:{maximumFractionDigits:0}})}},xaxis:{axisBorder:{show:!1},axisTicks:{show:!1},labels:{formatter:Ks({options:{notation:"compact"},hideZero:!0})}}}),Pke=e=>({...t$(e)}),Lke=(e,t="USD")=>{const n=t$(e);return{...n,tooltip:{...n.tooltip,y:{formatter:Ks({options:{style:"currency",currency:t}})}},xaxis:{...n.xaxis,labels:{formatter:Ks({options:{maximumFractionDigits:0,notation:"compact",style:"currency",currency:t},hideZero:!0})}}}},Fke=()=>a.jsx(a.Fragment,{children:Array(3).fill(null).map((e,t)=>a.jsx(Ve,{sx:{flexGrow:1},children:a.jsxs(Ue,{children:[a.jsxs($,{alignItems:"center",direction:"row",justifyContent:"flex-start",paddingBottom:1.5,spacing:1,children:[a.jsx(fe,{variant:"circular",height:"24px",width:"24px"}),a.jsx(fe,{variant:"text",width:"50%"})]}),a.jsx(fe,{sx:{fontSize:"24px"},variant:"text",width:200}),a.jsxs(T,{sx:{display:"grid",gap:{xs:1,lg:3,lx:5},gridTemplateColumns:"1fr 1px 1fr",pt:1},children:[a.jsxs(T,{children:[a.jsx(fe,{variant:"text",width:100}),a.jsx(fe,{variant:"text",width:100})]}),a.jsx(St,{flexItem:!0,orientation:"vertical",variant:"fullWidth"}),a.jsxs(T,{children:[a.jsx(fe,{variant:"text",width:100}),a.jsx(fe,{variant:"text",width:100})]})]})]})},t))}),vI=({colorStyle:e,label:t})=>{const s=e==="neutral"?"default":e==="success"?"success":"error";return a.jsx(ut,{color:s,sx:{height:"24px",ml:0,".MuiChip-label":{px:1,fontSize:12}},label:t})},$ke=({up:e})=>a.jsx(as,{sx:{backgroundColor:"background.brand.subtle.default",color:"text.default",height:"24px",width:"24px"},children:e?a.jsx(uu,{size:12}):a.jsx(hA,{size:12})}),Hp=new Intl.NumberFormat("en",{maximumFractionDigits:0}),zke=({recommendation:e})=>{const{engagementCurrency:t}=pe(),n=e.deltaSpend>=0,r=e.plannedSpend?Math.abs(100*e.deltaSpend/e.plannedSpend):0,s=`${e.deltaSpend>=0?"+":"-"}${Ci(Math.abs(e.deltaSpend),{options:{currency:t}})}`;return a.jsx(Ve,{sx:{flexGrow:1},children:a.jsxs(Ue,{children:[a.jsxs($,{alignItems:"center",direction:"row",justifyContent:"flex-start",paddingBottom:1.5,spacing:1,children:[a.jsx($ke,{up:n}),a.jsxs(I,{color:"text.secondary",sx:{fontSize:13,fontWeight:500,lineHeight:"18px",letterSpacing:".16px"},children:[n?"Increase":"Decrease"," spend by ",Hp.format(r),"%"]})]}),a.jsx(I,{component:"div",sx:{fontSize:18,fontWeight:600,lineHeight:"22px"},children:e.typeName}),a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:"1fr 1px 1fr",pt:2,gap:{xs:1,lg:3}},children:[a.jsxs($,{sx:{alignItems:"start",flexGrow:1},children:[a.jsxs($,{alignItems:"center",direction:"row",sx:{flexWrap:"wrap",columnGap:1},children:[a.jsxs($,{direction:"row",children:[a.jsx(Dl,{sx:{fontSize:"16px"}}),a.jsx(I,{component:"span",sx:{lineHeight:"22px"},variant:"subtitle2",children:Hp.format(e.optSpend)})]}),a.jsx(vI,{colorStyle:"neutral",label:s})]}),a.jsx(I,{color:"text.secondary",sx:{letterSpacing:.5},variant:"caption",children:"New spend"})]}),a.jsx(St,{flexItem:!0,orientation:"vertical",variant:"fullWidth"}),a.jsxs($,{sx:{flexGrow:1},children:[a.jsxs($,{direction:"row",sx:{alignItems:"end",flexWrap:"wrap",columnGap:1},children:[a.jsx(I,{component:"span",variant:"subtitle2",children:Hp.format(e.optConversions)}),a.jsx(vI,{colorStyle:e.deltaConversions>=0?"success":"error",label:`+${Hp.format(e.deltaConversions)}`})]}),a.jsx(I,{color:"text.secondary",sx:{letterSpacing:.5},variant:"caption",children:"New conversions"})]})]})]})})},Bke=new Intl.NumberFormat("en",{maximumFractionDigits:2}),Uke=new Intl.NumberFormat("en",{maximumFractionDigits:0}),CI=new Intl.NumberFormat("en",{style:"percent",minimumFractionDigits:1,maximumFractionDigits:1}),Vke=new Intl.NumberFormat("en",{notation:"compact"}),ob=({title:e,value:t,format:n,type:r,secondaryText:s,isLoading:i,isUnavailable:o=!1,inverseColor:l=!1})=>{const{palette:c}=Re();let d=t.toFixed(0);switch(n){case"money":d=Bke.format(t);break;case"discrete":d=Uke.format(t);break;case"compact":d=Vke.format(t);break;default:d=t.toString()}const u=s!==void 0&&s>=0,p=l?!u:u,h=c.icon.default;return a.jsx(Ve,{sx:{flexGrow:1},children:a.jsxs(Ue,{children:[a.jsx(I,{color:"text.secondary",variant:"caption",sx:{pb:1},children:e}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",flexWrap:"wrap",alignItems:"center",gap:1},children:[a.jsxs(T,{display:"flex",flexDirection:"row",children:[n==="money"?a.jsx(Dl,{sx:{fontSize:22,fontWeight:600,color:"neutral.400"}}
259):null,i?a.jsx(fe,{sx:{fontSize:"24px"},variant:"text",width:100}):o?a.jsx(I,{color:"text.secondary",sx:{fontSize:22,fontWeight:600,pl:"5px"},children:"Not Available"}):a.jsx(I,{sx:{fontSize:22,fontWeight:600,pl:"5px"},children:d})]}),r==="chip"&&s&&i?a.jsx(fe,{sx:{fontSize:"24px"},variant:"text",width:80}):r==="chip"&&s&&!o?a.jsx(ut,{color:p?"primary":"error",sx:{height:"24px",pl:.5,".MuiChip-label":{px:1}},label:u?`+${CI.format(s)}`:CI.format(s),icon:u?a.jsx(uu,{color:h,size:18}):a.jsx(hA,{color:h,size:18})}):null]})]})})},Wke=()=>{const{planResults:e,planResultsLoading:t,targetAudience:n,targetAudienceLoading:r}=Es(),s=!r&&!n,{budget:i,projConversions:o,projCPC:l,conversionsPerc:c,cpcPerc:d}=m.useMemo(()=>Oke(e),[e]);return a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:{xs:1,lg:3,xl:5}},children:[a.jsx(ob,{title:"Total Budget",value:i,format:"money",isLoading:t,isUnavailable:s}),a.jsx(ob,{title:"Optimized Conversions",value:o,format:"discrete",type:"chip",secondaryText:c,isLoading:t,isUnavailable:s}),a.jsx(ob,{title:"Optimized Spend Per Conversion",value:l,type:"chip",format:"money",secondaryText:d,isLoading:t,isUnavailable:s,inverseColor:!0})]})},Hke=()=>{const{plan:e,planLoading:t,kpiScalar:n}=Es(),{planProgress:r,planStatus:s}=m.useMemo(()=>e?RF(e):{planProgress:null,planStatus:null},[e]),{type:i,value:o}=m.useMemo(()=>{const{budget:l,conversion_target:c}=e;return c?{type:"conversion",value:c}:{type:"budget",value:l}},[e]);return t?a.jsx(fe,{sx:{fontSize:24,width:200},variant:"text"}):a.jsxs(T,{sx:{display:"flex",overflow:"hidden",alignItems:"center",gap:1},children:[a.jsx($w,{stateName:s}),a.jsx(OSe,{stateName:r}),a.jsx(UF,{type:i}),a.jsx(BF,{type:i,value:o,kpiScalar:n})]})},qke=e=>e?Object.fromEntries(e.map(t=>[t,t])):{},Gke=e=>{const t=[e.plan_start||e.duration_start,e.plan_end||e.duration_end].map(n=>Z(n)).filter(n=>n.isValid()).map(n=>n.format("MMM D, YYYY"));return t.length===2?t.join(" - "):"Unknown"},Yke=e=>{if(e?.model_info&&e?.model_info.model_coverage[0]&&e?.model_info.model_coverage[1]){const t=[e?.model_info.model_coverage[0],e?.model_info.model_coverage[1]].map(n=>{const r=Z(n);return r.isValid()?r.format("MMM D, YYYY"):""});return t.length===2?t.join(" - "):"Unknown"}return"Unknown"},Kke=()=>{const{metadataResults:e,plan:t,planLoading:n}=Es(),{objective_name:r}=t,s=m.useMemo(()=>Gke(t),[t]),i=m.useMemo(()=>Yke(e),[e]);return a.jsxs($,{sx:{gap:2},children:[a.jsx(Hke,{}),a.jsx(zF,{dateRangeString:s,kpiString:r,loading:n,modelDatesString:i})]})},Qke=a.jsx(ut,{icon:a.jsx(Si,{size:16}),label:"Click below to get a secure email containing an .xlsx results file",color:"primary",sx:{fontSize:14,fontWeight:400,lineHeight:"24px",px:1,py:2.5,mt:2,".MuiChip-label":{pl:2}}}),Jke=({downloadInitialized:e,initDownloadPlan:t,loading:n})=>{const r=ct(),[s,i]=m.useState(!1),o=async()=>{await t(),r()&&i(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(be,{title:n?"Initializing data":e?"Results email sent":"",children:a.jsx("span",{children:a.jsx(re,{sx:{height:"100%",whiteSpace:"nowrap"},color:"secondary","data-testid":"plan-results:download-plan:button",variant:"outlined",disabled:e||n,onClick:()=>{i(!0)},startIcon:a.jsx(bl,{size:16}),size:"small",children:"Download Plan"})})}),a.jsx(mt,{acceptLabel:"Send Email",body:Qke,handleAccept:o,handleClose:()=>{i(!1)},open:s,testId:"plan-results:download-dialog",title:"Download Plan"})]})},Xke=()=>{const{activeTab:e,calcId:t,handleEditPlan:n,handleDeletePlans:r,handleDuplicatePlan:s,handleDownloadPlan:i,handleUpdatePlanState:o,handleUpdateTargetAudience:l,isInternalUser:c,optId:d,plan:u,planLoading:p,planResultsMpTrack:h,state:{tableLoading:f},targetAudience:g,targetAudienceLoading:x,targetAudienceOptions:b,userId:y}=Es(),[v,C]=m.useState(!1),w=m.useMemo(()=>qke(b),[b]),S=y===u.identity_id,E=u.state_id===$n.Actioned,k=!c&&!S||E,j=e==="0",_=async()=>{C(!0),await i()};return a.jsxs(T,{sx:{display:"flex",flexWrap:{xs:j?"wrap":"nowrap",lg:"nowrap"},justifyContent:"space-between",alignItems:"center",columnGap:2,rowGap:.5},children:[a.jsx(T,{sx:{display:"flex",overflow:"hidden",alignItems:"center",gap:2,height:40},children:p?a.jsx(fe,{sx:{fontSize:24,width:400},variant:"text"}):a.jsx(I,{sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},variant:"h5",children:u.plan_name||""})}),a.jsxs(T,{sx:{display:"flex",gap:2,height:40},children:[j?a.jsxs(a.Fragment,{children:[a.jsx(Ar,{"data-testid":"plan-results:target-audience:select",sx:{width:"170px"},disabled:p,isLoading:x,menuItemStartIcon:a.jsx(ym,{size:"16px"}),onChange:({target:D})=>{l(D.value),h("audience"),C(!1)},options:w,value:g}),a.jsx(St,{flexItem:!0,orientation:"vertical",variant:"middle"}),a.jsx(Jke,{downloadInitialized:v,initDownloadPlan:_,loading:f})]}):null,a.jsx($F,{disabled:p,disableDuplicate:!1,disableEdit:k,handleEditPlan:n,handleDeletePlans:r,handleDuplicatePlan:s,handleUpdatePlanState:o,isInternalUser:c,row:{id:t,identityId:u.identity_id,ids:[t,d],planName:u.plan_name||"",stateId:u.state_id},userId:y,variant:"outlined"})]})]})},Zke=()=>{const{calcId:e,metadataLoading:t,metadataResults:n,optId:r}=Es();return a.jsxs($,{sx:{pb:4},children:[a.jsxs($,{sx:{rowGap:2,pb:4},children:[a.jsx(Xke,{}),a.jsx(Kke,{})]}
259),a.jsxs($,{sx:{gap:2},children:[a.jsx(Wke,{}),e&&r?a.jsx(ar,{authorized:"Chat",children:a.jsx(Tke,{briefSummaryText:n?.brief_summary_text??null,isLoading:t,optimizedMetaId:r,planName:n?.name??null,plannedMetaId:e})}):null]})]})},e1e=({value:e})=>{if(!e)return null;const t=e===void 0?"":new Intl.NumberFormat("en",{maximumFractionDigits:0}).format(e),n=e>0,r=a.jsx(I,{variant:"overline",children:`${n?"+":""}${t}`});return a.jsx(be,{title:e,children:a.jsx(ut,{color:n?"success":"error",icon:n?a.jsx(fA,{}):a.jsx(nC,{}),label:r,sx:{height:"24px",mr:1,".MuiChip-label":{pl:.75}}})})},Uc=({value:e})=>a.jsxs($,{alignItems:"center",direction:"row",sx:{color:"text.secondary"},children:[a.jsx(BU,{size:19}),a.jsx(I,{sx:{color:"text.primary",fontSize:"12px",fontWeight:500,ml:"5px"},component:"span",children:e})]}),qp=({fractionDigits:e=0,isCurrency:t=!1,isPercent:n=!1,value:r})=>{const{engagementCurrency:s}=pe();if(!r)return null;const i={style:"currency",currency:s},o=r===void 0?"":new Intl.NumberFormat("en",{...t?i:{},...n?{style:"percent"}:{},minimumFractionDigits:e,maximumFractionDigits:e}).format(r),l=r>0,c=a.jsx(I,{variant:"overline",children:`${l?"+":""}${o}`});return a.jsx(be,{title:r,children:a.jsx(ut,{icon:l?a.jsx(fA,{}):a.jsx(nC,{}),label:c,sx:{height:"24px",".MuiChip-label":{pl:.75}}})})},wI=({item:e,applyValue:t})=>{const n=r=>{t({...e,value:Number(r.target.value)/100,userInput:Number(r.target.value)})};return a.jsx(De,{id:"percentage-filter-input-field",label:"Value",value:Number(e.userInput)===0||Number(e.userInput)?Number(e.userInput):"",placeholder:"Filter value",type:"number",onChange:r=>{n(r)},InputProps:{endAdornment:"%"},InputLabelProps:{shrink:!0},variant:"standard"})},t1e=[{label:"<=",value:"<=",getApplyFilterFn:e=>!e.field||!e.value||!e.operator?null:t=>Number(t.value)<=Number(e.value),InputComponent:wI},{label:">=",value:">=",getApplyFilterFn:e=>!e.field||!e.value||!e.operator?null:t=>Number(t.value)>=Number(e.value),InputComponent:wI}],Vw={alwaysVisible:!1,flex:1,minWidth:150},n1e={...Vw,customType:"pivot",filterOperators:Em().filter(e=>Za.includes(e.value))},kr={...Vw,customType:"number",type:"number",filterOperators:_m().filter(e=>Lh.includes(e.value))},lb={...Vw,customType:"number",type:"number",filterOperators:t1e},r1e=[{...kr,field:"impressions",headerName:"Impressions",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e.value})},{...kr,field:"cpm",headerName:"CPM",renderCell:e=>a.jsx(ft,{isCurrency:!0,fractionDigits:2,value:e.value}),minWidth:100},{...kr,field:"initial_plan_spend",headerName:"Spend",renderCell:e=>a.jsx(ft,{isCurrency:!0,fractionDigits:0,value:e.value})},{...kr,field:"optimized_plan_spend",headerName:"Optimized Spend",renderCell:e=>a.jsx(ft,{isCurrency:!0,fractionDigits:0,value:e.value}),minWidth:160},{...kr,field:"delta_spend",headerName:"Delta Spend",renderHeader:()=>a.jsx(Uc,{value:"spend"}),renderCell:e=>a.jsx(qp,{isCurrency:!0,value:e.value})},{...kr,field:"initial_plan_conversions",headerName:"Conversions",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e.value})},{...kr,field:"optimized_plan_conversions",headerName:"Optimized Conversions",renderCell:e=>a.jsx(ft,{fractionDigits:0,value:e.value}),minWidth:200},{...kr,field:"delta_conversions",headerName:"Delta Conversions",renderHeader:()=>a.jsx(Uc,{value:"conversions"}),renderCell:e=>a.jsx(e1e,{value:e.value}),minWidth:200},{...lb,field:"initial_reach",headerName:"Reach",renderCell:e=>a.jsx(ft,{isPercent:!0,value:e.value,fractionDigits:0}),minWidth:100},{...lb,field:"optimized_reach",headerName:"Optimized Reach",renderCell:e=>a.jsx(ft,{isPercent:!0,value:e.value,fractionDigits:0}),minWidth:175},{...lb,field:"delta_reach",headerName:"Delta Reach",renderHeader:()=>a.jsx(Uc,{value:"Reach"}),renderCell:e=>a.jsx(qp,{fractionDigits:0,value:e.value?e.value:0,isPercent:!0}),minWidth:125},{...kr,field:"initial_frequency",headerName:"Frequency",renderCell:e=>a.jsx(ft,{fractionDigits:2,value:e.value}),minWidth:125},{...kr,field:"optimized_frequency",headerName:"Optimized Frequency",renderCell:e=>a.jsx(ft,{fractionDigits:2,value:e.value}),minWidth:200},{...kr,field:"delta_frequency",headerName:"Delta Frequency",renderHeader:()=>a.jsx(Uc,{value:"Frequency"}),renderCell:e=>a.jsx(qp,{fractionDigits:2,value:e.value})},{...kr,field:"initial_spend_per_conversion",headerName:"Spend Per Conversion",renderCell:e=>a.jsx(ft,{isCurrency:!0,fractionDigits:2,value:e.value}),minWidth:200},{...kr,field:"optimized_spend_per_conversion",headerName:"Optimized Spend Per Conversion",renderCell:e=>a.jsx(ft,{isCurrency:!0,fractionDigits:2,value:e.value}),minWidth:275},{...kr,field:"delta_spend_per_conversion",headerName:"Delta Spend Per Conversion",renderHeader:()=>a.jsx(Uc,{value:"Spend Per Conversion"}),renderCell:e=>a.jsx(qp,{isCurrency:!0,fractionDigits:2,value:e.value}),minWidth:225}],s1e=e=>({...n1e,field:e.value,headerName:e.label}),i1e=e=>[...e.map(n=>s1e(n)),...r1e],a1e=[{label:"Account ID",value:"account_id"},{label:"Account Name",value:"account_name"},{label:"Ad Group ID",value:"adgroup_id"},{label:"Ad Group Name",value:"adgroup_name"},{label:"Campaign Name",value:"campaign_name"},{label:"Country",value:"country_name"},{label:"Data Source",value:"datasource_name"},{label:"Media Market",value:"market_name"},{label:"Media Type",value:"type_name"},{label:"Placement Name",value:"name"},{label:"Platform",value:"platform_name"},{label:"Tactic",value:"tactic_name"},{label:"Vehicle",value:"vehicle_name"},{label:"Vendor",value:"vendor_nice_id"}],o1e=10,l1e=["cpm","initial_plan_spend","optimized_plan_spend","delta_spend","initial_plan_conversions","optimized_plan_conversions","delta_conversions"],c1e=["type_name"],d1e=[{field:"delta_conversions",sort:"desc"}],wv={selectedNumberFields:[...l1e],selectedPivots:[...c1e],sortModel:[...d1e]},u1e=()=>{const e=ct(),{calcId:t,dispatch:n,kpiScalar:r,optId:s,planResultsMpTrack:i,targetAudience:o,state:l}=Es(),{pivotTableRef:c}=l,[d]=D3(),[u]=A3(),{engagementNiceId:p}=pe(),h=m.useCallback(async x=>(i("table",{pivots:!0}),n({type:"tableLoading",value:!0}),"error"in await u({aggs:x,calc_id:t,engagement_nice_id:p,kpi_scalar:r,opt_id:s,target_audience:o})?{error:!0}:{error:!1}),[t,u,n,p,r,s,i,o]),f=m.useCallback(async x=>{const{filterModelItems:b,limit:y,offset:v}=x,C=Xje(x,t);n({type:"tableLoading",value:!0});const{data:w,error:S}=await d(C);if(S||!w)return e()&&n({type:"tableLoading",value:!1}),{error:!0};if(e()){const{media:E}=w,k=E[0]?.totalRows??0,j={query:!0,limit:y,offset:v};C.search&&(j.search=!0),b.length&&(j.filter=!0),C.sort?.length&&(j.sort=!0),i("table",j),n({type:"data",value:E}),n({type:"currentTotalRows",value:k}),n({type:"tableLoading",value:!1})}return{error:!1}},[t,n,e,i,d]),g=async()=>{const x=c?.current.state.selectedPivots||wv.selectedPivots,b=c?.current.state.rowsPerPage||o1e,y=c?.current.state.sortModel||wv.sortModel,v=c?.current.state.search||"",C=c?.current.state.filterModel.items||[];await h(x),e()&&await f({limit:b,offset:0,search:v,sortModel:y,filterModelItems:C})};return m.useEffect(()=>{o&&g()},[o]),{handleChangePivots:h,handleGetTableData:f}},p1e=()=>{const{dispatch:e,state:t}=Es(),{currentTotalRows:n,data:r,tableLoading:s}=t,{pivotOptions:i}=O0(a1e,{filterFn:({active:u,dimension_type:p})=>u&&p==="media"}),o=W0(),{handleChangePivots:l,handleGetTableData:c}=u1e(),d=m.useMemo(()=>i1e(i),[i]);return m.useEffect(()=>{t.pivotTableRef||e({type:"pivotTableRef",value:o})},[t.pivotTableRef]),a.jsxs($,{direction:"column",justifyContent:"space-between",paddingBottom:3,children:[a.jsx(I,{sx:{pb:3},variant:"subtitle1",children:"Plan Details"}),a.jsx(G0,{columns:d,data:r,initialState:wv,loading:s,onChangePivots:l,onGetData:c,pivotOptions:i,pivotTableRef:o,totalRows:n})]})},h1e="Reach and frequency data is not available for this plan. Please edit and rerun your plan to generate new data.",f1e="Planner prioritizes campaign conversion optimization. Consequently, you may encounter instances where the optimized Reach and Frequency for certain media types are lower than the initial figures.",n$=e=>Ks({options:{maximumFractionDigits:0,style:"currency",currency:e}}),m1e=Ks({options:{maximumFractionDigits:2}}
259),g1e=Ks({options:{maximumFractionDigits:0,style:"percent"}}),Sv=(e,t="USD")=>{const n=n$(t);return{chart:{type:"line",foreColor:e.palette.grey[600],toolbar:{show:!1},zoom:{enabled:!1}},colors:[],dataLabels:{enabled:!1},grid:{show:!1},legend:{position:"top",horizontalAlign:"left",markers:{radius:8},onItemClick:{toggleDataSeries:!1}},markers:{size:7},noData:{text:"No data available"},stroke:{curve:"smooth",width:3},tooltip:{shared:!1,intersect:!0,x:{formatter:(r,{seriesIndex:s,w:i})=>i.config.series[s].name},y:{formatter:(r,{seriesIndex:s,dataPointIndex:i,w:o})=>{const{data:l}=o.config.series[s],{x:c,y:d}=l[i],u=n(c),p=m1e(d);return`<span style="font-weight: normal">Spend: </span>${u}<br /><span style="font-weight: normal">Frequency: </span>${p}`},title:{formatter:()=>""}},marker:{show:!1}},xaxis:{axisBorder:{show:!1},axisTicks:{show:!1},labels:{formatter:Ks({options:{notation:"compact",style:"currency",currency:t},hideZero:!0})},tooltip:{enabled:!1},type:"numeric"},yaxis:{labels:{formatter:Ks({options:{notation:"compact",maximumFractionDigits:2},hideZero:!0})}}}},SI=(e,t="USD")=>{const n=n$(t),r=Sv(e,t);return{...r,tooltip:{...r.tooltip,y:{formatter:(s,{seriesIndex:i,dataPointIndex:o,w:l})=>{const{data:c}=l.config.series[i],{x:d,y:u}=c[o],p=n(d),h=g1e(u);return`<span style="font-weight: normal">Spend: </span>${p}<br /><span style="font-weight: normal">Reach: </span>${h}`},title:{formatter:()=>""}}},yaxis:{labels:{formatter:Ks({options:{notation:"compact",style:"percent"},hideZero:!0})}}}},jI=rt(ua)(({theme:e})=>({".apexcharts-tooltip":{backgroundColor:`${e.palette.background.paper} !important`,border:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`},".apexcharts-tooltip-title":{backgroundColor:`${e.palette.surface.tertiary} !important`,borderBottom:`1px solid ${e.palette.border.default} !important`,color:`${e.palette.text.primary} !important`}})),x1e=({reach:e,reachChartOptions:t,frequency:n,frequencyChartOptions:r})=>a.jsxs($,{alignItems:"stretch",direction:{xs:"column",lg:"row"},gap:1,justifyContent:"stretch",children:[a.jsxs(T,{sx:{flex:1},children:[a.jsx(I,{sx:{fontWeight:500,fontSize:"16px",marginBottom:1,marginLeft:2},children:"Reach"}),a.jsx(jI,{height:250,options:t,series:e,type:"line",width:"100%"})]}),a.jsxs(T,{sx:{flex:1},children:[a.jsx(I,{sx:{fontWeight:500,fontSize:"16px",marginBottom:1,marginLeft:2},children:"Frequency"}),a.jsx(jI,{height:250,options:r,series:n,type:"line",width:"100%"})]})]}),cb=({label:e,optimizedValue:t,initialValue:n})=>a.jsxs(T,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(I,{sx:{fontWeight:500,fontSize:"12px",color:"text.secondary"},children:e}),a.jsxs(T,{sx:{display:"flex",alignItems:"center",ml:"8px"},children:[a.jsx(I,{sx:{fontWeight:500,fontSize:"12px",color:"text.secondary"},children:"Optimized "}),a.jsx(I,{sx:{fontWeight:500,fontSize:"12px",color:"text.default"},children:t}),a.jsx(St,{orientation:"vertical",sx:{mx:"8px"},flexItem:!0}),a.jsx(I,{sx:{fontWeight:500,fontSize:"12px",color:"text.secondary"},children:"Planned "}),a.jsx(I,{sx:{fontWeight:500,fontSize:"12px",color:"text.default"},children:n})]})]}),b1e=({title:e,data:t,expanded:n=!1})=>{const{engagementCurrency:r}=pe(),{optData:s,plannedData:i}=t,o=i.find(u=>u.scalar===1),l=new Intl.NumberFormat(void 0,{style:"percent",minimumFractionDigits:0,maximumFractionDigits:0}),c=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function d(u){return u<.01?"<0.01":c.format(u)}return a.jsxs($,{width:"100%",children:[a.jsxs(T,{sx:{display:"flex",alignItems:"center",p:"24px"},children:[a.jsx(yl,{style:{transform:n?"rotate(90deg)":"none",alignSelf:"center",width:24,height:24}}),a.jsx(I,{sx:{fontSize:"18px",fontWeight:600,flexGrow:1,pl:1},children:e}),a.jsx(cb,{label:"Spend",optimizedValue:s[0]?Ci(s[0].spend,{options:{currency:r,notation:"compact"}}):"N/A",initialValue:o?Ci(o.spend,{options:{currency:r,notation:"compact"}}):"N/A"})]}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",backgroundColor:"surface.tertiary",borderRadius:"6px",p:"8px 16px"},children:[a.jsx(T,{sx:{width:"50%"},children:a.jsx(cb,{label:"Reach",optimizedValue:s[0]?l.format(s[0].reach):"N/A",initialValue:o?l.format(o.reach):"N/A"})}),a.jsx(T,{sx:{width:"50%",pl:"20px"},children:a.jsx(cb,{label:"Frequency",optimizedValue:s[0]?d(s[0].frequency):"N/A",initialValue:o?d(o.frequency):"N/A"})})]})]})},y1e=e=>{const t=[{name:"Planned",data:e.plannedData.map(s=>({x:s.spend,y:s.reach}))},{name:"Optimized",data:e.optData.map(s=>({x:s.spend,y:s.reach}))}],n=[{name:"Planned",data:e.plannedData.map(s=>({x:s.spend,y:s.frequency}))},{name:"Optimized",data:e.optData.map(s=>({x:s.spend,y:s.frequency}))}],r=e.plannedData.map((s,i)=>({seriesIndex:0,dataPointIndex:i,size:s.scalar===1?9:0})).filter(s=>s.size===0);return{name:e.aggValues,reach:t,frequency:n,hideMarkers:r}},v1e=({data:e,frequencyOptions:t,reachOptions:n,index:r})=>{const{name:s,reach:i,frequency:o,hideMarkers:l}=m.useMemo(()=>y1e(e),[e]),[c,d]=m.useState(r===0),u=m.useMemo(()=>({...t,markers:{...t.markers,discrete:l||[]}}),[t,l]),p=m.useMemo(()=>({...n,markers:{...n.markers,discrete:l||[]}}),[l,n]),h=()=>{d(f=>!f)};return a.jsxs(Ka,{expanded:c,sx:{marginBottom:2,borderRadius:"6px"},onChange:h,children:[a.jsx(Qa,{"aria-controls":"accordion-content",id:"accordion-header",sx:{"& .MuiAccordionSummary-content":{alignItems:"center"}},children:a.jsx(T,{width:"100%",display:"flex",alignItems:"center",children:a.jsx(b1e,{title:s,data:e,expanded:c})})}),a.jsx(Ja,{children:a.jsx(x1e,{reach:i,reachChartOptions:p,frequency:o,frequencyChartOptions:u})})]})},C1e=m.memo(v1e),w1e=({index:e})=>a.jsxs($,{width:"100%",children:[a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",p:"12px 24px 0 24px"},children:[a.jsxs(T,{sx:{display:"flex"},children:[a.jsx(yl,{style:{transform:e===0?"rotate(90deg)":"none",color:"disabled",alignSelf:"center",width:24,height:24,marginRight:7}}),a.jsx(fe,{variant:"text",sx:{fontSize:"2.1rem",width:110}})]}),a.jsx(T,{sx:{display:"flex",alignItems:"center"},children:a.jsx(fe,{variant:"text",sx:{fontSize:"1.5rem",width:230}})})]}),a.jsxs($,{alignItems:"stretch",direction:"row",gap:5,justifyContent:"stretch",pt:"12px",px:2,children:[a.jsx(T,{sx:{flex:1},children:a.jsx(fe,{variant:"text",sx:{fontSize:"1.5rem",width:215}})}),a.jsx(T,{sx:{flex:1},children:a.jsx(fe,{variant:"text",sx:{fontSize:"1.5rem",width:215}})})]})]}),S1e=({index:e})=>a.jsxs(Ka,{sx:{marginBottom:2,borderRadius:"6px",pointerEvents:"none"},defaultExpanded:e===0,children:[a.jsx(Qa,{sx:{"& .MuiAccordionSummary-content":{alignItems:"center"}},children:a.jsx(T,{width:"100%",display:"flex",alignItems:"center",children:a.jsx(w1e,{index:e})})}),a.jsx(Ja,{children:a.jsxs($,{alignItems:"stretch",direction:{xs:"column",lg:"row"},gap:5,justifyContent:"stretch",px:2,children:[a.jsxs($,{spacing:2,sx:{flex:1},children:[a.jsx(fe,{variant:"rounded",height:25,width:100}),a.jsx(fe,{variant:"rounded",height:250})]}),a.jsxs($,{spacing:2,sx:{flex:1},children:[a.jsx(fe,{variant:"rounded",height:25,width:100}),a.jsx(fe,{variant:"rounded",height:250})]})]})})]}),j1e=({data:e,isLoading:t=!1})=>{const n=Re(),{palette:r,typography:s}=n,{engagementCurrency:i}=pe(),o=m.useMemo(()=>({...SI(n,i),chart:{...SI(n,i).chart,fontFamily:s.fontFamily},colors:[r.chartBrand.main.light,r.chartBrand.secondary.bolder]}),[r,s,n,i]),l=m.useMemo(()=>({...Sv(n,i),chart:{...Sv(n,i).chart,fontFamily:s.fontFamily},colors:[r.chartBrand.main.light,r.chartBrand.secondary.bolder]}),[r,s,n,i]);return t?a.jsx(T,{children:Array(3).fill("temp").map((c,d)=>a.jsx(S1e,{index:d},d))}):a.jsx(T,{children:e.map((c,d)=>a.jsx(C1e,{data:c,frequencyOptions:l,index:d,reachOptions:o},c.aggValues))})},k1e=()=>{const{palette:e}=Re(),{planReachFrequency:t,planReachFrequencyLoading:n}=Es(),r=m.useMemo(()=>!n&&!t.length?h1e:f1e,[t,n]);return a.jsxs($,{gap:3,paddingBottom:1,children:[n?a.jsx(fe,{variant:"rounded",height:75}):a.jsx(vn,{sx:{minHeight:75,alignItems:"center",backgroundColor:"background.neutral.default",borderRadius:"8px",color:"text.default"},icon:a.jsx(wl,{color:e.icon.default,size:"16.67px"}),severity:"info",children:r}),a.jsx(j1e,{data:t,isLoading:n})]})}
259,kI=({noHeading:e=!1})=>{const t=Re(),{palette:n,typography:r}=t,{planResults:s,planResultsLoading:i}=Es(),{engagementCurrency:o}=pe(),l=m.useMemo(()=>Rke(s),[s]),[c,d]=m.useMemo(()=>Nke(s),[s]),u=Pke(t),p=Lke(t,o);return a.jsxs($,{gap:3,paddingBottom:e?1:4,children:[e?null:a.jsx($,{direction:"row",justifyContent:"space-between",children:a.jsx(I,{variant:"subtitle1",children:"Recommendations"})}),a.jsx(T,{sx:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:{xs:1,lg:3,xl:5}},children:i?a.jsx(Fke,{}):l.map(h=>a.jsx(zke,{recommendation:h},`${h.plannedSpend}-${h.plannedConversions}`))}),a.jsxs(T,{sx:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:{xs:1,lg:3,xl:5}},children:[a.jsx(yI,{data:c,isLoading:i,options:{...u,chart:{...u.chart,fontFamily:r.fontFamily},colors:[n.chartBrand.main.light,n.chartBrand.main.bold]},title:"Conversions"}),a.jsx(yI,{data:d,isLoading:i,options:{...p,chart:{...p.chart,fontFamily:r.fontFamily},colors:[n.chartBrand.secondary.light,n.chartBrand.secondary.bolder]},title:"Spend"})]})]})},E1e=[{authorized:"Planning.ReachFreqCharts",label:"Recommendations",value:"0"},{authorized:"Planning.ReachFreqCharts",label:"Reach & Frequency",value:"1"}],_1e=()=>{const{activeTab:e,handleUpdateActiveTab:t}=Es();return a.jsxs(fo,{onChange:t,renderOff:()=>a.jsx(kI,{}),tabs:E1e,testId:"plan-results:tab",value:e,children:[a.jsx(xt,{sx:{px:0},value:"0",children:a.jsx(kI,{noHeading:!0})}),a.jsx(xt,{sx:{px:0},value:"1",children:a.jsx(k1e,{})})]})},T1e={currentTotalRows:0,data:[],pivotTableRef:null,tableLoading:!0},I1e=(e,t)=>{switch(t.type){case"data":case"currentTotalRows":case"pivotTableRef":case"tableLoading":return{...e,[t.type]:t.value};default:return{...e}}},D1e=()=>{const{handleNavigateHome:e,handleNavigateToPlans:t,plan:n}=Es();return a.jsxs(T,{"data-testid":"plan-results:page:container",sx:{display:"flex",flexDirection:"column",width:ks,minWidth:600},children:[a.jsx(vu,{handleNavigateHome:e,pageName:n.plan_name,parentConfig:{handleNavigateToParent:t,parentName:"Planning"}}),a.jsx(Zke,{}),a.jsx(_1e,{}),a.jsx(p1e,{})]})},A1e=({activeTab:e,calcId:t,handleDeletePlans:n,handleDownloadPlan:r,handleDuplicatePlan:s,handleEditPlan:i,handleNavigateHome:o,handleNavigateToPlans:l,handleUpdateActiveTab:c,handleUpdatePlanState:d,handleUpdateTargetAudience:u,isInternalUser:p,kpiScalar:h,optId:f,plan:g,planLoading:x,planReachFrequency:b,planReachFrequencyLoading:y,planResults:v,planResultsMpTrack:C,planResultsLoading:w,metadataLoading:S,metadataResults:E,targetAudience:k,targetAudienceLoading:j,targetAudienceOptions:_,userId:D})=>{const[M,N]=m.useReducer(I1e,T1e),O=m.useMemo(()=>({state:M,dispatch:N,activeTab:e,calcId:t,handleDeletePlans:n,handleDownloadPlan:r,handleDuplicatePlan:s,handleEditPlan:i,handleNavigateHome:o,handleNavigateToPlans:l,handleUpdateActiveTab:c,handleUpdatePlanState:d,handleUpdateTargetAudience:u,isInternalUser:p,kpiScalar:h,optId:f,plan:g,planLoading:x,planReachFrequency:b,planReachFrequencyLoading:y,planResults:v,planResultsMpTrack:C,planResultsLoading:w,metadataLoading:S,metadataResults:E,targetAudience:k,targetAudienceLoading:j,targetAudienceOptions:_,userId:D}),[M,e,t,n,r,s,i,o,l,c,d,u,p,h,f,g,x,b,y,v,C,w,S,E,k,j,_,D]);return a.jsx(e$.Provider,{value:O,children:a.jsx(D1e,{})})},M1e=()=>{const e=en(),[t]=Jv(),n=kke(),[r,s]=m.useState("0"),[i,o]=m.useState(""),{calcId:l,optId:c}=m.useMemo(()=>{const ce=t.get("calcId"),J=t.get("optId");return{calcId:ce?Number(ce):0,optId:J?Number(J):0}},[t]),{engagementId:d,engagementNiceId:u}=pe(),{data:p=[]}=Qs(d),h=p[0]?.brand_nice_id||"",f=p[0]?.id||0,{data:g=[]}=QA({brandId:f,engagementNiceId:u},{skip:!f}),{data:x=null,isLoading:b}=XA(Number(l),{skip:!l}),{userIsInternal:y,userId:v}=gt(),C=yn({authorized:"Planning.ReachFreqCharts"}),{data:w=[],isLoading:S}=xC(d),{data:E=[],isLoading:k}=hu(d),j=m.useMemo(()=>l?w?.find(ce=>ce.id===l):null,[l,w]),_=m.useMemo(()=>j?.objective_name?E.find(J=>J.objective_name===j.objective_name)?.kpi_scalar??null:null,[j?.objective_name,E]),{data:D,isFetching:M}=M3(l,{skip:!l}),N=D??[],O=N.includes(i),{data:R=[],isFetching:L,isError:P}=R3({calcId:l,engagementNiceId:u,optId:c,targetAudience:i,kpiScalar:_},{skip:!(l&&c)||k||!i||!O}),F=M||N.length>0&&!O,{data:z=[],isFetching:B}=N3({calcId:l,optId:c},{skip:!(C&&l&&c)}),[W]=O3();m.useEffect(()=>{const[ce]=N;if(!ce){i&&o("");return}N.includes(i)||o(ce)},[i,N]),m.useEffect(()=>{(!(l&&c)||!(S||j))&&e("/planning/my-plans")},[l,e,c,j,S]);const H=m.useCallback(()=>e("/planning/my-plans"),[e]),V=m.useCallback(async()=>(n("email"),"error"in await W({brand:h,calcId:l,engagementNiceId:u,kpiScalar:_,mediaDimensions:g.map(({dimension:J})=>J),optId:c,planName:j?.plan_name||"",targetAudience:i})?{error:!0}:{error:!1}),[l,h,u,g,W,_,c,j,n,i]),{handleEditPlan:G,handleDuplicatePlan:X,handleDeletePlans:K,handleUpdatePlanState:ie}=PF("planResults"),le=m.useCallback(ce=>{s(ce),n("tab",{tab:ce==="1"?"Reach & Frequency":"Recommendations"})},[n]);return a.jsx(A1e,{activeTab:r,calcId:l||0,handleDeletePlans:K,handleDownloadPlan:V,handleDuplicatePlan:X,handleEditPlan:G,handleNavigateHome:H,handleNavigateToPlans:H,handleUpdateActiveTab:le,handleUpdatePlanState:ie,handleUpdateTargetAudience:o,isInternalUser:y,kpiScalar:_,optId:c||0,plan:j||Mke,planLoading:S,planReachFrequency:z,planReachFrequencyLoading:B,planResults:R,planResultsMpTrack:n,planResultsLoading:!P&&(L||F),metadataLoading:b,metadataResults:x,targetAudience:i,targetAudienceLoading:F,targetAudienceOptions:N,userId:v})},R1e=({objectiveName:e})=>{const t=m.useRef(null),n=t.current?t.current.scrollWidth>t.current.clientWidth:!1;return a.jsx(be,{title:n?e:"",children:a.jsxs($,{spacing:1,direction:"row",children:[a.jsx(T,{sx:{flexShrink:0},children:a.jsx(uu,{size:16})}),a.jsx(I,{ref:t,noWrap:!0,fontWeight:"500px",fontSize:"12px",children:e})]})})},N1e=({plans:e})=>{const[t,n]=m.useState(null),r=en(),s=o=>{const[l,c]=o,d=l?.toString()??"",u=c?.toString()??"";
259r("/planning/view-plan",{searchParams:{calcId:d,optId:u}})},i=e.length<2?{maxWidth:"500px"}:{};return a.jsx($,{spacing:2,children:a.jsx($,{direction:"row",gap:2,sx:{display:"flex",flexWrap:"wrap"},children:e.slice(0,4).map(o=>a.jsx(Ve,{sx:{minWidth:"220px",flex:"1 0 0",...i},children:a.jsx(Mb,{onClick:()=>s(o.ids),onMouseEnter:()=>n(o.id),onMouseLeave:()=>n(null),children:a.jsx(Ue,{children:a.jsxs($,{spacing:2,children:[a.jsxs($,{direction:"row",justifyContent:"space-between",children:[a.jsxs($,{spacing:1,children:[a.jsx(be,{title:`${o.planName} (${o.ids.join(", ")})`,children:a.jsx(I,{sx:{overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",align:"left",fontWeight:500,fontSize:"16px",mb:4,height:"48px"},children:o.planName})}),a.jsxs($,{direction:"row",gap:1,children:[a.jsx($w,{stateName:o.stateName}),a.jsx(UF,{type:o.type})]})]}),t&&t===o.id?a.jsx(Xv,{size:16}):a.jsx(T,{width:"16px"})]}),a.jsxs($,{gap:1,children:[a.jsxs($,{spacing:1,direction:"row",children:[a.jsx(au,{size:16}),a.jsx(T,{sx:{display:"flex",alignItems:"center",fontWeight:"500",fontSize:"12px"},children:o.dateRange})]}),a.jsx(R1e,{objectiveName:o.objectiveName}),a.jsx(BF,{type:o.type,value:o.budgetOrConversionValue,kpiScalar:o.kpiScalar})]})]})})})},o.id))})})},r$=({variant:e})=>{const{track:t}=wg(),n=en(),r=()=>{t("newPlan"),n("/planning/new-plan")};return a.jsx(ar,{authorized:"Planning.NewPlan",children:a.jsx(re,{color:"primary",variant:e,onClick:r,startIcon:a.jsx(ca,{size:16}),size:"small",children:"Create a Plan"})})},O1e=()=>a.jsxs($,{spacing:3,children:[a.jsx(I,{fontSize:"24px",fontWeight:600,children:"Start planning your new go-to-market plan in Planner now"}),a.jsx(gi,{width:"144px",children:a.jsx(r$,{variant:"contained"})})]}),s$=({Icon:e})=>a.jsx(T,{"aria-hidden":!0,sx:{alignItems:"center",bgcolor:"background.brand.subtle.default",borderRadius:1.5,color:"primary.main",display:"flex",height:32,justifyContent:"center",width:32},children:a.jsx(e,{size:18})}),P1e=({hasPlans:e,loading:t})=>{const n=en(),r=()=>{n("/planning/my-plans")};return a.jsxs($,{direction:"row",alignItems:"flex-start",justifyContent:"space-between",gap:2,children:[a.jsxs($,{direction:"row",alignItems:"center",gap:1.5,children:[a.jsx(s$,{Icon:OM}),a.jsxs($,{children:[a.jsx(I,{sx:{alignItems:"center",display:"flex",fontSize:"16px"},children:"My plans"}),!t&&(e?a.jsx(I,{sx:{color:"text.secondary",fontSize:"14px"},children:"Keep experimenting until you build the perfect go-to-market plan."}):a.jsx(I,{sx:{fontSize:"14px"},children:"You currently have no plans in progress."}))]})]}),a.jsx(T,{children:!t&&e&&a.jsxs($,{spacing:1,direction:"row",children:[a.jsx(re,{color:"secondary",variant:"outlined",onClick:r,size:"small",children:"See all"}),a.jsx(r$,{variant:"contained"})]})})]})},L1e=()=>{const e=[1,2,3,4];return a.jsxs($,{spacing:2,children:[a.jsx(T,{pt:"32px",children:a.jsx(fe,{variant:"rectangular",height:"50px"})}),a.jsx(T,{children:a.jsx($,{spacing:2,direction:"row",children:e.map(t=>a.jsx(Ve,{sx:{width:"100%"},children:a.jsx(Ue,{children:a.jsxs($,{spacing:2,children:[a.jsx(fe,{variant:"rectangular"}),a.jsxs($,{spacing:1,justifyContent:"space-between",children:[a.jsx(fe,{sx:{width:"200px"},variant:"rectangular"}),a.jsx(fe,{sx:{width:"200px"},variant:"rectangular"}),a.jsx(fe,{sx:{width:"200px"},variant:"rectangular"}),a.jsx(fe,{sx:{width:"200px"},variant:"rectangular"})]})]})})},t))})})]})},F1e=()=>{const{plans:e,isLoading:t}=sSe();return a.jsx($,{children:a.jsx(Ve,{children:a.jsx(Ue,{children:a.jsxs($,{spacing:3,children:[a.jsx(P1e,{hasPlans:e.length>0,loading:t}),t?a.jsx(L1e,{}):e.length>0?a.jsx(N1e,{plans:e}):a.jsx(O1e,{})]})})})})},$1e=()=>{const{availableDateRange:e,dispatch:t,getMediaData:n,handleConversionTypeChange:r,kpiOptions:s,mediaDataLoading:i,metaData:o,metaDataLoading:l,state:c,targetOptions:d,track:u}=wg(),{conversionType:p,selectedDateRange:h,selectedKpi:f,selectedTarget:g}=c,[x,b]=e,y=m.useCallback(w=>{const{nextDateRange:S,nextKpi:E,nextTarget:k}=Ys({metaData:o,selectedDateRange:h,selectedKpi:f,selectedTarget:w});t({type:"filtersBar",value:{selectedDateRange:S,selectedKpi:E,selectedTarget:k}}),u("targetAudience",{nextTarget:k}),n({nextDateRange:S,nextKpi:E,nextTarget:k})},[t,n,o,h,f,u]),v=m.useCallback(w=>{const{nextDateRange:S,nextKpi:E,nextTarget:k}=Ys({metaData:o,selectedDateRange:h,selectedKpi:w,selectedTarget:g});t({type:"filtersBar",value:{selectedDateRange:S,selectedKpi:E,selectedTarget:k}}),u("kpi",{nextKpi:E}),n({nextDateRange:S,nextKpi:E,nextTarget:k})},[t,n,o,g,h,u]),C=m.useCallback(w=>{const[S,E]=w;t({type:"selectedDateRange",value:w}),u("dateRange",{nextDateRange:{startDate:S?.format("YYYY-MM-DD")||"",endDate:E?.format("YYYY-MM-DD")||""}}),n({nextDateRange:w})},[t,n,u]);return a.jsxs($,{direction:"row",spacing:2,justifyContent:"space-between",children:[a.jsx(Mm,{disabled:l,onChange:r,value:p}),a.jsx(da,{dataFirstDate:x||void 0,dataLastDate:b||void 0,handleDatePickerOnChange:C,handleKpiOnChange:v,handleTargetAudienceOnChange:y,isDataLoading:i,isMetaLoading:l,kpiListOptions:s,selectedKpi:f,selectedTargetAudience:g,selectedDateRange:h,targetAudienceListOptions:d})]})},Gp=({title:e,value:t,isLoading:n,tooltipText:r="",Icon:s,accentColor:i})=>a.jsx(Ve,{elevation:0,sx:{border:"1px solid",borderColor:"divider",borderLeft:`4px solid ${i}`,borderRadius:3,flex:1,minWidth:200},children:a.jsx(be,{title:r,placement:"top",children:a.jsxs(Ue,{sx:{alignItems:"flex-start",display:"flex",p:2.5},children:[a.jsxs($,{direction:"column",gap:.5,flex:1,children:[a.jsx(I,{sx:{color:"text.secondary",fontSize:"0.75rem",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase"},children:e}),a.jsx(I,{variant:"h4",sx:{color:"text.primary",fontSize:"2rem",fontWeight:600,lineHeight:1.2},children:n?a.jsx(fe,{height:"48px",width:"150px"}):t||"-"})]}),a.jsx($,{sx:{alignItems:"center",display:"flex",height:40,justifyContent:"center",width:40},children:a.jsx(s,{size:24,strokeWidth:2,color:i})})]})})}),z1e=()=>{const e=yn({authorized:"ROAS"}),{mediaData:t,mediaDataLoading:n}=wg(),{engagementCurrency:r}=pe(),s=m.useMemo(()=>
259{if(t.length!==1)return{conversionsTotal:null,investmentTotal:null,totalCpc:null,roasTotal:null};const{conversions:o,investment:l,roas:c}=t[0];return{conversionsTotal:o,investmentTotal:l,totalCpc:o!==0?l/o:null,roasTotal:c??null}},[t]),{palette:i}=Re();return a.jsx(Ve,{sx:{flex:1},children:a.jsx(Ue,{sx:{height:"100%"},children:a.jsxs($,{direction:"column",gap:4.5,children:[a.jsxs($,{direction:"column",justifyContent:"space-between",gap:2.5,children:[a.jsxs($,{direction:"row",alignItems:"center",gap:1.5,children:[a.jsx(s$,{Icon:NM}),a.jsx(I,{fontSize:"16px",children:"Top insights"})]}),a.jsx($1e,{})]}),a.jsxs($,{direction:"row",alignItems:"center",gap:2,sx:{display:"flex",flexWrap:"wrap"},children:[a.jsx(Gp,{title:"Total Conversions",value:fg(s.conversionsTotal),isLoading:n,Icon:uu,accentColor:i.success.main}),a.jsx(Gp,{title:"Spend",value:Ci(s.investmentTotal,{options:{currency:r,maximumFractionDigits:0}}),isLoading:n,Icon:FD,accentColor:i.warning.main}),e&&a.jsx(Gp,{title:"ROAS",value:A2(s.roasTotal),isLoading:n,tooltipText:"Return on Advertising Spend is calculated as Attributed Revenue divided by Spend",Icon:dA,accentColor:i.info.main}),a.jsx(Gp,{title:"Spend Per Conversion",value:Ci(s.totalCpc,{options:{currency:r,maximumFractionDigits:2}}),isLoading:n,Icon:UU,accentColor:i.primary.main})]})]})})})},B1e=()=>a.jsxs($,{direction:"column",gap:3,minWidth:"600px",sx:{width:"100%"},children:[a.jsx(ar,{authorized:"Chat",children:a.jsx(ySe,{})}),a.jsx(ar,{authorized:"ReportsInsights",children:a.jsx(z1e,{})}),a.jsx(ar,{authorized:"Planning",children:a.jsx(F1e,{})})]}),U1e={conversionType:Wu,selectedDateRange:[null,null],selectedKpi:"",selectedTarget:""},V1e=(e,t)=>t.type in e?{...e,[t.type]:t.value}:t.type==="filtersBar"?{...e,...t.value}:e,W1e=()=>{const[e,t]=m.useReducer(V1e,U1e),{conversionType:n,selectedDateRange:r,selectedKpi:s,selectedTarget:i}=e,{userGivenName:o}=gt(),l=aSe(),c=m.useCallback(({type:w,value:S})=>{switch(w){case"conversionType":t({type:w,value:S}),l("conversionType",{conversionType:S});break;case"filtersBar":t({type:w,value:{selectedDateRange:S.nextDateRange,selectedKpi:S.nextKpi,selectedTarget:S.nextTarget}});break}},[l,t]),{availableDateRange:d,getMediaData:u,getMetaData:p,handleConversionTypeChange:h,kpiOptions:f,mediaData:g,mediaDataLoading:x,metaData:b,metaDataLoading:y,targetOptions:v}=Sw({conversionType:n,onFilterChange:c,selectedDateRange:r,selectedKpi:s,selectedTarget:i}),C=m.useMemo(()=>({availableDateRange:d,dispatch:t,getMediaData:u,getMetaData:p,handleConversionTypeChange:h,kpiOptions:f,mediaData:g,mediaDataLoading:x,metaData:b,metaDataLoading:y,state:e,targetOptions:v,track:l,userName:o}),[d,t,u,p,h,f,g,x,b,y,e,v,l,o]);return a.jsx(AF.Provider,{value:C,children:a.jsx(B1e,{})})};var Vc={},EI;function H1e(){if(EI)return Vc;EI=1;var e=Pt();Object.defineProperty(Vc,"__esModule",{value:!0}),Vc.default=void 0;var t=e(Lt()),n=Ot();return Vc.default=(0,t.default)((0,n.jsx)("path",{d:"M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"}),"ChevronLeft"),Vc}var q1e=H1e();const G1e=dt(q1e);var Wc={},_I;function Y1e(){if(_I)return Wc;_I=1;var e=Pt();Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.default=void 0;var t=e(Lt()),n=Ot();return Wc.default=(0,t.default)((0,n.jsx)("path",{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}),"ChevronRight"),Wc}var K1e=Y1e();const Q1e=dt(K1e);var TI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xu=(typeof window>"u"?"undefined":TI(window))==="object"&&(typeof document>"u"?"undefined":TI(document))==="object"&&document.nodeType===9,J1e={}.constructor;function jv(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(jv);if(e.constructor!==J1e)return e;var t={};for(var n in e)t[n]=jv(e[n]);return t}function Ww(e,t,n){e===void 0&&(e="unnamed");var r=n.jss,s=jv(t),i=r.plugins.onCreateRule(e,s,n);return i||(e[0],null)}var II=function(t,n){for(var r="",s=0;s<t.length&&t[s]!=="!important";s++)r&&(r+=n),r+=t[s];return r},Ga=function(t){if(!Array.isArray(t))return t;var n="";if(Array.isArray(t[0]))for(var r=0;r<t.length&&t[r]!=="!important";r++)n&&(n+=", "),n+=II(t[r]," ");else n=II(t,", ");return t[t.length-1]==="!important"&&(n+=" !important"),n};function Ul(e){return e&&e.format===!1?{linebreak:"",space:""}:{linebreak:` 260`,space:" "}}function Hc(e,t){for(var n="",r=0;r<t;r++)n+=" ";return n+e}function ru(e,t,n){n===void 0&&(n={});var r="";if(!t)return r;var s=n,i=s.indent,o=i===void 0?0:i,l=t.fallbacks;n.format===!1&&(o=-1/0);var c=Ul(n),d=c.linebreak,u=c.space;if(e&&o++,l)if(Array.isArray(l))for(var p=0;p<l.length;p++){var h=l[p];for(var f in h){var g=h[f];g!=null&&(r&&(r+=d),r+=Hc(f+":"+u+Ga(g)+";",o))}}else for(var x in l){var b=l[x];b!=null&&(r&&(r+=d),r+=Hc(x+":"+u+Ga(b)+";",o))}for(var y in t){var v=t[y];v!=null&&y!=="fallbacks"&&(r&&(r+=d),r+=Hc(y+":"+u+Ga(v)+";",o))}return!r&&!n.allowEmpty||!e?r:(o--,r&&(r=""+d+r+d),Hc(""+e+u+"{"+r,o)+Hc("}",o))}var X1e=/([[\].#*$><+~=|^:(),"'`\s])/g,DI=typeof CSS<"u"&&CSS.escape,Hw=(function(e){return DI?DI(e):e.replace(X1e,"\\$1")}),i$=(function(){function e(n,r,s){this.type="style",this.isProcessed=!1;var i=s.sheet,o=s.Renderer;this.key=n,this.options=s,this.style=r,i?this.renderer=i.renderer:o&&
260(this.renderer=new o)}var t=e.prototype;return t.prop=function(r,s,i){if(s===void 0)return this.style[r];var o=i?i.force:!1;if(!o&&this.style[r]===s)return this;var l=s;(!i||i.process!==!1)&&(l=this.options.jss.plugins.onChangeValue(s,r,this));var c=l==null||l===!1,d=r in this.style;if(c&&!d&&!o)return this;var u=c&&d;if(u?delete this.style[r]:this.style[r]=l,this.renderable&&this.renderer)return u?this.renderer.removeProperty(this.renderable,r):this.renderer.setProperty(this.renderable,r,l),this;var p=this.options.sheet;return p&&p.attached,this},e})(),kv=(function(e){MD(t,e);function t(r,s,i){var o;o=e.call(this,r,s,i)||this;var l=i.selector,c=i.scoped,d=i.sheet,u=i.generateId;return l?o.selectorText=l:c!==!1&&(o.id=u(bj(bj(o)),d),o.selectorText="."+Hw(o.id)),o}var n=t.prototype;return n.applyTo=function(s){var i=this.renderer;if(i){var o=this.toJSON();for(var l in o)i.setProperty(s,l,o[l])}return this},n.toJSON=function(){var s={};for(var i in this.style){var o=this.style[i];typeof o!="object"?s[i]=o:Array.isArray(o)&&(s[i]=Ga(o))}return s},n.toString=function(s){var i=this.options.sheet,o=i?i.options.link:!1,l=o?Ln({},s,{allowEmpty:!0}):s;return ru(this.selectorText,this.style,l)},aM(t,[{key:"selector",set:function(s){if(s!==this.selectorText){this.selectorText=s;var i=this.renderer,o=this.renderable;if(!(!o||!i)){var l=i.setSelector(o,s);l||i.replaceRule(o,this)}}},get:function(){return this.selectorText}}]),t})(i$),Z1e={onCreateRule:function(t,n,r){return t[0]==="@"||r.parent&&r.parent.type==="keyframes"?null:new kv(t,n,r)}},db={indent:1,children:!0},eEe=/@([\w-]+)/,tEe=(function(){function e(n,r,s){this.type="conditional",this.isProcessed=!1,this.key=n;var i=n.match(eEe);this.at=i?i[1]:"unknown",this.query=s.name||"@"+this.at,this.options=s,this.rules=new jg(Ln({},s,{parent:this}));for(var o in r)this.rules.add(o,r[o]);this.rules.process()}var t=e.prototype;return t.getRule=function(r){return this.rules.get(r)},t.indexOf=function(r){return this.rules.indexOf(r)},t.addRule=function(r,s,i){var o=this.rules.add(r,s,i);return o?(this.options.jss.plugins.onProcessRule(o),o):null},t.replaceRule=function(r,s,i){var o=this.rules.replace(r,s,i);return o&&this.options.jss.plugins.onProcessRule(o),o},t.toString=function(r){r===void 0&&(r=db);var s=Ul(r),i=s.linebreak;if(r.indent==null&&(r.indent=db.indent),r.children==null&&(r.children=db.children),r.children===!1)return this.query+" {}";var o=this.rules.toString(r);return o?this.query+" {"+i+o+i+"}":""},e})(),nEe=/@container|@media|@supports\s+/,rEe={onCreateRule:function(t,n,r){return nEe.test(t)?new tEe(t,n,r):null}},ub={indent:1,children:!0},sEe=/@keyframes\s+([\w-]+)/,Ev=(function(){function e(n,r,s){this.type="keyframes",this.at="@keyframes",this.isProcessed=!1;var i=n.match(sEe);i&&i[1]?this.name=i[1]:this.name="noname",this.key=this.type+"-"+this.name,this.options=s;var o=s.scoped,l=s.sheet,c=s.generateId;this.id=o===!1?this.name:Hw(c(this,l)),this.rules=new jg(Ln({},s,{parent:this}));for(var d in r)this.rules.add(d,r[d],Ln({},s,{parent:this}));this.rules.process()}var t=e.prototype;return t.toString=function(r){r===void 0&&(r=ub);var s=Ul(r),i=s.linebreak;if(r.indent==null&&(r.indent=ub.indent),r.children==null&&(r.children=ub.children),r.children===!1)return this.at+" "+this.id+" {}";var o=this.rules.toString(r);return o&&(o=""+i+o+i),this.at+" "+this.id+" {"+o+"}"},e})(),iEe=/@keyframes\s+/,aEe=/\$([\w-]+)/g,_v=function(t,n){return typeof t=="string"?t.replace(aEe,function(r,s){return s in n?n[s]:r}):t},AI=function(t,n,r){var s=t[n],i=_v(s,r);i!==s&&(t[n]=i)},oEe={onCreateRule:function(t,n,r){return typeof t=="string"&&iEe.test(t)?new Ev(t,n,r):null},onProcessStyle:function(t,n,r){return n.type!=="style"||!r||("animation-name"in t&&AI(t,"animation-name",r.keyframes),"animation"in t&&AI(t,"animation",r.keyframes)),t},onChangeValue:function(t,n,r){var s=r.options.sheet;if(!s)return t;switch(n){case"animation":return _v(t,s.keyframes);case"animation-name":return _v(t,s.keyframes);default:return t}}},lEe=(function(e){MD(t,e);function t(){return e.apply(this,arguments)||this}var n=t.prototype;return n.toString=function(s){var i=this.options.sheet,o=i?i.options.link:!1,l=o?Ln({},s,{allowEmpty:!0}):s;return ru(this.key,this.style,l)},t})(i$),cEe={onCreateRule:function(t,n,r){return r.parent&&r.parent.type==="
260keyframes"?new lEe(t,n,r):null}},dEe=(function(){function e(n,r,s){this.type="font-face",this.at="@font-face",this.isProcessed=!1,this.key=n,this.style=r,this.options=s}var t=e.prototype;return t.toString=function(r){var s=Ul(r),i=s.linebreak;if(Array.isArray(this.style)){for(var o="",l=0;l<this.style.length;l++)o+=ru(this.at,this.style[l]),this.style[l+1]&&(o+=i);return o}return ru(this.at,this.style,r)},e})(),uEe=/@font-face/,pEe={onCreateRule:function(t,n,r){return uEe.test(t)?new dEe(t,n,r):null}},hEe=(function(){function e(n,r,s){this.type="viewport",this.at="@viewport",this.isProcessed=!1,this.key=n,this.style=r,this.options=s}var t=e.prototype;return t.toString=function(r){return ru(this.key,this.style,r)},e})(),fEe={onCreateRule:function(t,n,r){return t==="@viewport"||t==="@-ms-viewport"?new hEe(t,n,r):null}},mEe=(function(){function e(n,r,s){this.type="simple",this.isProcessed=!1,this.key=n,this.value=r,this.options=s}var t=e.prototype;return t.toString=function(r){if(Array.isArray(this.value)){for(var s="",i=0;i<this.value.length;i++)s+=this.key+" "+this.value[i]+";",this.value[i+1]&&(s+=` 261`);return s}return this.key+" "+this.value+";"},e})(),gEe={"@charset":!0,"@import":!0,"@namespace":!0},xEe={onCreateRule:function(t,n,r){return t in gEe?new mEe(t,n,r):null}},MI=[Z1e,rEe,oEe,cEe,pEe,fEe,xEe],bEe={process:!0},RI={force:!0,process:!0},jg=(function(){function e(n){this.map={},this.raw={},this.index=[],this.counter=0,this.options=n,this.classes=n.classes,this.keyframes=n.keyframes}var t=e.prototype;return t.add=function(r,s,i){var o=this.options,l=o.parent,c=o.sheet,d=o.jss,u=o.Renderer,p=o.generateId,h=o.scoped,f=Ln({classes:this.classes,parent:l,sheet:c,jss:d,Renderer:u,generateId:p,scoped:h,name:r,keyframes:this.keyframes,selector:void 0},i),g=r;r in this.raw&&(g=r+"-d"+this.counter++),this.raw[g]=s,g in this.classes&&(f.selector="."+Hw(this.classes[g]));var x=Ww(g,s,f);if(!x)return null;this.register(x);var b=f.index===void 0?this.index.length:f.index;return this.index.splice(b,0,x),x},t.replace=function(r,s,i){var o=this.get(r),l=this.index.indexOf(o);o&&this.remove(o);var c=i;return l!==-1&&(c=Ln({},i,{index:l})),this.add(r,s,c)},t.get=function(r){return this.map[r]},t.remove=function(r){this.unregister(r),delete this.raw[r.key],this.index.splice(this.index.indexOf(r),1)},t.indexOf=function(r){return this.index.indexOf(r)},t.process=function(){var r=this.options.jss.plugins;this.index.slice(0).forEach(r.onProcessRule,r)},t.register=function(r){this.map[r.key]=r,r instanceof kv?(this.map[r.selector]=r,r.id&&(this.classes[r.key]=r.id)):r instanceof Ev&&this.keyframes&&(this.keyframes[r.name]=r.id)},t.unregister=function(r){delete this.map[r.key],r instanceof kv?(delete this.map[r.selector],delete this.classes[r.key]):r instanceof Ev&&delete this.keyframes[r.name]},t.update=function(){var r,s,i;if(typeof(arguments.length<=0?void 0:arguments[0])=="string"?(r=arguments.length<=0?void 0:arguments[0],s=arguments.length<=1?void 0:arguments[1],i=arguments.length<=2?void 0:arguments[2]):(s=arguments.length<=0?void 0:arguments[0],i=arguments.length<=1?void 0:arguments[1],r=null),r)this.updateOne(this.get(r),s,i);else for(var o=0;o<this.index.length;o++)this.updateOne(this.index[o],s,i)},t.updateOne=function(r,s,i){i===void 0&&(i=bEe);var o=this.options,l=o.jss.plugins,c=o.sheet;if(r.rules instanceof e){r.rules.update(s,i);return}var d=r.style;if(l.onUpdate(s,r,c,i),i.process&&d&&d!==r.style){l.onProcessStyle(r.style,r,c);for(var u in r.style){var p=r.style[u],h=d[u];p!==h&&r.prop(u,p,RI)}for(var f in d){var g=r.style[f],x=d[f];g==null&&g!==x&&r.prop(f,null,RI)}}},t.toString=function(r){for(var s="",i=this.options.sheet,o=i?i.options.link:!1,l=Ul(r),c=l.linebreak,d=0;d<this.index.length;d++){var u=this.index[d],p=u.toString(r);!p&&!o||(s&&(s+=c),s+=p)}return s},e})(),a$=(function(){function e(n,r){this.attached=!1,this.deployed=!1,this.classes={},this.keyframes={},this.options=Ln({},r,{sheet:this,parent:this,classes:this.classes,keyframes:this.keyframes}),r.Renderer&&(this.renderer=new r.Renderer(this)),this.rules=new jg(this.options);for(var s in n)this.rules.add(s,n[s]);this.rules.process()}var t=e.prototype;return t.attach=function(){return this.attached?this:(this.renderer&&this.renderer.attach(),this.attached=!0,this.deployed||this.deploy(),this)},t.detach=function(){return this.attached?(this.renderer&&this.renderer.detach(),this.attached=!1,this):this},t.addRule=function(r,s,i){var o=this.queue;
261this.attached&&!o&&(this.queue=[]);var l=this.rules.add(r,s,i);return l?(this.options.jss.plugins.onProcessRule(l),this.attached?(this.deployed&&(o?o.push(l):(this.insertRule(l),this.queue&&(this.queue.forEach(this.insertRule,this),this.queue=void 0))),l):(this.deployed=!1,l)):null},t.replaceRule=function(r,s,i){var o=this.rules.get(r);if(!o)return this.addRule(r,s,i);var l=this.rules.replace(r,s,i);return l&&this.options.jss.plugins.onProcessRule(l),this.attached?(this.deployed&&this.renderer&&(l?o.renderable&&this.renderer.replaceRule(o.renderable,l):this.renderer.deleteRule(o)),l):(this.deployed=!1,l)},t.insertRule=function(r){this.renderer&&this.renderer.insertRule(r)},t.addRules=function(r,s){var i=[];for(var o in r){var l=this.addRule(o,r[o],s);l&&i.push(l)}return i},t.getRule=function(r){return this.rules.get(r)},t.deleteRule=function(r){var s=typeof r=="object"?r:this.rules.get(r);return!s||this.attached&&!s.renderable?!1:(this.rules.remove(s),this.attached&&s.renderable&&this.renderer?this.renderer.deleteRule(s.renderable):!0)},t.indexOf=function(r){return this.rules.indexOf(r)},t.deploy=function(){return this.renderer&&this.renderer.deploy(),this.deployed=!0,this},t.update=function(){var r;return(r=this.rules).update.apply(r,arguments),this},t.updateOne=function(r,s,i){return this.rules.updateOne(r,s,i),this},t.toString=function(r){return this.rules.toString(r)},e})(),yEe=(function(){function e(){this.plugins={internal:[],external:[]},this.registry={}}var t=e.prototype;return t.onCreateRule=function(r,s,i){for(var o=0;o<this.registry.onCreateRule.length;o++){var l=this.registry.onCreateRule[o](r,s,i);if(l)return l}return null},t.onProcessRule=function(r){if(!r.isProcessed){for(var s=r.options.sheet,i=0;i<this.registry.onProcessRule.length;i++)this.registry.onProcessRule[i](r,s);r.style&&this.onProcessStyle(r.style,r,s),r.isProcessed=!0}},t.onProcessStyle=function(r,s,i){for(var o=0;o<this.registry.onProcessStyle.length;o++)s.style=this.registry.onProcessStyle[o](s.style,s,i)},t.onProcessSheet=function(r){for(var s=0;s<this.registry.onProcessSheet.length;s++)this.registry.onProcessSheet[s](r)},t.onUpdate=function(r,s,i,o){for(var l=0;l<this.registry.onUpdate.length;l++)this.registry.onUpdate[l](r,s,i,o)},t.onChangeValue=function(r,s,i){for(var o=r,l=0;l<this.registry.onChangeValue.length;l++)o=this.registry.onChangeValue[l](o,s,i);return o},t.use=function(r,s){s===void 0&&(s={queue:"external"});var i=this.plugins[s.queue];i.indexOf(r)===-1&&(i.push(r),this.registry=[].concat(this.plugins.external,this.plugins.internal).reduce(function(o,l){for(var c in l)c in o&&o[c].push(l[c]);return o},{onCreateRule:[],onProcessRule:[],onProcessStyle:[],onProcessSheet:[],onChangeValue:[],onUpdate:[]}))},e})(),vEe=(function(){function e(){this.registry=[]}var t=e.prototype;return t.add=function(r){var s=this.registry,i=r.options.index;if(s.indexOf(r)===-1){if(s.length===0||i>=this.index){s.push(r);return}for(var o=0;o<s.length;o++)if(s[o].options.index>i){s.splice(o,0,r);return}}},t.reset=function(){this.registry=[]},t.remove=function(r){var s=this.registry.indexOf(r);this.registry.splice(s,1)},t.toString=function(r){for(var s=r===void 0?{}:r,i=s.attached,o=Kz(s,["attached"]),l=Ul(o),c=l.linebreak,d="",u=0;u<this.registry.length;u++){var p=this.registry[u];i!=null&&p.attached!==i||(d&&(d+=c),d+=p.toString(o))}return d},aM(e,[{key:"index",get:function(){return this.registry.length===0?0:this.registry[this.registry.length-1].options.index}}]),e})(),Td=new vEe,Tv=typeof globalThis<"u"?globalThis:typeof window<"u"&&window.Math===Math?window:typeof self<"u"&&self.Math===Math?self:Function("return this")(),Iv="2f1acc6c3a606b082e5eef5e54414ffb";Tv[Iv]==null&&(Tv[Iv]=0);var NI=Tv[Iv]++,OI=function(t){t===void 0&&(t={});var n=0,r=function(i,o){n+=1;var l="",c="";return o&&(o.options.classNamePrefix&&(c=o.options.classNamePrefix),o.options.jss.id!=null&&(l=String(o.options.jss.id))),t.minify?""+(c||"c")+NI+l+n:c+i.key+"-"+NI+(l?"-"+l:"")+"-"+n};return r},o$=function(t){var n;return function(){return n||(n=t()),n}},CEe=function(t,n){try{return t.attributeStyleMap?t.attributeStyleMap.get(n):t.style.getPropertyValue(n)}catch{return""}},wEe=function(t,n,r){try{var s=r;if(Array.isArray(r)&&(s=Ga(r)),t.attributeStyleMap)t.attributeStyleMap.set(n,s);else{var i=s?s.indexOf("!important"):-1,o=i>-1?s.substr(0,i-1):s;t.style.setProperty(n,o,i>-1?"important":"")}}catch{return!1}return!0},SEe=function(t,n){try{t.attributeStyleMap?t.attributeStyleMap.delete(n):t.style.removeProperty(n)}catch{}},jEe=function(t,n){return t.selectorText=n,t.selectorText===n},l$=o$(function(){return document.querySelector("head")});function kEe(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(r.attached&&r.options.index>t.index&&r.options.insertionPoint===t.insertionPoint)return r}return null}function EEe(e,t){for(var n=e.length-1;n>=0;n--){var r=e[n];if(r.attached&&r.options.insertionPoint===t.insertionPoint)return r}return null}function _Ee(e){for(var t=l$(),n=0;n<t.childNodes.length;n++){var r=t.childNodes[n];
261if(r.nodeType===8&&r.nodeValue.trim()===e)return r}return null}function TEe(e){var t=Td.registry;if(t.length>0){var n=kEe(t,e);if(n&&n.renderer)return{parent:n.renderer.element.parentNode,node:n.renderer.element};if(n=EEe(t,e),n&&n.renderer)return{parent:n.renderer.element.parentNode,node:n.renderer.element.nextSibling}}var r=e.insertionPoint;if(r&&typeof r=="string"){var s=_Ee(r);if(s)return{parent:s.parentNode,node:s.nextSibling}}return!1}function IEe(e,t){var n=t.insertionPoint,r=TEe(t);if(r!==!1&&r.parent){r.parent.insertBefore(e,r.node);return}if(n&&typeof n.nodeType=="number"){var s=n,i=s.parentNode;i&&i.insertBefore(e,s.nextSibling);return}l$().appendChild(e)}var DEe=o$(function(){var e=document.querySelector('meta[property="csp-nonce"]');return e?e.getAttribute("content"):null}),PI=function(t,n,r){try{"insertRule"in t?t.insertRule(n,r):"appendRule"in t&&t.appendRule(n)}catch{return!1}return t.cssRules[r]},LI=function(t,n){var r=t.cssRules.length;return n===void 0||n>r?r:n},AEe=function(){var t=document.createElement("style");return t.textContent=` 262`,t},MEe=(function(){function e(n){this.getPropertyValue=CEe,this.setProperty=wEe,this.removeProperty=SEe,this.setSelector=jEe,this.hasInsertedRules=!1,this.cssRules=[],n&&Td.add(n),this.sheet=n;var r=this.sheet?this.sheet.options:{},s=r.media,i=r.meta,o=r.element;this.element=o||AEe(),this.element.setAttribute("data-jss",""),s&&this.element.setAttribute("media",s),i&&this.element.setAttribute("data-meta",i);var l=DEe();l&&this.element.setAttribute("nonce",l)}var t=e.prototype;return t.attach=function(){if(!(this.element.parentNode||!this.sheet)){IEe(this.element,this.sheet.options);var r=!!(this.sheet&&this.sheet.deployed);this.hasInsertedRules&&r&&(this.hasInsertedRules=!1,this.deploy())}},t.detach=function(){if(this.sheet){var r=this.element.parentNode;r&&r.removeChild(this.element),this.sheet.options.link&&(this.cssRules=[],this.element.textContent=` 263`)}},t.deploy=function(){var r=this.sheet;if(r){if(r.options.link){this.insertRules(r.rules);return}this.element.textContent=` 264`+r.toString()+` 265`}},t.insertRules=function(r,s){for(var i=0;i<r.index.length;i++)this.insertRule(r.index[i],i,s)},t.insertRule=function(r,s,i){if(i===void 0&&(i=this.element.sheet),r.rules){var o=r,l=i;if(r.type==="conditional"||r.type==="keyframes"){var c=LI(i,s);if(l=PI(i,o.toString({children:!1}),c),l===!1)return!1;this.refCssRule(r,c,l)}return this.insertRules(o.rules,l),l}var d=r.toString();if(!d)return!1;var u=LI(i,s),p=PI(i,d,u);return p===!1?!1:(this.hasInsertedRules=!0,this.refCssRule(r,u,p),p)},t.refCssRule=function(r,s,i){r.renderable=i,r.options.parent instanceof a$&&this.cssRules.splice(s,0,i)},t.deleteRule=function(r){var s=this.element.sheet,i=this.indexOf(r);return i===-1?!1:(s.deleteRule(i),this.cssRules.splice(i,1),!0)},t.indexOf=function(r){return this.cssRules.indexOf(r)},t.replaceRule=function(r,s){var i=this.indexOf(r);return i===-1?!1:(this.element.sheet.deleteRule(i),this.cssRules.splice(i,1),this.insertRule(s,i))},t.getRules=function(){return this.element.sheet.cssRules},e})(),REe=0,NEe=(function(){function e(n){this.id=REe++,this.version="10.10.0",this.plugins=new yEe,this.options={id:{minify:!1},createGenerateId:OI,Renderer:Xu?MEe:null,plugins:[]},this.generateId=OI({minify:!1});for(var r=0;r<MI.length;r++)this.plugins.use(MI[r],{queue:"internal"});this.setup(n)}var t=e.prototype;return t.setup=function(r){return r===void 0&&(r={}),r.createGenerateId&&(this.options.createGenerateId=r.createGenerateId),r.id&&(this.options.id=Ln({},this.options.id,r.id)),(r.createGenerateId||r.id)&&(this.generateId=this.options.createGenerateId(this.options.id)),r.insertionPoint!=null&&(this.options.insertionPoint=r.insertionPoint),"Renderer"in r&&(this.options.Renderer=r.Re
265nderer),r.plugins&&this.use.apply(this,r.plugins),this},t.createStyleSheet=function(r,s){s===void 0&&(s={});var i=s,o=i.index;typeof o!="number"&&(o=Td.index===0?0:Td.index+1);var l=new a$(r,Ln({},s,{jss:this,generateId:s.generateId||this.generateId,insertionPoint:this.options.insertionPoint,Renderer:this.options.Renderer,index:o}));return this.plugins.onProcessSheet(l),l},t.removeStyleSheet=function(r){return r.detach(),Td.remove(r),this},t.createRule=function(r,s,i){if(s===void 0&&(s={}),i===void 0&&(i={}),typeof r=="object")return this.createRule(void 0,r,s);var o=Ln({},i,{name:r,jss:this,Renderer:this.options.Renderer});o.generateId||(o.generateId=this.generateId),o.classes||(o.classes={}),o.keyframes||(o.keyframes={});var l=Ww(r,s,o);return l&&this.plugins.onProcessRule(l),l},t.use=function(){for(var r=this,s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];return i.forEach(function(l){r.plugins.use(l)}),this},e})(),c$=function(t){return new NEe(t)},qw=typeof CSS=="object"&&CSS!=null&&"number"in CSS;function d$(e){var t=null;for(var n in e){var r=e[n],s=typeof r;if(s==="function")t||(t={}),t[n]=r;else if(s==="object"&&r!==null&&!Array.isArray(r)){var i=d$(r);i&&(t||(t={}),t[n]=i)}}return t}c$();function u$(e={}){const{baseClasses:t,newClasses:n,Component:r}=e;if(!n)return t;const s=Bs({},t);return Object.keys(n).forEach(i=>{n[i]&&(s[i]=`${t[i]} ${n[i]}`)}),s}const Ho={set:(e,t,n,r)=>{let s=e.get(t);s||(s=new Map,e.set(t,s)),s.set(n,r)},get:(e,t,n)=>{const r=e.get(t);return r?r.get(n):void 0},delete:(e,t,n)=>{e.get(t).delete(n)}};function p$(){var e;const t=Qz();return(e=t?.$$material)!=null?e:t}const OEe=["checked","disabled","error","focused","focusVisible","required","expanded","selected"];function PEe(e={}){const{disableGlobal:t=!1,productionPrefix:n="jss",seed:r=""}=e,s=r===""?"":`${r}-`;let i=0;const o=()=>(i+=1,i);return(l,c)=>{const d=c.options.name;if(d&&d.indexOf("Mui")===0&&!c.options.link&&!t){if(OEe.indexOf(l.key)!==-1)return`Mui-${l.key}`;const u=`${s}${d}-${l.key}`;return!c.options.theme[Jz]||r!==""?u:`${u}-${o()}`}return`${s}${n}${o()}`}}var h$=Date.now(),pb="fnValues"+h$,hb="fnStyle"+ ++h$,LEe=function(){return{onCreateRule:function(n,r,s){if(typeof r!="function")return null;var i=Ww(n,{},s);return i[hb]=r,i},onProcessStyle:function(n,r){if(pb in r||hb in r)return n;var s={};for(var i in n){var o=n[i];typeof o=="function"&&(delete n[i],s[i]=o)}return r[pb]=s,n},onUpdate:function(n,r,s,i){var o=r,l=o[hb];l&&(o.style=l(n)||{});var c=o[pb];if(c)for(var d in c)o.prop(d,c[d](n),i)}}},ta="@global",Dv="@global ",FEe=(function(){function e(n,r,s){this.type="global",this.at=ta,this.isProcessed=!1,this.key=n,this.options=s,this.rules=new jg(Ln({},s,{parent:this}));for(var i in r)this.rules.add(i,r[i]);this.rules.process()}var t=e.prototype;return t.getRule=function(r){return this.rules.get(r)},t.addRule=function(r,s,i){var o=this.rules.add(r,s,i);return o&&this.options.jss.plugins.onProcessRule(o),o},t.replaceRule=function(r,s,i){var o=this.rules.replace(r,s,i);return o&&this.options.jss.plugins.onProcessRule(o),o},t.indexOf=function(r){return this.rules.indexOf(r)},t.toString=function(r){return this.rules.toString(r)},e})(),$Ee=(function(){function e(n,r,s){this.type="global",this.at=ta,this.isProcessed=!1,this.key=n,this.options=s;var i=n.substr(Dv.length);this.rule=s.jss.createRule(i,r,Ln({},s,{parent:this}))}var t=e.prototype;return t.toString=function(r){return this.rule?this.rule.toString(r):""},e})(),zEe=/\s*,\s*/g;function f$(e,t){for(var n=e.split(zEe),r="",s=0;s<n.length;s++)r+=t+" "+n[s].trim(),n[s+1]&&(r+=", ");return r}function BEe(e,t){var n=e.options,r=e.style,s=r?r[ta]:null;if(s){for(var i in s)t.addRule(i,s[i],Ln({},n,{selector:f$(i,e.selector)}));delete r[ta]}}function UEe(e,t){var n=e.options,r=e.style;for(var s in r)if(!(s[0]!=="@"||s.substr(0,ta.length)!==ta)){var i=f$(s.substr(ta.length),e.selector);t.addRule(i,r[s],Ln({},n,{selector:i})),delete r[s]}}function VEe(){function e(n,r,s){if(!n)return null;if(n===ta)return new FEe(n,r,s);if(n[0]==="@"&&n.substr(0,Dv.length)===Dv)return new $Ee(n,r,s);var i=s.parent;return i&&(i.type==="global"||i.options.parent&&i.options.parent.type==="global")&&(s.scoped=!1),!s.selector&&s.scoped===!1&&(s.selector=n),null}function t(n,r){n.type!=="style"||!r||(BEe(n,r),UEe(n,r))}return{onCreateRule:e,onProcessRule:t}}var FI=/\s*,\s*/g,WEe=/&/g,HEe=/\$([\w-]+)/g;function qEe(){function e(s,i){return function(o,l){var c=s.getRule(l)||i&&i.getRule(l);return c?c.selector:l}}function t(s,i){for(var o=i.split(FI),l=s.split(FI),c="",d=0;d<o.length;d++)for(var u=o[d],p=0;p<l.length;p++){var h=l[p];c&&(c+=", "),c+=h.indexOf("&")!==-1?h.replace(WEe,u):u+" "+h}return c}function n(s,i,o){if(o)return Ln({},o,{index:o.index+1});var l=s.options.nestingLevel;l=l===void 0?1:l+1;var c=Ln({},s.options,{nestingLevel:l,index:i.indexOf(s)+1});return delete c.name,c}function r(s,i,o){if(i.type!=="style")return s;var l=i,c=l.options.parent,d,u;
265for(var p in s){var h=p.indexOf("&")!==-1,f=p[0]==="@";if(!(!h&&!f)){if(d=n(l,c,d),h){var g=t(p,l.selector);u||(u=e(c,o)),g=g.replace(HEe,u);var x=l.key+"-"+p;"replaceRule"in c?c.replaceRule(x,s[p],Ln({},d,{selector:g})):c.addRule(x,s[p],Ln({},d,{selector:g}))}else f&&c.addRule(p,{},d).addRule(l.key,s[p],{selector:l.selector});delete s[p]}}return s}return{onProcessStyle:r}}var GEe=/[A-Z]/g,YEe=/^ms-/,fb={};function KEe(e){return"-"+e.toLowerCase()}function m$(e){if(fb.hasOwnProperty(e))return fb[e];var t=e.replace(GEe,KEe);return fb[e]=YEe.test(t)?"-"+t:t}function om(e){var t={};for(var n in e){var r=n.indexOf("--")===0?n:m$(n);t[r]=e[n]}return e.fallbacks&&(Array.isArray(e.fallbacks)?t.fallbacks=e.fallbacks.map(om):t.fallbacks=om(e.fallbacks)),t}function QEe(){function e(n){if(Array.isArray(n)){for(var r=0;r<n.length;r++)n[r]=om(n[r]);return n}return om(n)}function t(n,r,s){if(r.indexOf("--")===0)return n;var i=m$(r);return r===i?n:(s.prop(i,n),null)}return{onProcessStyle:e,onChangeValue:t}}var ge=qw&&CSS?CSS.px:"px",Yp=qw&&CSS?CSS.ms:"ms",Oo=qw&&CSS?CSS.percent:"%",JEe={"animation-delay":Yp,"animation-duration":Yp,"background-position":ge,"background-position-x":ge,"background-position-y":ge,"background-size":ge,border:ge,"border-bottom":ge,"border-bottom-left-radius":ge,"border-bottom-right-radius":ge,"border-bottom-width":ge,"border-left":ge,"border-left-width":ge,"border-radius":ge,"border-right":ge,"border-right-width":ge,"border-top":ge,"border-top-left-radius":ge,"border-top-right-radius":ge,"border-top-width":ge,"border-width":ge,"border-block":ge,"border-block-end":ge,"border-block-end-width":ge,"border-block-start":ge,"border-block-start-width":ge,"border-block-width":ge,"border-inline":ge,"border-inline-end":ge,"border-inline-end-width":ge,"border-inline-start":ge,"border-inline-start-width":ge,"border-inline-width":ge,"border-start-start-radius":ge,"border-start-end-radius":ge,"border-end-start-radius":ge,"border-end-end-radius":ge,margin:ge,"margin-bottom":ge,"margin-left":ge,"margin-right":ge,"margin-top":ge,"margin-block":ge,"margin-block-end":ge,"margin-block-start":ge,"margin-inline":ge,"margin-inline-end":ge,"margin-inline-start":ge,padding:ge,"padding-bottom":ge,"padding-left":ge,"padding-right":ge,"padding-top":ge,"padding-block":ge,"padding-block-end":ge,"padding-block-start":ge,"padding-inline":ge,"padding-inline-end":ge,"padding-inline-start":ge,"mask-position-x":ge,"mask-position-y":ge,"mask-size":ge,height:ge,width:ge,"min-height":ge,"max-height":ge,"min-width":ge,"max-width":ge,bottom:ge,left:ge,top:ge,right:ge,inset:ge,"inset-block":ge,"inset-block-end":ge,"inset-block-start":ge,"inset-inline":ge,"inset-inline-end":ge,"inset-inline-start":ge,"box-shadow":ge,"text-shadow":ge,"column-gap":ge,"column-rule":ge,"column-rule-width":ge,"column-width":ge,"font-size":ge,"font-size-delta":ge,"letter-spacing":ge,"text-decoration-thickness":ge,"text-indent":ge,"text-stroke":ge,"text-stroke-width":ge,"word-spacing":ge,motion:ge,"motion-offset":ge,outline:ge,"outline-offset":ge,"outline-width":ge,perspective:ge,"perspective-origin-x":Oo,"perspective-origin-y":Oo,"transform-origin":Oo,"transform-origin-x":Oo,"transform-origin-y":Oo,"transform-origin-z":Oo,"transition-delay":Yp,"transition-duration":Yp,"vertical-align":ge,"flex-basis":ge,"shape-margin":ge,size:ge,gap:ge,grid:ge,"grid-gap":ge,"row-gap":ge,"grid-row-gap":ge,"grid-column-gap":ge,"grid-template-rows":ge,"grid-template-columns":ge,"grid-auto-rows":ge,"grid-auto-columns":ge,"box-shadow-x":ge,"box-shadow-y":ge,"box-shadow-blur":ge,"box-shadow-spread":ge,"font-line-height":ge,"text-shadow-x":ge,"text-shadow-y":ge,"text-shadow-blur":ge};function g$(e){var t=/(-[a-z])/g,n=function(o){return o[1].toUpperCase()},r={};for(var s in e)r[s]=e[s],r[s.replace(t,n)]=e[s];return r}var XEe=g$(JEe);function Id(e,t,n){if(t==null)return t;if(Array.isArray(t))for(var r=0;r<t.length;r++)t[r]=Id(e,t[r],n);else if(typeof t=="object")if(e==="fallbacks")for(var s in t)t[s]=Id(s,t[s],n);else for(var i in t)t[i]=Id(e+"-"+i,t[i],n);else if(typeof t=="number"&&isNaN(t)===!1){var o=n[e]||XEe[e];return o&&!(t===0&&o===ge)?typeof o=="function"?o(t).toString():""+t+o:t.toString()}return t}function ZEe(e){e===void 0&&(e={});var t=g$(e);
265function n(s,i){if(i.type!=="style")return s;for(var o in s)s[o]=Id(o,s[o],t);return s}function r(s,i){return Id(i,s,t)}return{onProcessStyle:n,onChangeValue:r}}var dd="",Av="",x$="",b$="",e_e=Xu&&"ontouchstart"in document.documentElement;if(Xu){var mb={Moz:"-moz-",ms:"-ms-",O:"-o-",Webkit:"-webkit-"},t_e=document.createElement("p"),gb=t_e.style,n_e="Transform";for(var xb in mb)if(xb+n_e in gb){dd=xb,Av=mb[xb];break}dd==="Webkit"&&"msHyphens"in gb&&(dd="ms",Av=mb.ms,b$="edge"),dd==="Webkit"&&"-apple-trailing-word"in gb&&(x$="apple")}var lt={js:dd,css:Av,vendor:x$,browser:b$,isTouch:e_e};function r_e(e){return e[1]==="-"||lt.js==="ms"?e:"@"+lt.css+"keyframes"+e.substr(10)}var s_e={noPrefill:["appearance"],supportedProperty:function(t){return t!=="appearance"?!1:lt.js==="ms"?"-webkit-"+t:lt.css+t}},i_e={noPrefill:["color-adjust"],supportedProperty:function(t){return t!=="color-adjust"?!1:lt.js==="Webkit"?lt.css+"print-"+t:t}},a_e=/[-\s]+(.)?/g;function o_e(e,t){return t?t.toUpperCase():""}function Gw(e){return e.replace(a_e,o_e)}function la(e){return Gw("-"+e)}var l_e={noPrefill:["mask"],supportedProperty:function(t,n){if(!/^mask/.test(t))return!1;if(lt.js==="Webkit"){var r="mask-image";if(Gw(r)in n)return t;if(lt.js+la(r)in n)return lt.css+t}return t}},c_e={noPrefill:["text-orientation"],supportedProperty:function(t){return t!=="text-orientation"?!1:lt.vendor==="apple"&&!lt.isTouch?lt.css+t:t}},d_e={noPrefill:["transform"],supportedProperty:function(t,n,r){return t!=="transform"?!1:r.transform?t:lt.css+t}},u_e={noPrefill:["transition"],supportedProperty:function(t,n,r){return t!=="transition"?!1:r.transition?t:lt.css+t}},p_e={noPrefill:["writing-mode"],supportedProperty:function(t){return t!=="writing-mode"?!1:lt.js==="Webkit"||lt.js==="ms"&<.browser!=="edge"?lt.css+t:t}},h_e={noPrefill:["user-select"],supportedProperty:function(t){return t!=="user-select"?!1:lt.js==="Moz"||lt.js==="ms"||lt.vendor==="apple"?lt.css+t:t}},f_e={supportedProperty:function(t,n){if(!/^break-/.test(t))return!1;if(lt.js==="Webkit"){var r="WebkitColumn"+la(t);return r in n?lt.css+"column-"+t:!1}if(lt.js==="Moz"){var s="page"+la(t);return s in n?"page-"+t:!1}return!1}},m_e={supportedProperty:function(t,n){if(!/^(border|margin|padding)-inline/.test(t))return!1;if(lt.js==="Moz")return t;var r=t.replace("-inline","");return lt.js+la(r)in n?lt.css+r:!1}},g_e={supportedProperty:function(t,n){return Gw(t)in n?t:!1}},x_e={supportedProperty:function(t,n){var r=la(t);return t[0]==="-"||t[0]==="-"&&t[1]==="-"?t:lt.js+r in n?lt.css+t:lt.js!=="Webkit"&&"Webkit"+r in n?"-webkit-"+t:!1}},b_e={supportedProperty:function(t){return t.substring(0,11)!=="scroll-snap"?!1:lt.js==="ms"?""+lt.css+t:t}},y_e={supportedProperty:function(t){return t!=="overscroll-behavior"?!1:lt.js==="ms"?lt.css+"scroll-chaining":t}},v_e={"flex-grow":"flex-positive","flex-shrink":"flex-negative","flex-basis":"flex-preferred-size","justify-content":"flex-pack",order:"flex-order","align-items":"flex-align","align-content":"flex-line-pack"},C_e={supportedProperty:function(t,n){var r=v_e[t];return r&<.js+la(r)in n?lt.css+r:!1}},y$={flex:"box-flex","flex-grow":"box-flex","flex-direction":["box-orient","box-direction"],order:"box-ordinal-group","align-items":"box-align","flex-flow":["box-orient","box-direction"],"justify-content":"box-pack"},w_e=Object.keys(y$),S_e=function(t){return lt.css+t},j_e={supportedProperty:function(t,n,r){var s=r.multiple;if(w_e.indexOf(t)>-1){var i=y$[t];if(!Array.isArray(i))return lt.js+la(i)in n?lt.css+i:!1;if(!s)return!1;for(var o=0;o<i.length;o++)if(!(lt.js+la(i[0])in n))return!1;return i.map(S_e)}return!1}},v$=[s_e,i_e,l_e,c_e,d_e,u_e,p_e,h_e,f_e,m_e,g_e,x_e,b_e,y_e,C_e,j_e],$I=v$.filter(function(e){return e.supportedProperty}).map(function(e){return e.supportedProperty}),k_e=v$.filter(function(e){return e.noPrefill}).reduce(function(e,t){return e.push.apply(e,jW(t.noPrefill)),e},[]),ud,Ra={};if(Xu){ud=document.createElement("p");var bb=window.getComputedStyle(document.documentElement,"");for(var yb in bb)isNaN(yb)||(Ra[bb[yb]]=bb[yb]);k_e.forEach(function(e){return delete Ra[e]})}function Mv(e,t){if(t===void 0&&(t={}),!ud)return e;if(Ra[e]!=null)return Ra[e];(e==="transition"||e==="transform")&&(t[e]=e in ud.style);for(var n=0;n<$I.length&&(Ra[e]=$I[n](e,ud.style,t),!Ra[e]);n++);try{ud.style[e]=""}catch{return!1}return Ra[e]}var Po={},E_e={transition:1,"transition-property":1,"-webkit-transition":1,"-webkit-transition-property":1}
265,__e=/(^\s*[\w-]+)|, (\s*[\w-]+)(?![^()]*\))/g,Ni;function T_e(e,t,n){if(t==="var")return"var";if(t==="all")return"all";if(n==="all")return", all";var r=t?Mv(t):", "+Mv(n);return r||t||n}Xu&&(Ni=document.createElement("p"));function zI(e,t){var n=t;if(!Ni||e==="content")return t;if(typeof n!="string"||!isNaN(parseInt(n,10)))return n;var r=e+n;if(Po[r]!=null)return Po[r];try{Ni.style[e]=n}catch{return Po[r]=!1,!1}if(E_e[e])n=n.replace(__e,T_e);else if(Ni.style[e]===""&&(n=lt.css+n,n==="-ms-flex"&&(Ni.style[e]="-ms-flexbox"),Ni.style[e]=n,Ni.style[e]===""))return Po[r]=!1,!1;return Ni.style[e]="",Po[r]=n,Po[r]}function I_e(){function e(s){if(s.type==="keyframes"){var i=s;i.at=r_e(i.at)}}function t(s){for(var i in s){var o=s[i];if(i==="fallbacks"&&Array.isArray(o)){s[i]=o.map(t);continue}var l=!1,c=Mv(i);c&&c!==i&&(l=!0);var d=!1,u=zI(c,Ga(o));u&&u!==o&&(d=!0),(l||d)&&(l&&delete s[i],s[c||i]=u||o)}return s}function n(s,i){return i.type!=="style"?s:t(s)}function r(s,i){return zI(i,Ga(s))||s}return{onProcessRule:e,onProcessStyle:n,onChangeValue:r}}function D_e(){var e=function(n,r){return n.length===r.length?n>r?1:-1:n.length-r.length};return{onProcessStyle:function(n,r){if(r.type!=="style")return n;for(var s={},i=Object.keys(n).sort(e),o=0;o<i.length;o++)s[i[o]]=n[i[o]];return s}}}function A_e(){return{plugins:[LEe(),VEe(),qEe(),QEe(),ZEe(),typeof window>"u"?null:I_e(),D_e()]}}const M_e=c$(A_e()),R_e=PEe(),N_e=new Map,O_e={disableGeneration:!1,generateClassName:R_e,jss:M_e,sheetsCache:null,sheetsManager:N_e,sheetsRegistry:null},P_e=m.createContext(O_e);let BI=-1e9;function L_e(){return BI+=1,BI}const F_e=["variant"];function UI(e){return e.length===0}function $_e(e){const{variant:t}=e,n=Fh(e,F_e);let r=t||"";return Object.keys(n).sort().forEach(s=>{s==="color"?r+=UI(r)?e[s]:sh(e[s]):r+=`${UI(r)?s:sh(s)}${sh(e[s].toString())}`}),r}const z_e={};function B_e(e){const t=typeof e=="function";return{create:(n,r)=>{let s;try{s=t?e(n):e}catch(c){throw c}if(!r||!n.components||!n.components[r]||!n.components[r].styleOverrides&&!n.components[r].variants)return s;const i=n.components[r].styleOverrides||{},o=n.components[r].variants||[],l=Bs({},s);
265return Object.keys(i).forEach(c=>{l[c]=gj(l[c]||{},i[c])}),o.forEach(c=>{const d=$_e(c.props);l[d]=gj(l[d]||{},c.style)}),l},options:{}}}const U_e=["name","classNamePrefix","Component","defaultTheme"];function V_e({state:e,stylesOptions:t},n,r){if(t.disableGeneration)return n||{};e.cacheClasses||(e.cacheClasses={value:null,lastProp:null,lastJSS:{}});let s=!1;return e.classes!==e.cacheClasses.lastJSS&&(e.cacheClasses.lastJSS=e.classes,s=!0),n!==e.cacheClasses.lastProp&&(e.cacheClasses.lastProp=n,s=!0),s&&(e.cacheClasses.value=u$({baseClasses:e.cacheClasses.lastJSS,newClasses:n,Component:r})),e.cacheClasses.value}function W_e({state:e,theme:t,stylesOptions:n,stylesCreator:r,name:s},i){if(n.disableGeneration)return;let o=Ho.get(n.sheetsManager,r,t);o||(o={refs:0,staticSheet:null,dynamicStyles:null},Ho.set(n.sheetsManager,r,t,o));const l=Bs({},r.options,n,{theme:t,flip:typeof n.flip=="boolean"?n.flip:t.direction==="rtl"});l.generateId=l.serverGenerateClassName||l.generateClassName;const c=n.sheetsRegistry;if(o.refs===0){let d;n.sheetsCache&&(d=Ho.get(n.sheetsCache,r,t));const u=r.create(t,s);d||(d=n.jss.createStyleSheet(u,Bs({link:!1},l)),d.attach(),n.sheetsCache&&Ho.set(n.sheetsCache,r,t,d)),c&&c.add(d),o.staticSheet=d,o.dynamicStyles=d$(u)}if(o.dynamicStyles){const d=n.jss.createStyleSheet(o.dynamicStyles,Bs({link:!0},l));d.update(i),d.attach(),e.dynamicSheet=d,e.classes=u$({baseClasses:o.staticSheet.classes,newClasses:d.classes}),c&&c.add(d)}else e.classes=o.staticSheet.classes;o.refs+=1}function H_e({state:e},t){e.dynamicSheet&&e.dynamicSheet.update(t)}function q_e({state:e,theme:t,stylesOptions:n,stylesCreator:r}){if(n.disableGeneration)return;const s=Ho.get(n.sheetsManager,r,t);s.refs-=1;const i=n.sheetsRegistry;s.refs===0&&(Ho.delete(n.sheetsManager,r,t),n.jss.removeStyleSheet(s.staticSheet),i&&i.remove(s.staticSheet)),e.dynamicSheet&&(n.jss.removeStyleSheet(e.dynamicSheet),i&&i.remove(e.dynamicSheet))}function G_e(e,t){const n=m.useRef([]);let r;const s=m.useMemo(()=>({}),t);n.current!==s&&(n.current=s,r=e()),m.useEffect(()=>()=>{r&&r()},[s])}function Y_e(e,t={}){const{name:n,classNamePrefix:r,Component:s,defaultTheme:i=z_e}=t,o=Fh(t,U_e),l=B_e(e),c=n||r||"makeStyles";return l.options={index:L_e(),name:n,meta:c,classNamePrefix:c},(u={})=>{const p=p$()||i,h=Bs({},m.useContext(P_e),o),f=m.useRef(),g=m.useRef();return G_e(()=>{const b={name:n,state:{},stylesCreator:l,stylesOptions:h,theme:p};return W_e(b,u),g.current=!1,f.current=b,()=>{q_e(b)}},[p,l]),m.useEffect(()=>{g.current&&H_e(f.current,u),g.current=!0}),V_e(f.current,u.classes,s)}}function K_e(e){const{theme:t,name:n,props:r}=e;if(!t||!t.components||!t.components[n]||!t.components[n].defaultProps)return r;const s=Bs({},r),i=t.components[n].defaultProps;let o;for(o in i)s[o]===void 0&&(s[o]=i[o]);return s}const Q_e=["defaultTheme","withTheme","name"],J_e=["classes"],Be=(e,t={})=>n=>{const{defaultTheme:r,withTheme:s=!1,name:i}=t,o=Fh(t,Q_e);let l=i;const c=Y_e(e,Bs({defaultTheme:r,Component:n,name:i||n.displayName,classNamePrefix:l},o)),d=m.forwardRef(function(p,h){const f=Fh(p,J_e),g=c(Bs({},n.defaultProps,p));let x,b=f;return(typeof i=="string"||s)&&(x=p$()||r,i&&(b=K_e({theme:x,name:i,props:f})),s&&!b.theme&&(b.theme=x)),a.jsx(n,Bs({ref:h,classes:g},b))});return Xz(d,n),d},X_e=()=>({container:{display:"flex",flexDirection:"row",alignItems:"flex-end"},formControl:{marginTop:2,marginRight:5,"& div":{"&:focus":{backgroundColor:"transparent"}}},label:{marginRight:12,marginBottom:10},menuItems:{fontSize:14},selectValue:{fontSize:14,"& svg":{paddingBottom:5}}}),Z_e=25,eTe=[5,10,25,50,100],Yw=({attributeName:e,classes:t,onChangeView:n,pageSize:r})=>{const[s,i]=m.useState(r),o=a.jsx(I,{variant:"body1",className:t.label,children:"Rows per page"}),l=eTe.map((d,u)=>a.jsx(Se,{value:d,id:`${e}-page-size-menu-item-${d}`,className:t.menuItems,children:d},u)),c=a.jsx(Qe,{className:t.formControl,children:a.jsx(tt,{className:t.selectValue,SelectDisplayProps:{id:`${e}-page-size-select-display`},MenuProps:{disableAutoFocusItem:!0,id:`${e}-page-size-select-menu`,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},PaperProps:{style:{marginTop:-20,maxHeight:150,width:60}}},onChange:d=>{const{target:u}=d,{value:p}=u;i(p),n(p)},value:s,children:l})});return a.jsxs("div",{className:t.container,children:[o,c]})};Yw.propTypes={attributeName:A.string.isRequired,classes:A.object.isRequired,onChangeView:A.func.isRequired,pageSize:A.number};Yw.defaultProps={pageSize:Z_e};const tTe=Be(X_e)(Yw),nTe=()=>({root:{alignItems:"center",display:"flex",justifyContent:"flex-end",marginTop:10},arrow:{}}),Kw=({attributeName:e,classes:t,controlPageSizeBool:n,pageSize:r,currentPage:s,total:i,onChangePageSize:o,onGoForward:l,onGoBackward:c})=>{if(i===0||i<=r)return null;const d=s*r+1;let u=d+r-1;u>i&&(u=i);
265const p=a.jsx(tTe,{attributeName:e,onChangeView:o,pageSize:r});return a.jsxs("div",{className:t.root,children:[n?p:null,a.jsx(I,{children:`${d}-${u} of ${i}`}),a.jsx(He,{"data-testid":"button-back",id:`${e}-paginator-back-button`,onClick:c,children:a.jsx(G1e,{className:t.arrow})}),a.jsx(He,{"data-testid":"button-forward",id:`${e}-paginator-forward-button`,onClick:l,children:a.jsx(Q1e,{className:t.arrow})})]})};Kw.propTypes={attributeName:A.string,classes:A.object.isRequired,controlPageSizeBool:A.bool,currentPage:A.number.isRequired,onChangePageSize:A.func,onGoBackward:A.func.isRequired,onGoForward:A.func.isRequired,pageSize:A.number.isRequired,total:A.number.isRequired};Kw.defaultProps={attributeName:"",controlPageSizeBool:!1,onChangePageSize:()=>{}};const Qw=Be(nTe)(Kw),rTe=({completed:e})=>a.jsxs(T,{sx:{alignItems:"center",display:"flex",flexDirection:"row",justifyContent:"space-between",mt:4.5},children:[a.jsx(lo,{sx:{flexGrow:1},variant:"determinate",value:e}),a.jsx(I,{sx:{alignSelf:"flex-end",flexBasis:"40px",flexGrow:0,color:"secondary.main",minWidth:"55px",textAlign:"right"},variant:"body2",children:`${e} %`})]}),C$=({id:e="progress-modal",show:t,message:n,percentComplete:r,variant:s="progressBar"})=>a.jsx(cB,{open:t,id:e,children:a.jsxs(T,{sx:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",backgroundColor:"background.paper",boxShadow:24,p:3,outline:"none",minWidth:300},children:[a.jsx(I,{children:n}),s==="progressBar"?a.jsx(rTe,{completed:Math.trunc(r*100)}):a.jsx(T,{sx:{mt:2.5,display:"flex",justifyContent:"center"},children:a.jsx(Ze,{size:25})})]})}),w$=({addNewText:e,onClickCreate:t})=>a.jsx(He,{onClick:t,children:a.jsxs(dB,{children:[a.jsx(ca,{size:20}),a.jsx(I,{sx:{marginLeft:"10px"},children:e})]})});w$.propTypes={addNewText:A.string.isRequired,onClickCreate:A.func.isRequired};const S$=({children:e})=>a.jsx(I,{sx:{fontSize:12,fontStyle:"italic",marginLeft:"18px"},variant:"body1",children:e});S$.propTypes={children:A.string.isRequired};const Jw=({disabled:e})=>a.jsx(Bn,{position:"end",children:a.jsx(T,{sx:{color:e?"text.disabled":"text.secondary",marginTop:"11px",display:"flex"},children:a.jsx(er,{size:20})})});Jw.defaultProps={disabled:!1};Jw.propTypes={disabled:A.bool};const Xw=Ne.forwardRef(({disabled:e,error:t,errorText:n,filterFunction:r,id:s,items:i,onChange:o,placeholder:l,searchTerm:c,showSearchAdornment:d,...u},p)=>a.jsx(T,{sx:{paddingBottom:"10px",paddingLeft:"15px",paddingRight:"15px"},ref:p,...u,children:a.jsx(De,{sx:{pointerEvents:e?"none":"inherit"},disabled:e,error:t,helperText:t&&n,InputProps:{id:`${s}-search-input`,endAdornment:d?a.jsx(Jw,{disabled:e}):null},onChange:({target:h})=>{const{value:f}=h,g=f===""?i:i.filter(x=>r(x,f));o(g,f)},onKeyDown:h=>h.stopPropagation(),placeholder:l,style:{width:"100%"},value:c,variant:"standard"})}));Xw.propTypes={disabled:A.bool,error:A.bool,errorText:A.string,id:A.string.isRequired,items:A.array,onChange:A.func,placeholder:A.string,filterFunction:A.func,searchTerm:A.string,showSearchAdornment:A.bool};Xw.defaultProps={disabled:!1,error:!1,errorText:"",items:[],onChange:()=>{},placeholder:"Search",filterFunction:(e,t)=>e!==t,searchTerm:"",showSearchAdornment:!1};const Zw=({id:e,index:t,label:n,numberOfItems:r,onReorderDown:s,onReorderUp:i})=>a.jsxs(T,{sx:{display:"flex","& button":{marginBottom:"2px",marginTop:"2px"},"& p":{left:"6px !important"},"& svg":{height:"12px"}},children:[a.jsxs(T,{sx:{marginTop:"3px",marginLeft:"10px",display:"flex",flexWrap:"wrap",flexDirection:"column","& button":{padding:0}},children:[a.jsx(Ie,{id:`${e}-reorder-up-button-${t}`,onClick:()=>i(t),sx:{visibility:t===0?"hidden":"visible",paddingRight:"10px","&:hover":{background:"transparent",boxShadow:"none"},"&:disabled":{opacity:.25},color:"secondary.main"},size:"large",children:a.jsx(Qv,{size:18})}),a.jsx(Ie,{id:`${e}-reorder-down-button-${t}`,onClick:()=>s(t),sx:{visibility:t===r-1?"hidden":"visible",paddingRight:"10px","&:hover":{background:"transparent",boxShadow:"none"},"&:disabled":{opacity:.25},color:"secondary.main"},size:"large",children:a.jsx(vs,{size:18})})]}),a.jsx(I,{children:a.jsx("strong",{children:n})})]});Zw.propTypes={id:A.string.isRequired,index:A.number.isRequired,label:A.string,numberOfItems:A.number.isRequired,onReorderDown:A.func.isRequired,onReorderUp:A.func.isRequired};Zw.defaultProps={label:""};const eS=({editable:e,id:t,onEdit:n,onDeselect:r,onSelect:s,orderLabels:i,renderSelectedItem:o,reorderable:l,selectedItems:c,width:d})=>c.map((u,p)=>a.jsxs(T,{sx:{display:"flex",alignItems:"center",marginTop:20,"& p":{position:"relative",left:-6},"& div":{display:"flex",alignItems:"center"}},children:[a.jsxs(T,{sx:{width:d},children:[a.jsx(Ie,{sx:{padding:0,marginRight:"15px",color:"text.primary","&:active":{backgroundColor:"common.white"},"&:hover":{backgroundColor:"common.white"}},id:`${t}-remove-button-${p}`,onClick:()=>{r(u)},size:"large",children:a.jsx(Kv,{size:20})}),e&&a.jsx(Ie,{sx:{padding:0,marginRight:"15px",color:"text.primary","&:active":{backgroundColor:"common.white"},"&:hover":{backgroundColor:"common.white"}},id:`${t}-edit-button-${p}`,action:()=>n(u),size:"large",children:a.jsx(ou,{size:20})}),a.jsx(I,{children:o(u)})]}),l&&a.jsx(Zw,{index:p,label:i[p],numberOfItems:c.length,id:t,onReorderDown:()=>{let h=[...c];const f=h.splice(p,1)[0],g=h.slice(0,p+1),x=h.slice(p+1);h=[...g,f,...x],s(h.map(b=>b.value))},onReorderUp:()=>{let h=[...c];const f=h.splice(p,1)[0],g=h.slice(0,p-1),x=h.slice(p-1);h=[...g,f,...x],s(h.map(b=>b.value))}})]},`selected-item-${p}-${u}`));eS.defaultProps={editable:!1,onEdit:()=>{},onDeselect:()=>{},onSelect:()=>{},orderLabels:[],renderSelectedItem:e=>e.label||e.value,reorderable:!1,selectedItems:[],width:300};eS.propTypes={editable:A.bool,id:A.string.isRequired,onEdit:A.func,onDeselect:A.func.isRequired,onSelect:A.func,orderLabels:A.array,renderSelectedItem:A.func,reorderable:A.bool,selectedItems:A.array,width:A.number};const kg=({addNewText:e,children:t,creatable:n,disabled:r,editable:s,error:i,errorText:o,filterFunction:l,id:c,instruction:d,inputId:u,items:p,label:h,maxSelectedItems:f,menuListId:g,multiple:x,onChange:b,onChangeSearch:y,onClickCreate:v,onEdit:C,orderLabels:w,placeholder:S,renderMenuItem:E,renderSelectedItem:k,reorderable:j,searchable:_,showSkeleton:D,selectDisplayId:M,showSearchAdornment:N,style:O,value:R,valueReturnType:L,width:P,...F})=>{if(x&&!Array.isArray(R))throw Error('If prop "multiple" is set to true, value must be an array');const[z,B]=m.useState(null),[W,H]=m.useState([]),[V,G]=m.useState(""),X=Y=>x&&f?Y.slice(0,f):Y,K=Y=>{b(X(Y)),G(""),H(p)},ie=Y=>x?Y.map(ae=>p.findIndex(je=>je.value===ae)):p.findIndex(ae=>ae.value===R),le=Y=>x?R.includes(Y.value):!1,ce=R?ie(R):[];Kn(p,z)||(B(p),H(p));const J=x?ce.filter(Y=>Y!==-1).map(Y=>
265p[Y]):p[ce],he=_&&a.jsx(Xw,{filterFunction:l,id:c,items:p,onChange:(Y,ae)=>{H(Y),G(ae),y(ae)},searchTerm:V,showSearchAdornment:N}),ne=a.jsx(fe,{height:27,variant:"rectangular",width:P});return a.jsxs(Qe,{sx:{marginTop:"25px",marginBottom:"10px"},style:O,children:[a.jsx(wt,{id:`${c}-input-label`,sx:{top:"-15px"},disabled:r,error:i,shrink:!0,children:h}),a.jsxs(T,{sx:{alignItems:"flex-end",display:"flex",flexDirection:"row"},children:[D?ne:a.jsxs(tt,{disabled:r,displayEmpty:!0,error:i,id:c,SelectDisplayProps:{id:M||`${c}-select`},MenuProps:{anchorOrigin:{vertical:"bottom",horizontal:"left"},disableAutoFocusItem:!0,id:`${c}-menu`,marginThreshold:0,MenuListProps:{id:g||`${c}-menu-list`},transformOrigin:{vertical:"top",horizontal:"left"},PaperProps:{id:`${c}-paper`,style:{marginTop:10,maxHeight:224,width:P}},TransitionProps:{onEnter:()=>{H(p)}}},inputProps:{classes:{root:{width:"100%"}},id:u||`${h}-input`},multiple:x,onChange:Y=>{const ae=Y.target.value;if(x&&ae[0]===void 0){Y.preventDefault(),Y.stopPropagation();return}K(L==="value"?ae:Y),G("")},sx:{color:R?"text.primary":"text.disabled",width:P},value:R||"",variant:"standard",...F,children:[he,n&&a.jsx(w$,{addNewText:e,onClickCreate:()=>{const Y=v();Y!==void 0&&!Y&&G("")}}),W.filter(Y=>!le(Y)).map(Y=>E(Y))]}),a.jsx(S$,{children:d})]}),i&&a.jsx(Zn,{error:!0,children:o}),x&&p.length>0&&a.jsx(eS,{editable:s,id:c,onEdit:K,onDeselect:Y=>{const ae=R.indexOf(Y.value);K([...R.slice(0,ae),...R.slice(ae+1)])},onSelect:K,orderLabels:w,reorderable:j,selectedItems:J,width:P})]})};kg.propTypes={addNewText:A.string,children:A.object,creatable:A.bool,disabled:A.bool,editable:A.bool,error:A.bool,errorText:A.string,filterFunction:A.func,id:A.string,inputId:A.string,instruction:A.string,items:A.array.isRequired,label:A.string,maxSelectedItems:A.number,menuListId:A.string,multiple:A.bool,onChange:A.func,onChangeSearch:A.func,onClickCreate:A.func,onEdit:A.func,orderLabels:A.array,placeholder:A.string,renderMenuItem:A.func,renderSelectedItem:A.func,reorderable:A.bool,searchable:A.bool,showSkeleton:A.bool,selectDisplayId:A.string,showSearchAdornment:A.bool,style:A.object,value:A.oneOfType([A.array,A.number,A.string]),valueReturnType:A.string,width:A.oneOfType([A.number,A.string])};kg.defaultProps={addNewText:"Add new",children:null,creatable:!1,disabled:!1,editable:!1,errorText:"Please enter the value",id:"my-super-select",inputId:null,instruction:"",error:!1,label:"",maxSelectedItems:null,menuListId:null,multiple:!1,onChange:()=>{},onChangeSearch:()=>{},onClickCreate:()=>{},onEdit:()=>{},orderLabels:[],placeholder:"",renderMenuItem:e=>a.jsx(Se,{id:`item-${vM(e.value)}`,value:e.value,children:e.label},`item-${e.value}`),renderSelectedItem:e=>e.label||e.value,reorderable:!1,searchable:!1,showSkeleton:!1,selectDisplayId:null,showSearchAdornment:!1,style:{},filterFunction:(e,t)=>e.value.toLowerCase().includes(t.toLowerCase()),value:"",valueReturnType:"value",width:300};const Zo=({color:e,count:t=0,label:n,tooltip:r=""})=>a.jsx(be,{title:r,placement:"top",children:a.jsxs($,{direction:"row",sx:{alignItems:"center"},children:[a.jsx(T,{id:`tally-box-${n.toLowerCase()}`,"data-testid":`tally-box-${n.toLowerCase()}`,sx:{backgroundColor:e,border:e==="common.white"?"1px solid":"none",borderColor:e==="common.white"?"secondary.main":"none",minHeight:"17px",minWidth:"15px",mr:.75,p:"0 3px 1px",textAlign:"center"},children:a.jsx(I,{component:"span",sx:{color:e==="common.white"?"primary.main":"white",fontSize:12},children:t})}),a.jsx(I,{sx:{mr:2.5},variant:"body2",children:n})]})}),Rs={ERROR:"error",RESOLVED:"resolved",WARNING:"warning"},Yi={errorRow:"checkbox-alert-error",warningRow:"checkbox-alert-warning",resolvedRow:"checkbox-alert-resolved",checkboxHeader:"checkbox-header"},qc=[{label:"Warnings",value:"warning"},{label:"Errors",value:"error"},{label:"Resolved",value:"resolved"}],sTe={warning:{id:1,field:"log_level",operator:"equals",value:"Warning"},error:{id:2,field:"log_level",operator:"equals",value:"Error"},resolved:{id:3,field:"log_level",operator:"equals",value:"Resolved"}},VI={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Gc={flex:1,headerAlign:"left",minWidth:100},tS=[{...SW,cellClassName:({row:e})=>!e?.log_level||e?.resolved?Yi.resolvedRow:e.log_level==="error"?Yi.errorRow:Yi.warningRow,headerClassName:Yi.checkboxHeader,minWidth:55}
265,{...Gc,field:"log_level",filterable:!1,flex:.25,headerName:"Type",minWidth:50,valueGetter:e=>Pr(e.row.resolved?Rs.RESOLVED:e.row.log_level)},{...Gc,field:"datasource",headerName:"Data Source",minWidth:50,renderCell:({row:e})=>a.jsxs(I,{sx:VI,children:[e.datasource," (",e.datasource_id,")"]})},{...Gc,field:"log_message",flex:4,headerName:"Alert",renderCell:({row:e})=>a.jsxs(I,{sx:VI,children:[a.jsxs("strong",{children:[Pr(e.log_level),":"]})," ",e.log_message]})},{...Gc,disableColumnMenu:!0,disableExport:!0,field:"log_url",filterable:!1,headerName:"Cloudwatch Log",minWidth:125,renderCell:({row:e})=>a.jsx(xm,{href:e.log_url,rel:"noreferrer",target:"_blank",underline:"hover",children:"Go to Cloudwatch"}),sortable:!1},{...Gc,field:"timestamp",headerName:"Created On",minWidth:110,type:"dateTime",valueGetter:e=>e.value&&Z(e.value).toDate()}],j$=(e,t=!1)=>{const n={};return e.forEach(r=>{r.field!=="__check__"&&(n[r.field]=t||r.field!=="log_url")}),n},iTe=j$(tS),aTe=j$(tS,!0),vb="_selectAll",oTe=({apiRef:e,disabled:t})=>{const[n,r]=m.useState(qc.map(u=>u.value)),[s,i]=m.useState(""),o=n.length===qc.length,l=m.useMemo(()=>gm(u=>{e.current.setQuickFilterValues(u.split(" ").filter(p=>p!==""))},150),[e]),c=u=>{const p=u.target.value;i(p),l(p)},d=u=>{const{value:p}=u.target,h=typeof p=="string"?p.split(","):p;let f=[];h.includes(vb)?f=o?[]:qc.map(g=>g.value):f=h.filter(g=>g!==vb),r(f)};return m.useEffect(()=>{if(!n?.length||n.length===qc.length){e.current.setFilterModel({items:[]});return}const u=n.map(p=>sTe[p]).filter(p=>p!==void 0);e.current.setFilterModel({items:u,logicOperator:rl.Or})},[e,n]),a.jsxs($,{direction:"row",justifyContent:"space-between",py:3,children:[a.jsxs(tt,{multiple:!0,disabled:t,displayEmpty:!0,id:"alerts-table-view-select",value:n,onChange:d,renderValue:()=>a.jsxs($,{direction:"row",gap:1,sx:{color:t?"text.disabled":"text.secondary",alignItems:"center"},children:[a.jsx(VU,{size:19}),a.jsx(I,{component:"span",children:"Table View"})]}),sx:{height:42,width:175},children:[a.jsxs(Se,{className:o?"Mui-selected":"",value:vb,children:[a.jsx(et,{checked:o,indeterminate:!!n.length&&!o}),a.jsx(Kt,{primary:"Select All"})]}),a.jsx(St,{}),qc.map(u=>a.jsxs(Se,{value:u.value,sx:{height:48},children:[a.jsx(et,{checked:n.includes(u.value)}),a.jsx(Kt,{primary:u.label})]},u.value))]}),a.jsx(Qe,{children:a.jsx(ys,{disabled:t,startAdornment:a.jsx(Mt,{sx:{color:"text.disabled"},children:a.jsx(er,{size:20})}),onChange:c,placeholder:"Search",sx:{borderRadius:1,height:42,width:228,px:1.5,".MuiInputBase-inputAdornedStart":{pl:1.5,pr:0,height:24},"&.Mui-focused":{".MuiOutlinedInput-notchedOutline":{boxShadow:"none"}}},value:s})})]})},WI=()=>a.jsx(T,{sx:{display:"flex",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"},children:a.jsx(I,{children:"No data available."})}),Rv=rt(Mn)(({theme:e})=>{const{palette:t,spacing:n}=e,{background:r,border:s,text:i}=t;return{border:"none",[`& .${xe.main}`]:{borderRadius:n(2)},[`& .${xe.columnHeaders}`]:{backgroundColor:r.tableHeader,borderBottom:"none"},[`& .${xe.columnHeader}`]:{fontSize:12,height:18,textTransform:"uppercase",color:i.secondary,":focus":{outline:"none"},":focus-within":{outline:"none"}},[`& .${xe.columnHeaderCheckbox}`]:{paddingLeft:n(1.75)},[`& .${xe.columnSeparator}`]:{color:s.default,":hover":{color:s.default}},[`& .${xe.row}`]:{backgroundColor:r.paper,borderRadius:n(1),":hover":{backgroundColor:e.palette.mode==="dark"?r.brand.subtle.hovered:r.brand.subtlest.default}},[`& .${xe.cell}`]:{border:"none",":focus":{outline:"none"},":focus-within":{outline:"none"}},[`& .${Yi.errorRow}`]:{borderLeft:`10px solid ${t.error.main}`},[`& .${Yi.warningRow}`]:{borderLeft:`10px solid ${t.warning.main}`},[`& .${Yi.resolvedRow}`]:{borderLeft:`10px solid ${t.success.main}`},[`& .${Yi.checkboxHeader}`]:{paddingLeft:n(1.75)},[`& .${xe.footerContainer}`]:{border:"none"}}});Rv.defaultProps={...Rv.defaultProps,columnHeaderHeight:50,disableRowSelectionOnClick:!0,getRowSpacing:()=>({top:0,bottom:8}),pageSizeOptions:[10,25,50],pagination:!0,rowHeight:60};const lTe=({alerts:e,apiRef:t,isFetching:n,isInternalUser:r})=>{const s=r?aTe:iTe;return a.jsxs(T,{children:[a.jsx(oTe,{apiRef:t,disabled:n}),a.jsx(T,{sx:{display:"grid",minHeight:250},children:a.jsx(Rv,{apiRef:t,checkboxSelection:!0,columns:tS,columnVisibilityModel:s,initialState:{pagination:{paginationModel:{pageSize:10}}},isRowSelectable:({row:i})=>!i?.resolved,loading:n,rows:e||[],slots:{loadingOverlay:Cs,noRowsOverlay:WI,noResultsOverlay:WI}})})]})},cTe=e=>({badge:{alignItems:"center",backgroundColor:e.palette.error.main,borderRadius:31,display:"flex",height:30,justifyContent:"center",marginRight:15,textAlign:"center",width:30},badgeText:{color:e.palette.common.white,fontFamily:e.typography.fontFamily,fontSize:16},container:{display:"flex",alignItems:"center",marginBottom:15}}),nS=({classes:e,count:t})=>a.jsxs("div",{className:e.container,children:[a.jsx("div",{className:e.badge,children:a.jsx("span",{className:e.badgeText,children:t>99?"99+":t})}),a.jsx(I,{sx:{fontSize:"16px"},children:"Alerts"})]});nS.propTypes={classes:A.object.isRequired,count:A.number};nS.defaultProps={count:0};const dTe=Be(cTe)(nS),uTe=()=>{const{palette:e}=Re(),{userIsInternal:t}=gt(),{clientNiceId:n,engagementNiceId:r}=pe(),{dataIngestionAlerts:s,alertsLoading:i}=MC({clientNiceId:n,engagementNiceId:r,userIsInternal:t}),[o,{isLoading:l}]=P3(),c=zn(),d=m.useMemo(()=>s.reduce((p,h)=>{const f=h.resolved?Rs.RESOLVED:h.log_level;return{...p,[f]:p[f]+1}},{[Rs.ERROR]:0,[Rs.WARNING]:0,[Rs.RESOLVED]:0}),[s]),u=async()=>{const p=Object.keys(c.current).length?c.current.getSelectedRows():new Map,h=s.filter(({id:f})=>p.has(f));h.length&&(o({alerts:h,clientNiceId:n,engagementNiceId:r}),c.current.setRowSelectionModel([]))};return a.jsxs(T,{sx:{width:ks},id:"alerts",children:[a.jsx(dTe,{count:d[Rs.ERROR]+d[Rs.WARNING]}),a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",mt:5},children:[a.jsxs(T,{sx:{display:"flex"},children:[a.jsx(Zo,{color:e.error.main,count:d[Rs.ERROR],label:"Errors"}),a.jsx(Zo,{color:e.warning.main,count:d[Rs.WARNING],label:"Warnings"}),a.jsx(Zo,{color:e.success.main,count:d[Rs.RESOLVED],label:"Resolved"})]}),a.jsx(re,{sx:{padding:"12px 14px"},disabled:l,id:"resolve-alerts-button",onClick:u,variant:"contained",children:"RESOLVE"})]}),a.jsx(lTe,{alerts:s,apiRef:c,isFetching:i,isInternalUser:t})]})},k$=Object.freeze({EMPTY_STRING:"Please fill in a field, or uncheck the box",DUPLICATES:"Duplicate classifications can not be used",DUPLICATES_TAB:"Duplicate found in other tab",INVALID_CHARACTERS:"Names can't include ( or )"}),pTe=e=>!(e.every(t=>t.includes("attribute"))||e.every(t=>!t.includes("attribute"))),hTe=e=>{const{creative:t,kpi:n,media:r}=e.attributes,s={...t,...n,...r,...e.mediaContainers},i={};
265return Object.entries(s).forEach(([o,{value:l}])=>{l in i?i[l]?.push(o):i[l]=[o]}),Object.fromEntries(Object.entries(i).filter(([o,l])=>o&&l.length>1).map(([o,l])=>{const c=pTe(l);return[o,{keys:l,acrossTabs:c}]}))},E$=[1,2,3,4,5,6,7,8],el=(e,t)=>{const r=!(e==="theme");return E$.reduce((s,i)=>({...s,[`${e}_${i}`]:{active:r,error:{duplicate:!1,duplicateOtherTab:!1},label:`${t} ${i}`,original:{active:r,value:""},value:""}}),{})},_$=()=>{const t={type:{label:"Media Type",value:""},vehicle:{label:"Vehicle",value:""},platform:{label:"Platform",value:""},tactic:{label:"Tactic",value:""},program_name:{label:"Program",value:""},country:{label:"Country",value:""},market:{label:"Media Market",value:""},data_source:{label:"Data Source",value:""},vendor:{label:"Vendor",value:""}},n={account_name:{label:"Account Name",value:""},account_id:{label:"Account ID",value:""},campaign_name:{label:"Campaign Name",value:""},campaign_id:{label:"Campaign ID",value:""},ad_group_name:{label:"Ad Group Name",value:""},ad_group_id:{label:"Ad Group ID",value:""},placement_name:{label:"Placement Name",value:""}},r=E$.reduce((i,o)=>({...i,[`media_attribute_${o}`]:{active:!0,error:{duplicate:!1,duplicateOtherTab:!1},label:`Media Attribute ${o}`,original:{active:!0,value:""},value:""}}),{}),s={...t,...n};return Object.entries(s).reduce((i,[o,{label:l,value:c}])=>({...i,[o]:{active:!0,error:{duplicate:!1,duplicateOtherTab:!1},label:l,original:{active:!0,value:c},value:c}}),r)},fTe=()=>({attributes:{creative:el("creative_attribute","Creative Attribute"),kpi:el("kpi_attribute","KPI Attribute"),media:_$()},mediaContainers:el("theme","Theme")}),mTe=/^theme_\d+$/,T$=/^(media|creative|kpi)_attribute_\d+$/,gTe=["attribute_1","attribute_2","attribute_3","attribute_4","attribute_5","attribute_6","attribute_7","attribute_8"],lm=["type","vehicle","platform","tactic","program_name","country","market","data_source","vendor","account_name","account_id","campaign_name","campaign_id","ad_group_name","ad_group_id","placement_name"],xTe={type:"type_name",vehicle:"vehicle_name",platform:"platform_name",tactic:"tactic_name",account_name:"account_name",campaign_name:"campaign_name",ad_group_name:"adgroup_name",placement_name:"name",program_name:"program_name",account_id:"account_id",campaign_id:"campaign_id",ad_group_id:"adgroup_id",country:"country_name",market:"market_name",data_source:"datasource_name",vendor:"vendor_nice_id"},bTe={type_name:"type",vehicle_name:"vehicle",platform_name:"platform",tactic_name:"tactic",adgroup_name:"ad_group_name",name:"placement_name",adgroup_id:"ad_group_id",country_name:"country",market_name:"market",datasource_name:"data_source",vendor_nice_id:"vendor"},yTe={type:"Media Type",vehicle:"Vehicle",platform:"Platform",tactic:"Tactic",program_name:"Program",country:"Country",market:"Media Market",data_source:"Data Source",vendor:"Vendor",account_name:"Account Name",account_id:"Account ID",campaign_name:"Campaign Name",campaign_id:"Campaign ID",ad_group_name:"Ad Group Name",ad_group_id:"Ad Group ID",placement_name:"Placement Name"},Mh=(e=[])=>e.reduce((t,n)=>{const{active:r,dimension:s,dimension_type:i,title:o}=n;let l;const c=s.startsWith("theme"),d=gTe.includes(s),u=T$.test(s),p=bTe[s],h=lm.includes(s)||p;c?l=s:p?l=p:lm.includes(s)||u?l=s:d?l=`${i}_${s}`:l=`${i}_${s}`;let f;c?f=Pr(s).replaceAll("_"," "):h?f=yTe[l]||Pr(s).replaceAll("_"," "):i==="media"?f=`Media Attribute ${s.replace("attribute_","")}`:i==="creative"?f=`Creative Attribute ${s.replace("attribute_","")}`:i==="kpi"?f=`KPI Attribute ${s.replace("attribute_","")}`:f=Pr(s).replaceAll("_"," ");const g=t[l],x=r||o&&o.length>0,b=g&&(g.active||g.value.length>0);return(!g||x&&!b)&&(t[l]={active:r,label:f,error:{duplicate:!1,duplicateOtherTab:!1},original:{active:r,value:o||""},value:o||""}),t},{}),vTe=e=>{const t=el("creative_attribute","Creative Attribute"),n=el("kpi_attribute","KPI Attribute"),r=_$(),s=Mh(e.filter(({dimension_type:u})=>u==="creative")),i=Mh(e.filter(({dimension_type:u})=>u==="kpi")),o=Mh(e.filter(({dimension_type:u})=>u==="media")),l={...t,...s},c={...n,...i},d={...r,...o};return{creative:l,kpi:c,media:d}},CTe=e=>{const t=el("theme","Theme"),n=Mh(e);return{...t,...n}},Kp=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>{const{original:r}=n,s={...n,active:r.active,error:{duplicate:!1,duplicateOtherTab:!1},value:r.value};return[t,s]})),HI=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>{const r={...n,active:!1,value:""};return[t,r]})),Qp=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>{const r={...n,active:!1,value:"",error:{duplicate:!1,duplicateOtherTab:!1}};return[t,r]})),Jp=(e,t)=>Object.entries(e).filter(([n])=>t?mTe.test(n):T$.test(n)||lm.includes(n)).map(([n,{active:r,label:s,value:i}])=>{let o;if(t)o=n;else if(lm.includes(n))o=xTe[n]||n;else{const l=n.split("_");o=`attribute_${l[l.length-1]}`}return{active:r,dimension:o,title:i||s}}),wTe=/[()]/,rS=e=>wTe.test(e),STe=e=>{const{creative:t,kpi:n,media:r}=e.attributes,s={...t,...n,...r,...e.mediaContainers};return Object.values(s).some(({value:i})=>rS(i))},jTe=(e,t)=>
265{switch(t.type){case"resetToDefaults":return{...e,mediaContainers:Qp(e.mediaContainers),attributes:{creative:Qp(e.attributes.creative),kpi:Qp(e.attributes.kpi),media:Qp(e.attributes.media)}};case"initMediaContainers":return{...e,mediaContainers:CTe(t.value)};case"initAttributes":return{...e,attributes:vTe(t.value)};case"resetToOriginals":if(t.value==="attributes"){const{creative:n,kpi:r,media:s}=e.attributes;return{...e,attributes:{creative:Kp(n),kpi:Kp(r),media:Kp(s)}}}return{...e,mediaContainers:Kp(e.mediaContainers)};case"clear":return t.containerType==="mediaContainer"?{...e,mediaContainers:HI(e.mediaContainers)}:{...e,attributes:{...e.attributes,[t.containerType]:HI(e.attributes[t.containerType])}};case"updateValue":if(t.containerType==="mediaContainer"&&t.value.keyName in e.mediaContainers){const{keyName:n,newValue:r}=t.value,s=e.mediaContainers[n];return{...e,mediaContainers:{...e.mediaContainers,[n]:{...s,value:r}}}}if(t.containerType!=="mediaContainer"&&t.value.keyName in e.attributes[t.containerType]){const{containerType:n}=t,{keyName:r,newValue:s}=t.value,i=e.attributes[n],o=i[r];return{...e,attributes:{...e.attributes,[n]:{...i,[r]:{...o,value:s}}}}}return e;case"updateActive":if(t.containerType==="mediaContainer"&&t.value.keyName in e.mediaContainers
265){const{keyName:n,active:r}=t.value,s=e.mediaContainers[n];return{...e,mediaContainers:{...e.mediaContainers,[n]:{...s,active:r}}}}if(t.containerType!=="mediaContainer"&&t.value.keyName in e.attributes[t.containerType]){const{containerType:n}=t,{keyName:r,active:s}=t.value,i=e.attributes[n],o=i[r];return{...e,attributes:{...e.attributes,[n]:{...i,[r]:{...o,active:s}}}}}return e;default:return e}},kTe=e=>{const{engagementId:t,engagementNiceId:n}=pe(),{data:r=[]}=Qs(t),{data:s=[],isFetching:i,refetch:o}=dC({engagementNiceId:n,brandNiceId:e?.brand_nice_id||""},{skip:!n||!e}),{data:l=[],isFetching:c,refetch:d}=wm({engagementNiceId:n,brandNiceId:e?.brand_nice_id||""},{skip:!n||!e}),[u,p]=m.useReducer(jTe,fTe()),h=i||c,f=m.useMemo(()=>e?.brand_nice_id||"",[e?.brand_nice_id]),g=m.useRef(null),x=m.useRef(null);return m.useEffect(()=>{f&&f!==g.current&&(g.current=null),f&&f!==x.current&&(x.current=null)},[f]),m.useEffect(()=>{s.length&&!i&&g.current!==f&&(p({type:"initMediaContainers",value:s}),g.current=f)},[s,i,f]),m.useEffect(()=>{l.length&&!c&&x.current!==f&&(p({type:"initAttributes",value:l}),x.current=f)},[l,c,f]),{brands:r,containerDispatch:p,containerState:u,engagementId:t,engagementNiceId:n,fetchingData:h,refetchAllData:async()=>{g.current=null,x.current=null,await Promise.all([o(),d()])}}},qI="DASHBOARDADMIN MANAGECONTENT ACTIONS",ETe={saveAttributions:"SAVE ATTRIBUTIONS",saveThemes:"MEDIA - SAVE THEMES",download:"MEDIA - DOWNLOAD",upload:"MEDIA - UPLOAD",rebuild:"MEDIA - REBUILD CONTAINERS",step1To2:"MEDIA - MOVE TO STEP 1 FROM 2",step2To1:"MEDIA - MOVE TO STEP 2 FROM 1",step2To3:"MEDIA - MOVE TO STEP 2 FROM 3",step3To2:"MEDIA - MOVE TO STEP 3 FROM 2",step3To4:"MEDIA - MOVE TO STEP 4 FROM 3",step4To3:"MEDIA - MOVE TO STEP 3 FROM 4"},I$=e=>{const{mpTrack:t}=tr();return n=>{const r=ETe[n];switch(n){case"saveAttributions":case"saveThemes":case"download":case"upload":case"rebuild":t(qI,{actionType:r,brandId:e?.id||0,brandName:e?.brand_name||"",brandNiceId:e?.brand_nice_id||""});break;default:t(qI,{actionType:r})}}},_Te=({brand:e,engagementId:t,engagementNiceId:n})=>{const r=I$(e),[s]=Sm(),[i]=L3();return async({file:o,mediaUploadFields:l,url:c})=>{const{key:d,AWSAccessKeyId:u,"x-amz-security-token":p,policy:h,signature:f}=l,g={"Access-Control-Allow-Origin":"*","Content-Type":"multipart/form-data"},x=new FormData;x.append("key",d),x.append("AWSAccessKeyId",u),x.append("x-amz-security-token",p),x.append("policy",h),x.append("signature",f),x.append("file",o,o.name),r("upload"),await s({data:x,headers:g,method:"post",url:c});const b=await i({brandNiceId:e?.brand_nice_id||"",engagementId:t||0,engagementNiceId:n,fileName:o.name});return"data"in b?b.data:null}},D$=({changeText:e})=>a.jsxs(I,{component:"span",variant:"body2",children:["You are about to lose all edits if you ",a.jsx("b",{children:"change"})," ",e,". Please CANCEL and save before changing ",e,"."]}),TTe=a.jsx(D$,{changeText:"tabs"}),ITe=a.jsx(D$,{changeText:"brands"}),DTe={brand:{body:ITe,confirmText:"Change"},tab:{body:TTe,confirmText:"Change"},clear:{body:"You are about to clear and deactivate each item.",confirmText:"Clear All"},save:{body:"Are you sure you want to publish the changes made to your column names and settings?",confirmText:"Publish"},restore:{body:"Are you sure you want to restore all columns to their default names and settings? This will discard all unsaved changes.",confirmText:"Restore Defaults"}},ATe={body:"",confirmText:""},MTe=({handleClickCancel:e,handleClickConfirm:t,openState:n})=>{const{body:r,confirmText:s}=n?DTe[n]:ATe;return a.jsx(mt,{acceptLabel:s,body:r,closeLabel:"Cancel",handleAccept:t,handleClose:e,open:!!n,title:"Are you sure?"})},RTe=e=>{switch(e){case"complete":return"Your flexible classifications have been rebuilt.";case"inProgress":return"Your flexible classifications are being built.";default:return"Rebuild flexible classifications."}},NTe=({handleRebuild:e,onStartRebuild:t})=>{const n=ct(),r=en(),{supportLink:s}=jt(),[i,o]=m.useState(null),[l,c]=m.useState(null),{isError:d,percentComplete:u}=jm({eventType:"FlexibleContainerRebuildProgress",taskId:l}),p=RTe(i),h=d?"Task failed to complete, please create a support ticket.":"Upload classifications task initializing. Initialization may take several minutes before the task starts.";m.useEffect(()=>{u>=100&&(o("complete"),c(null))},[u]);const f=async()=>{t(),o("inProgress");const x=await e();x&&n()&&c(x.task_id)};let g;switch(i){case"complete":g=a.jsx(re,{onClick:()=>{r("/overview")},sx:{mr:1,mt:3.75,mb:7.5},variant:"contained",children:"Done"});break;case"inProgress":g=a.jsxs(T,{sx:{mr:1,mt:5.5,mb:7},children:[a.jsx(lo,{variant:"determinate",value:u}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",width:"max-content"},children:[u===0?a.jsx(I,{sx:{mt:2.5,color:d?"error.main":""},children:h}):null,d?a.jsx(lu,{href:s,sx:{ml:5}}):null]})]});break;default:g=a.jsx(re,{onClick:f,variant:"contained",sx:{mt:2},children:"Rebuild"})}return a.jsxs(a.Fragment,{children:[a.jsx(I,{sx:{mb:1},children:p}),g]})},GI=({inputFileRef:e,loading:t})=>a.jsxs(a.Fragment,{children:[a.jsx(I,{children:"Upload your media classifications CSV file."}),a.jsx(Dt,{loading:t,onClick:()=>{e?.current?.click()},variant:"contained",sx:{mt:3},children:"Choose File"})]}),OTe=({fileName:e,handleReplaceFile:t})=>a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center"},children:[`Upload complete for ${e}`,a.jsx(re,{onClick:t,sx:{ml:2},variant:"outlined",children:"Replace File"})]}),PTe=({completed:e,hasError:t=!1})=>{const{supportLink:n}=jt(),r=t?"Task failed to complete. Please create a support ticket.":"Uploading classifications - initialization may take several minutes before progress changes.";return a.jsxs(T,{children:[a.jsx(lo,{variant:"determinate",value:e}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center",width:"max-content",mt:2.5},children:[a.jsx(I,{sx:{color:t?"error.main":""},children:r}),t?a.jsx(lu,{href:n,sx:{ml:5}}):null]})]})},LTe=({fileName:e,handleReplaceFile:t,handleUpload:n,loading:r})=>a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center",mb:2},children:[a.jsx(I,{component:"span",children:e}),a.jsx(Dt,{loading:r,onClick:t,sx:{ml:2},variant:"outlined",children:"Replace File"})]}),a.jsx(Dt,{loading:r,onClick:n,variant:"contained",children:"Upload Selected File"})]}),FTe=({checkIsLoading:e,checkNextStepReady:t,handleUploadFile:n,handleGetMediaUploadURL:r})=>{const s=ct(),i=m.useRef(null),[o,l]=m.useState("choose"),[c,d]=m.useState(null),[u,p]=m.useState(null),[h,f]=m.useState(null),[g,x]=m.useState(null),[b,y]=m.useState(null),{isError:v,percentComplete:C}=jm({eventType:"MediaContainerUploadProgress",taskId:b});m.useEffect(()=>{e(!!u)},[e,u]),m.useEffect(()=>{C>=100&&!v&&(l("complete"),y(null),t(!0))},[t,C,v]);const w=()=>{i?.current?.click(),t(!1)},S=async j=>{const{files:_}=j.target;if(_?.length){const D=_?.[0];d(D),p("gettingURL"),l("choose");const M=await r(D.name);s()&&(f(M?.url||null),x(M?.fields||null),p(null),l("upload"))}},E=async()=>
265{if(h&&g&&c){l("inProgress");const j=await n({url:h,mediaUploadFields:g,file:c});j?.task_id&&y(j.task_id)}};let k;switch(o){case"choose":k=a.jsx(GI,{inputFileRef:i,loading:u==="gettingURL"});break;case"upload":k=a.jsx(LTe,{fileName:c?.name||"",handleReplaceFile:w,handleUpload:E,loading:!!u});break;case"inProgress":k=a.jsx(PTe,{completed:C,hasError:v});break;case"complete":k=a.jsx(OTe,{fileName:c?.name||"",handleReplaceFile:w});break;default:k=a.jsx(GI,{inputFileRef:i,loading:u==="gettingURL"})}return a.jsxs(T,{children:[k,a.jsx("input",{accept:".csv",hidden:!0,id:"upload-input",onChange:S,ref:i,type:"file"})]})},A$=m.createContext(null),sS=()=>{const e=m.useContext(A$);if(!e)throw new Error("useContentManagement must be used within a ContentManagementProvider");return e},YI=({children:e,value:t})=>a.jsx(A$.Provider,{value:t,children:e}),$Te=61,zTe=600,BTe=bs(Mn)(({theme:e})=>{const{background:t,text:n}=e.palette,{spacing:r}=e;return{border:"none",maxHeight:zTe,".MuiDataGrid-cell":{border:"none",fontSize:14,fontWeight:600,overflow:"visible",paddingLeft:r(2),paddingRight:r(1),position:"relative",zIndex:1,"&:focus":{outline:"none"},"&:focus-within":{outline:"none",zIndex:2}},".MuiDataGrid-columnHeader":{paddingLeft:r(2),paddingRight:r(2),":focus-within":{outline:"none"}},".MuiDataGrid-columnHeaders":{backgroundColor:t.tableHeader,border:"none",zIndex:3},".MuiDataGrid-columnHeaderTitle":{color:n.secondary,fontSize:12,fontWeight:500,textTransform:"uppercase"},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-row":{backgroundColor:t.paper,color:n.default,overflow:"visible","&:hover":{backgroundColor:"action.hover"}},".MuiDataGrid-virtualScrollerContent":{overflow:"visible"},".MuiDataGrid-virtualScrollerRenderZone":{overflow:"visible"}}}),UTe=e=>Object.entries(e).sort(([t],[n])=>t<n?-1:1).map(([t,n])=>({id:t,fieldKey:t,active:n.active,label:n.label,value:n.value})),VTe=()=>{const{mediaContainers:e,containerDispatch:t,duplicatesObj:n,hasInvalidNames:r,handleOnSave:s,isSaving:i}=sS(),o=Object.keys(n).length>0||r,l=m.useCallback((p,h)=>{t({type:"updateActive",containerType:"mediaContainer",value:{keyName:p,active:h}})},[t]),c=m.useCallback((p,h)=>{t({type:"updateValue",containerType:"mediaContainer",value:{keyName:p,newValue:h}})},[t]),d=m.useMemo(()=>UTe(e),[e]),u=m.useMemo(()=>[{field:"label",headerName:"DATA COLUMN",width:240,sortable:!0},{field:"active",headerName:"ACTIVE",width:120,sortable:!1,renderCell:p=>a.jsx(Dn,{checked:p.row.active,color:"primary",disabled:i,onChange:h=>l(p.row.fieldKey,h.target.checked)})},{field:"value",headerName:"DISPLAY NAME",flex:1,minWidth:250,sortable:!1,renderCell:p=>{const h=p.row.value in n,f=rS(p.row.value);let g="";return f?g=k$.INVALID_CHARACTERS:h&&(g="Duplicate name"),a.jsx(De,{disabled:i,error:h||f,fullWidth:!0,helperText:g,onChange:x=>c(p.row.fieldKey,x.target.value),onKeyDown:x=>x.stopPropagation(),placeholder:"Add display name...",size:"small",value:p.row.value,variant:"outlined",sx:{my:.5,"& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline":{borderWidth:1},"& .MuiFormHelperText-root":{position:"absolute",bottom:-14,right:0,margin:0,fontSize:11,lineHeight:1}}})}}],[n,l,c,i]);return a.jsxs(T,{sx:{p:3},children:[a.jsx(T,{sx:{width:"100%"},children:a.jsx(BTe,{columns:u,disableColumnMenu:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,getRowHeight:()=>$Te,hideFooter:!0,rows:d})}),a.jsx(T,{sx:{display:"flex",justifyContent:"flex-end",mt:3,mr:-1},children:a.jsx(Dt,{disabled:o,loading:i,onClick:s,variant:"contained",children:"Save Changes"})})]})},WTe=({loading:e,onSendEmail:t})=>a.jsxs(T,{sx:{p:2,height:200},children:[a.jsx(I,{children:"Send the CSV template to your email below. Using the media name and placements determine your media classifications. Fill in your media classifications under the appropriate theme."}),a.jsx(Dt,{loading:e==="email",onClick:t,sx:{my:3},variant:"contained",children:"Send to email"})]}),HTe=()=>{const{contentMpTrack:e,duplicatesObj:t,hasInvalidNames:n,handleGetMediaUploadURL:r,handleRebuildContainers:s,handleUploadFile:i,sendEmailProps:o}=sS(),l=ct(),[c]=F3(),[d,u]=m.useState(null),[p,h]=m.useState(!1),[f,g]=m.useState(!1),[x,b]=m.useState(!1),y=Object.keys(t).length===0&&!n,v=async()=>{u("email"),e("download"),await c(o),l()&&u(null)},C=m.useCallback(w=>{h(w)},[]);return a.jsxs(WU,{cancelButton:a.jsx(T,{}
265),hideFinish:!0,children:[a.jsx(rp,{label:"Configure",disableNext:!y,onNext:()=>{e("step1To2")},children:a.jsx(VTe,{})}),a.jsx(rp,{label:"Export",disableBack:d==="email",disableNext:d==="email",onBack:()=>{e("step2To1")},onNext:()=>{e("step2To3")},children:a.jsx(WTe,{loading:d,onSendEmail:v})}),a.jsx(rp,{label:"Upload",disableBack:p,disableNext:!f,onBack:()=>{e("step3To2")},onNext:()=>{e("step3To4")},children:a.jsx(T,{sx:{p:2,height:200},children:a.jsx(FTe,{checkIsLoading:C,checkNextStepReady:w=>{g(w)},handleGetMediaUploadURL:r,handleUploadFile:i})})}),a.jsx(rp,{label:"Rebuild",disableBack:x,onBack:()=>{e("step4To3")},children:a.jsx(T,{sx:{p:2,height:200},children:a.jsx(NTe,{handleRebuild:s,onStartRebuild:()=>{b(!0)}})})})]})},qTe=61,GTe=700,YTe=bs(Mn)(({theme:e})=>{const{background:t,text:n}=e.palette,{spacing:r}=e;return{border:"none",maxHeight:GTe,".MuiDataGrid-cell":{border:"none",overflow:"visible",paddingLeft:r(2),paddingRight:r(1),position:"relative",zIndex:1,"&:focus-within":{zIndex:2},"&:focus-visible":{outline:`2px solid ${e.palette.primary.main}`,outlineOffset:-2}},".MuiDataGrid-columnHeader":{paddingLeft:r(2),paddingRight:r(2),"&:focus-visible":{outline:`2px solid ${e.palette.primary.main}`,outlineOffset:-2}},".MuiDataGrid-columnHeaders":{backgroundColor:t.tableHeader,border:"none",zIndex:3},".MuiDataGrid-columnSeparator":{display:"none"},".MuiDataGrid-row":{backgroundColor:t.paper,color:n.default,overflow:"visible","&:hover":{backgroundColor:"action.hover"}},".MuiDataGrid-treeDataGroupingCell":{fontSize:14,fontWeight:600},".MuiDataGrid-virtualScrollerContent":{overflow:"visible"},".MuiDataGrid-virtualScrollerRenderZone":{overflow:"visible"}}}),KTe={headerName:"DATA COLUMN",width:300,renderHeader:()=>a.jsx(T,{sx:{color:"text.secondary",fontSize:12,fontWeight:500,textTransform:"uppercase"},children:"DATA COLUMN"})},QTe=["type","vehicle","platform","tactic","program_name","country","market","data_source","vendor"],JTe=["account_name","account_id","campaign_name","campaign_id","ad_group_name","ad_group_id","placement_name"],XTe=["media_attribute_1","media_attribute_2","media_attribute_3","media_attribute_4","media_attribute_5","media_attribute_6","media_attribute_7","media_attribute_8"],ZTe=()=>{const{attributesState:e,containerDispatch:t,duplicatesObj:n,hasInvalidNames:r,handleOnSave:s,isSaving:i}=sS(),{creative:o,kpi:l,media:c}=e,[d,u]=m.useState(""),p=zn(),h=m.useRef(new Set(["Primary Media"])),f=m.useRef(i),g=Object.keys(n).length>0||r,[x,b]=m.useState(!1),[y,v]=m.useState(0),C=N=>{u(N.target.value)},w=m.useCallback(()=>{const N=!x;N?["Primary Media","Campaign","Media Attributes","Creative Attributes","KPI Attributes"].forEach(R=>{h.current.add(R)}):h.current.clear(),b(N),v(R=>R+1)},[x]),S=m.useCallback((N,O,R)=>{t({type:"updateActive",containerType:N,value:{keyName:O,active:R}})},[t]),E=m.useCallback((N,O,R)=>{t({type:"updateValue",containerType:N,value:{keyName:O,newValue:R}})},[t]),k=(N,O,R,L)=>Object.entries(N).filter(([P])=>!L||L.includes(P)).sort(([P],[F])=>{if(L){const z=L.indexOf(P),B=L.indexOf(F);return(z===-1?1/0:z)-(B===-1?1/0:B)}return P<F?-1:1}).map(([P,F])=>({id:`${R}-${P}`,path:`${O}.${F.label}`,containerType:R,fieldKey:P,active:F.active,label:F.label,value:F.value,isCategory:!1})),j=m.useMemo(()=>{const N=k(c,"Primary Media","media",QTe),O=k(c,"Campaign","media",JTe),R=k(c,"Media Attributes","media",XTe),L=k(o,"Creative Attributes","creative"),P=k(l,"KPI Attributes","kpi");return[...N,...O,...R,...L,...P]},[c,o,l]),_=m.useMemo(()=>{if(!d.trim())return j;const N=d.toLowerCase();return j.filter(O=>O.label.toLowerCase().includes(N)||O.value.toLowerCase().includes(N)||O.path.toLowerCase().includes(N))},[j,d]),D=m.useCallback(N=>d.trim()||x?!0:h.current.has(JSON.stringify(N.groupingKey??"")),[d,x]);m.useEffect(()=>p.current?.subscribeEvent?p.current.subscribeEvent("rowExpansionChange",O=>{const R=JSON.stringify(O.groupingKey??"");O.childrenExpanded?h.current.add(R):h.current.delete(R)}):void 0,[p]),m.useEffect(()=>{const N=f.current;if(f.current=i,!N||i||!p.current?.getAllRowIds||!p.current?.setRowChildrenExpansion)return;const O=setTimeout(()=>
265{p.current.getAllRowIds().forEach(L=>{const P=p.current.getRowNode(L);if(P?.type==="group"&&P.groupingKey){const F=String(P.groupingKey);if(h.current.has(F))try{p.current.setRowChildrenExpansion(L,!0)}catch{}}})},100);return()=>clearTimeout(O)},[p,i]);const M=m.useMemo(()=>[{field:"active",headerName:"",width:120,sortable:!1,renderCell:N=>N.rowNode.type==="group"?N.rowNode.childrenExpanded?a.jsx(T,{sx:{fontSize:14,fontWeight:600},children:"Active"}):null:a.jsx(Dn,{checked:N.row.active??!1,color:"primary",disabled:i,onChange:O=>{const{containerType:R,fieldKey:L}=N.row;R&&L&&S(R,L,O.target.checked)}})},{field:"value",headerName:"",flex:1,minWidth:250,sortable:!1,renderCell:N=>{if(N.rowNode.type==="group")return N.rowNode.childrenExpanded?a.jsx(T,{sx:{fontSize:14,fontWeight:600},children:"Display Name"}):null;const O=Object.hasOwn(n,N.row.value),R=rS(N.row.value);let L="";return R?L=k$.INVALID_CHARACTERS:O&&(L="Duplicate name"),a.jsx(De,{disabled:i,error:O||R,fullWidth:!0,helperText:L,onChange:P=>{const{containerType:F,fieldKey:z}=N.row;F&&z&&E(F,z,P.target.value)},onKeyDown:P=>P.stopPropagation(),placeholder:"Add display name...",size:"small",value:N.row.value,variant:"outlined",sx:{my:.5,"& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline":{borderWidth:1},"& .MuiFormHelperText-root":{position:"absolute",bottom:-14,right:0,margin:0,fontSize:11,lineHeight:1}}})}}],[n,S,E,i]);return a.jsxs(T,{sx:{p:3},children:[a.jsxs(T,{sx:{display:"flex",gap:2,mb:3},children:[a.jsx(Qe,{children:a.jsx(ys,{startAdornment:a.jsx(Mt,{sx:{color:"text.secondary",fontSize:20},children:a.jsx(er,{})}),onChange:C,placeholder:"Search",sx:{borderRadius:1,height:42,px:1.5,width:320,".MuiInputBase-inputAdornedStart":{height:24,pl:1.5,pr:0}},value:d})}),a.jsx(re,{onClick:w,variant:"outlined",children:x?"Collapse All":"Expand All"})]}),a.jsx(T,{sx:{width:"100%"},children:a.jsx(YTe,{apiRef:p,columns:M,disableColumnMenu:!0,disableColumnSelector:!0,disableRowSelectionOnClick:!0,getRowHeight:()=>qTe,getTreeDataPath:N=>N.path.split("."),groupingColDef:KTe,hideFooter:!0,isGroupExpandedByDefault:D,rows:_,treeData:!0},y)}),a.jsx(T,{sx:{display:"flex",justifyContent:"flex-end",mt:3},children:a.jsx(Dt,{disabled:g,loading:i,onClick:s,variant:"contained",children:"Save Changes"})})]})},eIe=[{authorized:"DataPipeline.DisplaySettings",label:"Standard Columns",value:"0"},{authorized:"DataPipeline.DisplaySettings",label:"Custom Columns",value:"1"}],KI=()=>a.jsx(T,{sx:{alignItems:"center",display:"flex",height:464,justifyContent:"center",width:"100%"},children:a.jsx(Ze,{})}),tIe=()=>{const e=ct(),[t]=$3(),[n]=z3(),[r]=B3(),[s]=U3(),[i,o]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[p,h]=m.useState(null),[f,g]=m.useState("0"),[x,b]=m.useState(null),{brands:y,containerDispatch:v,containerState:C,engagementId:w,engagementNiceId:S,fetchingData:E,refetchAllData:k}=kTe(i),j=_Te({brand:i,engagementId:w||0,engagementNiceId:S||""}),_=I$(i),D=hTe(C),M=STe(C);m.useEffect(()=>{y.length>0&&!i&&o(y[0]||null)},[y,i]);const N=async()=>{if(!(Object.keys(D).length>0||M||!i)){if(u(!0),x==="standard"){const{attributes:W}=C,{creative:H,kpi:V,media:G}=W,X=Jp(H,!1),K=Jp(V,!1),ie=Jp(G,!1);_("saveAttributions"),await t({brand:i,engagementNiceId:S||"",creativeAttributes:X,kpiAttributes:K,mediaAttributes:ie})}else if(x==="custom"){const{mediaContainers:W}=C,H=Jp(W,!0);_("saveThemes"),await n({brand:i,engagementNiceId:S||"",uploadMediaContainers:H})}await k(),e()&&(u(!1),b(null))}},O=()=>{c(null)},R=()=>{switch(l){case"save":N();break;case"clear":p&&v({type:"clear",containerType:p}),h(null);break;case"restore":v({type:"resetToDefaults"});break}c(null)},L=async W=>{if(i){const{data:H=null}=await r({brandId:i.id,brandName:i.brand_nice_id,engagementId:w||0,engagementNiceId:S||"",fileName:W});return H}return null},P=async()=>{_("rebuild");const W=await s({brandId:i?.id||0,engagementId:w||0});return"data"in W?W.data:null},F=W=>{g(W)},z=E&&!d,B=i&&(!E||d);return a.jsxs($,{direction:"column",gap:5,minWidth:"600px",width:ks,children:[a.jsx(Xt,{title:"Data Display Settings",subTitle:"Configure how data displays across the platform"}),a.jsxs(fo,{onChange:F,tabs:eIe,value:f,children:[a.jsxs(xt,{value:"0",sx:{p:0},children:[z?a.jsx(KI,{}):null,B?a.jsx(YI,{value:{attributesState:C.attributes,containerDispatch:v,contentMpTrack:_,duplicatesObj:D,hasInvalidNames:M,handleGetMediaUploadURL:L,handleOnRestore:()=>c("restore"),handleOnSave:()=>{b("standard"),c("save")},handleRebuildContainers:P,handleUploadFile:j,isSaving:d,mediaContainers:C.mediaContainers,sendEmailProps:{engagementId:w||0,engagementNiceId:S||"",brandName:i.brand_nice_id}},children:a.jsx(ZTe,{})}):null]}),a.jsxs(xt,{value:"1",sx:{p:0,pt:3},children:[z?a.jsx(KI,{}):null,B?a.jsx(YI,{value:{attributesState:C.attributes,containerDispatch:v,contentMpTrack:_,duplicatesObj:D,hasInvalidNames:M,handleGetMediaUploadURL:L,handleOnRestore:()=>c("restore"),handleOnSave:()=>{b("custom"),c("save")},handleRebuildContainers:P,handleUploadFile:j,isSaving:d,mediaContainers:C.mediaContainers,sendEmailProps:{engagementId:w||0,engagementNiceId:S||"",brandName:i.brand_nice_id}},children:a.jsx(HTe,{})}):null]})]}),a.jsx(MTe,{handleClickCancel:O,handleClickConfirm:R,openState:l})]})},tl=[{name:"US-West-2",id:"us-west-2",active:!0},{name:"US-East-1",id:"us-east-1",active:!1}],Yc=[{name:"Snowflake Data Share",id:"sfdatashare",active:!0,view:"sf-data-share"},{name:"Export to S3 Bucket",id:"exporttos3bucket",active:!0,view:"s3-data-share"},{name:"API Query",id:"apikey",active:!0,view:"api-key"}],nIe=[{label:"Attribution Report",value:"ATTRIBUTION_REPORTING_DEMOS"},{label:"Media Reporting Attribution",value:"MEDIA_REPORTING_ATTRIBUTION_VIEW"},{label:"Media Reporting Contribution",value:"MEDIA_REPORTING_VIEW"},{label:"Media Dimensions",value:"MEDIA_DIMENSIONS"},{label:"Media Dimensions Definitions",value:"MEDIA_DIMENSIONS_DEFINITIONS"}],ko={API_CONNECTIONS:"api-connections",API_KEY:"api-key",CURRENT_CONNECTIONS:"current-connections",SF_DATA_SHARE:"sf-data-share",S_THREE_DATA_SHARE:"s3-
265data-share"},Cb={"api-key":1,"sf-data-share":1,"s3-data-share":1},Xp={s3Bucket:"Enter the name of your AWS S3 bucket.",folderPath:"Enter the AWS S3 bucket path.",accessKey:"Enter the AWS secret access key.",keyId:"Enter the AWS secret access key ID."},wb={s3Bucket:"Check bucket information.",accessKey:"Check AWS access key.",keyId:"Check AWS access key ID."},{API_CONNECTIONS:rIe,API_KEY:QI,SF_DATA_SHARE:JI,S_THREE_DATA_SHARE:XI}=ko,_s=m.createContext(null),iS=({children:e,initialStore:t})=>{const{clientId:n,engagementNiceId:r,engagementId:s}=pe(),{currentEngagement:i}=yu(s),[o,l]=m.useState(t.apiKey),[c,d]=m.useState(t.keyAccountClicked),[u,p]=m.useState(t.engagementSfAccountInfo),{isLoading:h}=OA(n),{data:{metadata:f=[]}={},isLoading:g}=V3(r),{data:{keys:x=[]}={}}=W3(r),[b,y]=m.useState(t.accountClicked),[v,C]=m.useState(t.s3AccountClicked),[w,S]=m.useState(t.confirmDialogOpen),[E,k]=m.useState(t.creating),[j,_]=m.useState(t.deliveryTypeSelected),[D,M]=m.useState(t.destroying),[N,O]=m.useState(t.errorMessage),[R,L]=m.useState(t.errorSavingShare),[P,F]=m.useState(t.newAccountText),[z,B]=m.useState(t.pageView),[W,H]=m.useState(t.regionSelected),[V,G]=m.useState(t.reportsSelected),X=m.useCallback(()=>{k(t.creating),O(t.errorMessage),L(t.errorSavingShare),F(t.newAccountText),H(t.regionSelected),G(t.reportsSelected)},[t.creating,t.errorMessage,t.errorSavingShare,t.newAccountText,t.regionSelected,t.reportsSelected]),K=m.useCallback(()=>{M(t.destroying),y(t.accountClicked),C(t.s3AccountClicked),d(t.keyAccountClicked),S(t.confirmDialogOpen)},[t.destroying,t.accountClicked,t.s3AccountClicked,t.keyAccountClicked,t.confirmDialogOpen]),[ie,le]=m.useState(t.saving),[ce,J]=m.useState(t.errorSavingS3Share),[he,ne]=m.useState(t.duplicateError),[Y,ae]=m.useState(t.errorMessageAccessKey),[je,me]=m.useState(t.errorMessageBucket),[ve,Me]=m.useState(t.errorMessageFolder),[q,Q]=m.useState(t.errorMessageKeyId),[ee,Ce]=m.useState(t.s3AccessKeyText),[se,oe]=m.useState(t.errorMessageFolder),[te,de]=m.useState(t.errorMessageKeyId),[ke,Le]=m.useState(t.s3AccessKeyText),at=m.useCallback(()=>{ne(t.duplicateError),Ce(t.s3AccessKeyText),oe(t.s3FolderText),de(t.s3KeyIdText),Le(t.s3NameText),ae(t.errorMessageAccessKey),me(t.errorMessageBucket),Me(t.errorMessageFolder),Q(t.errorMessageKeyId),J(t.errorSavingS3Share),G(t.reportsSelected)},[t.duplicateError,t.s3AccessKeyText,t.s3FolderText,t.s3KeyIdText,t.s3NameText,t.errorMessageAccessKey,t.errorMessageBucket,t.errorMessageFolder,t.errorMessageKeyId,t.errorSavingS3Share,t.reportsSelected]),Wt=m.useCallback(()=>{ne(!0),me("This bucket has already been added for data delivery.")},[]);m.useEffect(()=>{const{sf_account:Cn}=i||{};p(Cn?.accounts||[])},[i]);const zt=m.useCallback(()=>f.map(Cn=>{const{Description:Sr=""}=Cn||{},_i=JSON.parse(Sr),{bucket:Ti=""}=_i;return Ti===ke}).reduce((Cn,Sr)=>Cn||Sr,!1),[f,ke]),Ht=m.useCallback(()=>ee||se||te||ke,[ee,se,te,ke]),Oe=m.useCallback(()=>ee&&se&&te&&ke&&Array.isArray(V)&&V.length,[ee,se,te,ke,V]),Pe=m.useCallback(()=>u?.length>0||f?.length>0||x?.length>0,[u,f,x]),Fe=m.useCallback(()=>x?.length>=Cb[QI],[x]),pt=m.useCallback(()=>u?.length>=Cb[JI],[u]),_t=m.useCallback(()=>f?.length>=Cb[XI],[f]),Rn=m.useCallback(()=>!Fe()||!pt()||!_t(),[Fe,pt,_t]),ot=m.useCallback(Cn=>Cn.map(Sr=>{const _i={...Sr};let Ti=!1;const{view:ep="",name:tp=""}=_i;switch(ep){case QI:Ti=Fe();break;case JI:Ti=pt();break;case XI:Ti=_t();break}return Ti&&(_i.disabled=!0,_i.name=`${tp} (Set up done)`),_i}),[Fe,pt,_t]),Vn=m.useMemo(()=>({apiKey:o,setApiKey:l,checkCurrentAccounts:Pe,checkConnectionSpaceAvaliable:Rn,engagementSfAccountInfo:u,setEngagementSfAccountInfo:p,engagementS3AccountInfo:f,engagementKe
265yAccountInfo:x,gatherMetaData:g,gatherSfData:h,getDynamicDeliveryOptions:ot,keyAccountClicked:c,setKeyAccountClicked:d,setPageView:B,pageView:z,settings:{apiConnections:{accountClicked:b,confirmDialogOpen:w,creating:E,deliveryTypeSelected:j,destroying:D,errorMessage:N,errorSavingShare:R,newAccountText:P,regionSelected:W,reportsSelected:V,resetApiConnectionEditVariables:X,resetApiConnectionRemoveVariables:K,setAccountClicked:y,setConfirmDialogOpen:S,setCreating:k,setDeliveryTypeSelected:_,setDestroying:M,setErrorMessage:O,setErrorSavingShare:L,setNewAccountText:F,setRegionSelected:H,setReportsSelected:G},s3Connections:{s3AccountClicked:v,setS3AccountClicked:C,clearS3Data:at,checkClearAllReady:Ht,checkForDuplicate:zt,checkSaveReady:Oe,saving:ie,duplicateError:he,errorSavingS3Share:ce,errorMessageAccessKey:Y,errorMessageBucket:je,errorMessageFolder:ve,errorMessageKeyId:q,markDuplicate:Wt,reportsSelected:V,s3AccessKeyText:ee,s3FolderText:se,s3KeyIdText:te,s3NameText:ke,setDuplicateError:ne,setSaving:le,setReportsSelected:G,setS3AccessKeyText:Ce,setS3FolderText:oe,setS3KeyIdText:de,setS3NameText:Le,setErrorMessageAccessKey:ae,setErrorMessageBucket:me,setErrorMessageFolder:Me,setErrorMessageKeyId:Q,setErrorSavingS3Share:J}}}),[o,Pe,Rn,u,f,x,g,h,ot,z,v,C,at,Ht,zt,Oe,ie,he,ce,Y,je,ve,q,c,Wt,V,ee,se,te,ke,b,w,E,j,D,N,R,P,W,X,K]);return a.jsx(_s.Provider,{value:Vn,children:e})};iS.propTypes={children:A.node.isRequired,initialStore:A.object};iS.defaultProps={initialStore:{accountClicked:null,apiKey:{},s3AccountClicked:null,engagementSfAccountInfo:[],engagementS3AccountInfo:[],engagementKe
265yAccountInfo:[],confirmDialogOpen:!1,creating:!1,deliveryTypeSelected:{},destroying:!1,duplicateError:!1,errorMessage:"",errorSavingShare:!1,keyAccountClicked:null,gatherMetaData:!0,gatherSfData:!0,newAccountText:"",pageView:rIe,regionSelected:tl[0]||{},reportsSelected:[],errorSavingS3Share:!1,errorMessageAccessKey:"",errorMessageBucket:"",errorMessageFolder:"",errorMessageKeyId:"",s3AccessKeyText:"",s3FolderText:"",s3KeyIdText:"",s3NameText:""}};const Eg=({disabled:e,error:t,id:n,label:r,onChange:s,options:i,title:o,value:l,width:c})=>{const d=i.filter(h=>h.active).map((h,f)=>a.jsx(Se,{id:`${r}-menu-item-${f}`,disabled:h.disabled,value:h.id,sx:{lineHeight:"normal",whiteSpace:"normal",wordBreak:"break-word",hyphens:"auto",height:"auto"},children:h.name},h.id)),u=a.jsx(Se,{disabled:!0,id:"placeholder-menu-item",sx:{display:"none"},value:"Select"},"placeholder"),p=[...d,u];return a.jsxs(RC,{sx:{width:c},error:t,disabled:e,title:o,children:[a.jsx(wt,{id:`${n}-label`,children:r}),a.jsx(tt,{labelId:`${n}-label`,id:n,value:l,label:r,onChange:h=>s(h.target.value),children:p})]})};Eg.defaultProps={disabled:!1,error:!1,id:"standard-reporting-select",label:"",onChange:()=>{},options:[],title:"",value:"",width:200};Eg.propTypes={disabled:A.bool,error:A.bool,id:A.string,label:A.string,onChange:A.func,options:A.array,title:A.string,width:A.number,value:A.string};const{API_CONNECTIONS:sIe,CURRENT_CONNECTIONS:iIe}=ko,aIe=()=>{const{checkCurrentAccounts:e,setApiKey:t,setPageView:n}=m.useContext(_s),[r,s]=m.useState(!1),{mpTrack:i}=tr(),[o]=ZA(),[l]=eM(),{engagementNiceId:c}=pe(),d=e()?iIe:sIe,u=async()=>{s(!0);const{data:{key_value:h,key_id:f}={}}=await o(c)||{};i("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"GENERATE API SECRET KEY",secretKeyId:f}),await l(),t({id:f,value:h})},p=a.jsx(Ze,{color:"inherit",size:30});return a.jsxs(T,{children:[a.jsx(I,{sx:{my:"25px"},children:"Please click on GENERATE to get your API secret"}),a.jsx(re,{id:"api-key-cancel-button",onClick:()=>n(d),sx:{mr:"40px"},variant:"outlined",children:"cancel"}),a.jsx(re,{id:"api-key-generate-button",onClick:u,sx:{height:"40px",width:"104px"},variant:"contained",children:r?p:"generate"})]})},aS=()=>{const{supportLink:e}=jt();return a.jsxs(T,{sx:{width:"220px"},children:["If you encounter any problems, please"," ",a.jsx(lu,{href:e,text:"contact support."})]})},{API_CONNECTIONS:oIe,CURRENT_CONNECTIONS:lIe}=ko,cIe=()=>{const{apiKey:e,setApiKey:t,checkCurrentAccounts:n,setPageView:r}=m.useContext(_s),{palette:s}=Re(),[i,o]=m.useState(!1),[l,c]=m.useState(!1),d=ct(),u=()=>{d()&&(c(!1),t({}),r(n()?lIe:oIe))},p=a.jsxs(I,{component:"span",children:[a.jsx("strong",{children:"EXIT"})," only if you have copied and stored securely the API secret as API secret"," ",a.jsx("strong",{children:"CANNOT"})," be shown again. To see the secret again, you will start over and generate a new key."]}),h=()=>{o(!0),navigator.clipboard.writeText(e?.value||"Error copying secret."),setTimeout(()=>{d()&&o(!1)},2500)},f=a.jsxs(T,{sx:{display:"inline-flex",ml:"5px",alignItems:"center"},children:[a.jsx(Oh,{color:s.success.main,size:20}),a.jsx(I,{sx:{ml:"5px"},children:"Copied to clipboard!"})]});return a.jsxs(T,{children:[a.jsx(I,{sx:{mb:"20px"},children:"Please copy the API secret below"}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"flex-end",mb:"40px"},children:[a.jsx(De,{id:"api-key-view-field","data-testid":"key-secret-field",value:e?.value||"Error getting value.",label:"API secret",onChange:()=>{},type:"password",size:"small",sx:{width:300},inputProps:{maxLength:125}}),a.jsx(T,{sx:{ml:"20px"},children:a.jsx(aS,{})})]}),a.jsx(re,{id:"api-key-exit-button","data-testid":"exit-button",onClick:()=>c(!l),sx:{mr:"40px"},variant:"outlined",children:"exit"}),a.jsx(re,{id:"api-key-copy-button","data-testid":"copy-button",onClick:h,sx:{height:"40px",minWidth:"130px",pointerEvents:i?"none":"auto"},variant:"contained",children:"copy secret"}),i&&f,a.jsx(mt,{acceptLabel:"Exit",bodyText:p,cancelLabel:"Cancel",handleAccept:u,handleClose:()=>c(!1),open:l,title:"Have you copied this API secret?"})]})},dIe=()=>{const{apiKey:e}
265=m.useContext(_s);return a.jsx(T,{children:e?.id?a.jsx(cIe,{}):a.jsx(aIe,{})})},M$=()=>{const{engagementSfAccountInfo:e,settings:t={}}=m.useContext(_s),{apiConnections:n={}}=t,{newAccountText:r,regionSelected:s,reportsSelected:i,resetApiConnectionEditVariables:o,resetApiConnectionRemoveVariables:l,setCreating:c,setDestroying:d,setErrorMessage:u,setErrorSavingShare:p}=n,{mpTrack:h}=tr(),{engagementId:f,engagementNiceId:g}=pe(),[x]=UA(),[b]=H3(),[y]=q3(),[v]=G3(),[C]=Y3(),[w]=K3(),[S]=Q3(),E="Snowflake error, please contact admin",k=()=>{o(),l()},j=M=>{u(M),p(!0),c(!1),d(!1)};return{shareCreateStart:async()=>{c(!0),h("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"ADD SNOWFLAKE SHARE ACCOUNT",sfAccount:r,sfRegion:s.id,sfTables:i});const M={engagement_nice_id:g,region:s.id},{data:{status:N=400}={}}=await y({body:{...M}});if(N!==200){j("Invalid Snowflake account");return}const O=i.map(z=>v({body:{...M,snowflake_view_name:z}}));if(!(await Promise.all(O)).reduce((z,{data:{status:B=400}={}})=>z&&B===200,!0)){j(E);return}const P=[...e,{name:r,region:s.id,tables:i}],{data:{status:F=400}={}}=await b({body:{...M,client_sf_account:[r]}});if(F!==200){j(E);return}x({body:{sf_account:JSON.stringify({accounts:P})},engagementId:f}).finally(()=>{k()})},shareRemoveStart:async M=>{d(!0);const N=e.find(V=>V.name===M),O=N?.region||"",R=N?.tables||[],L={engagement_nice_id:g,region:O},P=e.filter(V=>V.name!==M);h("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"REMOVE SNOWFLAKE SHARE ACCOUNT",sfAccount:M,sfRegion:s});const{data:{status:F=400}={}}=await C({body:{...L,client_sf_account:[M]}});if(F!==200){j(E);return}x({body:{sf_account:JSON.stringify({accounts:P})},engagementId:f});const z=R.map(V=>S({body:{...L,snowflake_view_name:V}}));if(!(await Promise.all(z)).reduce((V,{data:{status:G}={}})=>V&&G===200,!0)){j(E);return}const{data:{status:H}}=await w({body:{...L}});H===200?k():j("Invalid Snowflake account")}}},R$=({destroying:e,open:t,onClickCancel:n,onClickConfirm:r})=>{const[s,i]=m.useState(!1);m.useEffect(()=>{!t&&s&&i(!s)},[t]);const l=a.jsxs("div",{children:[a.jsx(I,{component:"span",variant:"body2",sx:{mb:"20px"},children:"You are about to delete this API connection."}),a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center",mt:"10px"},children:[a.jsx(et,{id:"dialog-confirm-delete-checkbox",sx:{padding:0,ml:"-3px"},checked:s,onClick:()=>i(!s)}),a.jsx(I,{component:"span",variant:"body2",sx:{pl:"5px"},children:"Please confirm deletion by selecting the check box."})]})]});return a.jsxs(yt,{open:t,id:"dialog-confirm-delete",children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"row",justifyContent:"space-between"},children:[a.jsx(vt,{sx:{pl:"20px",fontSize:"20px",fontWeight:"500",mb:0,mt:"20px"},variant:"h1",children:"Are you sure?"}),a.jsx(HU,{id:"dialog-confirm-delete-close-button",onClick:n,sx:{mt:"20px",mr:"25px"}})]}),a.jsx(Ct,{sx:{pl:"20px",pb:"20px",width:450},children:l}),a.jsxs(un,{sx:{justifyContent:"right",pl:"15px",ml:0},children:[a.jsx(re,{id:"dialog-confirm-delete-cancel-button",sx:{mb:"20px",borderRadius:"2px",minHeight:40,maxHeight:40,pointerEvents:e?"none":"auto"},variant:"outlined",onClick:n,children:"cancel"}),a.jsx(re,{id:"dialog-confirm-delete-submit-button",disabled:!s,sx:{mr:"30px",mb:"20px",minWidth:85,maxWidth:85,minHeight:40,maxHeight:40,pointerEvents:e?"none":"auto"},onClick:r,variant:"contained",children:e?a.jsx(T,{sx:{margin:"1px 0px 0px 0px"},children:a.jsx(Ze,{color:"inherit",size:30})}):a.jsx("span",{children:"delete"})})]})]})};R$.propTypes={destroying:A.bool.isRequired,onClickCancel:A.func.isRequired,onClickConfirm:A.func.isRequired,open:A.bool.isRequired};const{API_CONNECTIONS:Sb,API_KEY:ZI,CURRENT_CONNECTIONS:uIe}=ko,oS=({onAddAccountClick:e})=>{const{palette:t}=Re(),{checkCurrentAccounts:n,checkConnectionSpaceAvaliable:r,engagementSfAccountInfo:s,engagementS3AccountInfo:i,engagementKe
265yAccountInfo:o,keyAccountClicked:l,setKeyAccountClicked:c,pageView:d,setApiKey:u,setPageView:p,settings:h={}}=m.useContext(_s),{apiConnections:f={},s3Connections:g={}}=h,{accountClicked:x,confirmDialogOpen:b,destroying:y,setDestroying:v,resetApiConnectionRemoveVariables:C,setAccountClicked:w,setConfirmDialogOpen:S}=f,[E,k]=m.useState(null),[j,_]=m.useState(!1),{mpTrack:D}=tr(),{shareRemoveStart:M}=M$(),{engagementNiceId:N}=pe(),[O]=J3(),[R]=X3(),[L]=ZA(),[P]=tM(),[F]=eM(),{s3AccountClicked:z,setS3AccountClicked:B}=g;m.useEffect(()=>{n()&&d!==Sb&&d!==ZI?p(uIe):!n()&&d!==Sb&&p(Sb)},[s,i,o,p]);const W=()=>{F().unwrap().then(()=>{v(!1),c(null),S(!1)})},H=()=>{P().unwrap().then(()=>{v(!1),B(null),S(!1)})},V=he=>{v(!0),D("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"REMOVE S3 BUCKET ACCOUNT",s3Account:he}),R({body:{body:{secret_name:he}}.body,engagementNiceId:N}).unwrap().then(()=>{setTimeout(H,750)}).catch(()=>v(!1))},G=he=>{v(!0),D("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"REMOVE API SECRET KEY",removedSecretKeyId:he}),O({body:{body:{key_id:he}}.body,engagementNiceId:N}).unwrap().then(()=>{setTimeout(W,750)}).catch(()=>v(!1))},X=async()=>{if(!E)return;_(!0),await O({body:{body:{key_id:E}}.body,engagementNiceId:N});const{data:{key_value:ne,key_id:Y}={}}=await L(N)||{};u({id:Y,value:ne}),D("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"REGENERATE API SECRET KEY",secretKeyId:Y,removedSecretKeyId:E}),W(),k(null),_(!1),p(ZI)};m.useEffect(()=>{(x||z||l)&&S(!0)},[x,z,l,S]);const K=s.length===0,ie=i.map((he,ne)=>{const{name:Y,type:ae="",bucket:je,aws_access_key_id:me}=he||{};return a.jsxs(T,{sx:{minWidth:325,maxWidth:325,display:"flex",flexDirection:"row",justifyContent:"space-between",borderTop:K&&ne===0?"none":`1px solid ${t.divider}`},children:[a.jsxs(T,{sx:{mt:"20px",display:"flex",flexDirection:"column",justifyContent:"center"},children:[a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:ae?`${ae} delivery`:""}),a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:je||""}),a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:me?`AWS secret key ID: ${me} (last 4 digits)`:""})]}),a.jsx(He,{id:`s-three-account-trash-button-${ne}`,onClick:()=>B(Y),children:a.jsx(Xr,{size:20})})]},je)}),le=s.map((he,ne)=>{const{name:Y,region:ae}=he;let je=ae;const me=tl.findIndex(ve=>ve.id===ae);return me!==-1&&(je=tl[me].name),a.jsxs(T,{sx:{minWidth:325,maxWidth:325,display:"flex",flexDirection:"row",justifyContent:"space-between",borderTop:ne===0?"none":`1px solid ${t.divider}`},children:[a.jsxs(T,{sx:{mt:"20px",display:"flex",flexDirection:"column",justifyContent:"center"},children:[a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:"Snowflake data share"}),a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:Y||""}),a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:je||""})]}),a.jsx(He,{id:`snowflake-account-trash-button-${ne}`,onClick:()=>w(Y),children:a.jsx(Xr,{size:20})})]},Y)}),ce=s.length===0&&i.length===0,J=o.sort((he,ne)=>ne?.created_at?.localeCompare(he?.created_at)).map((he,ne)=>{const{key_id:Y}=he;return a.jsxs(T,{sx:{minWidth:325,maxWidth:325,display:"flex",flexDirection:"row",justifyContent:"space-between",borderTop:ce&&ne===0?"none":`1px solid ${t.divider}`},children:[a.jsxs(T,{sx:{mt:"20px",display:"flex",flexDirection:"column",justifyContent:"center"},children:[a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:"API Query"}),a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:`API Key ID: ${Y}`}),a.jsx(I,{sx:{marginBottom:"20px",maxWidth:275},variant:"body2",children:"API Secret: ********"}),a.jsx(re,{variant:"text",id:`api-query-${Y}-regenerate-link`,onClick:()=>k(Y),sx:{marginBottom:"20px",justifyContent:"flex-start",p:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:"Regenerate secret"})]}),a.jsx(He,{id:`key-account-trash-button-${ne}`,onClick:()=>c(Y),children:a.jsx(Xr,{size:20})})]},Y)});return a.jsxs(T,{sx:{mb:"10px"},id:"connected-accounts-container",children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"row",justifyContent:"flex-start",alignItems:"start"},children:[a.jsx(I,{sx:{fontWeight:"bold",minWidth:"320px"},variant:"body2",children:"Data shares have been set up for:"}),r()&&a.jsx(re,{variant:"text",onClick:e,sx:{mr:3.75,p:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:"Add another connection"}),a.jsx(aS,{})]}),le,ie,J,a.jsx(R$,{destroying:y,open:b,onClickConfirm:()=>{x?M(x):z?V(z):l&&G(l)},onClickCancel:C},x||0),a.jsx(mt,{acceptLabel:"Regenerate",bodyText:"You are about to regenerate an API secret.",cancelLabel:"Cancel",handleAccept:()=>X(),handleClose:()=>k(null),loading:j,open:!!E,title:"Are you sure?"})]})};oS.propTypes={onAddAccountClick:A.func};oS.defaultProps={onAddAccountClick:()=>{}};const lS=({disabled:e=!1,error:t=!1,onChange:n,value:r=[],excludeOptions:s=[]})=>{const i=nIe.filter(l=>!s.includes(l.value)),o=r.filter(l=>!s.includes(l.value));return a.jsxs(T,{sx:{display:"flex",flexDirection:"row",marginTop:"25px",width:"500px"},children:[a.jsxs(RC,{sx:{minWidth:"300px",width:"300px"},error:t,disabled:e,children:[a.jsx(wt,{id:"report-multi-select-label",children:"Data Feed(s)"}),a.jsx(tt,{labelId:"report-multi-select-label",id:"report-multi-select-dropdown",multiple:!0,value:o,onChange:l=>{const c=l.target.value.filter(d=>!s.includes(d)).map(d=>({value:d}));n(c)},input:a.jsx(ys,{label:"Data Feed(s)"}),children:i.map(l=>a.jsx(Se,{value:l.value,children:l.label},l.value))})]}),a.jsx(T,{sx:{alignItems:"flex-end",display:"flex",paddingLeft:"15px"},children:a.jsx(aS,{})})]})};
265lS.propTypes={disabled:A.bool,error:A.bool,onChange:A.func.isRequired,value:A.array,excludeOptions:A.array};const{API_CONNECTIONS:pIe,CURRENT_CONNECTIONS:eD}=ko,hIe=()=>{const{checkCurrentAccounts:e,settings:t={},setPageView:n}=m.useContext(_s),{s3Connections:r={}}=t,{saving:s,setSaving:i,checkClearAllReady:o,checkForDuplicate:l,checkSaveReady:c,clearS3Data:d,duplicateError:u,errorSavingS3Share:p,errorMessageAccessKey:h,errorMessageBucket:f,errorMessageFolder:g,errorMessageKeyId:x,markDuplicate:b,reportsSelected:y,s3AccessKeyText:v,s3FolderText:C,s3KeyIdText:w,s3NameText:S,setDuplicateError:E,setReportsSelected:k,setS3AccessKeyText:j,setS3FolderText:_,setS3KeyIdText:D,setS3NameText:M,setErrorMessageAccessKey:N,setErrorMessageBucket:O,setErrorMessageFolder:R,setErrorMessageKeyId:L,setErrorSavingS3Share:P}=r,F=c(),z=o(),{mpTrack:B}=tr(),{engagementNiceId:W}=pe(),[H]=Z3(),[V]=tM(),G=ne=>{const Y=ne.map(({value:ae})=>ae);k(Y)},X=()=>{N(wb.accessKey),O(wb.s3Bucket),L(wb.keyId),P(!0)},K=async()=>{await V(),i(!1),n(eD),d()},ie=async()=>{i(!0),B("DASHBOARDADMIN DATADELIVERY ACTIONS",{actionType:"ADD S3 BUCKET ACCOUNT",s3Account:S}),await H({body:{body:{aws_secret_access_key:v,aws_access_key_id:w,bucket:S,prefix:C,tables:y}}.body,engagementNiceId:W}).unwrap().then(()=>{setTimeout(K,750)}).catch(()=>{X(),i(!1)})},le=a.jsx(T,{children:a.jsx(re,{variant:"text",onClick:()=>d(),sx:{display:z?"inherit":"none",pointerEvents:s?"none":"auto",pl:0,ml:-5,mt:13,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:"Clear all"})}),ce=a.jsxs(a.Fragment,{children:[a.jsx(I,{sx:{fontWeight:"bold",marginBottom:"20px"},variant:"body2",children:"NOTE: You must have an existing AWS S3 bucket in order to set up the connection."}),a.jsx(I,{sx:{mb:"20px"},variant:"body2",children:"Please fill out all fields below to connect your S3 bucket."})]}),J=a.jsxs(T,{sx:{mt:"40px",display:"flex",flexDirection:"row",maxWidth:300,justifyContent:"space-between"},children:[le,a.jsxs(T,{sx:{display:"flex",flexDirection:"row",justifyContent:"flex-end"},children:[a.jsx(re,{id:"s-three-account-cancel-button",sx:{mb:"20px",minHeight:40,maxHeight:40,pointerEvents:s?"none":"auto","&:hover":F?"auto":"none"},variant:"outlined",onClick:()=>{n(e()?eD:pIe),d()},children:"Cancel"}),a.jsx(re,{id:"s-three-account-submit-button",sx:{pointerEvents:s?"none":"auto",ml:"40px",mb:"20px",minWidth:85,maxWidth:85,minHeight:40,maxHeight:40},disabled:!F,onClick:()=>{l()?b():ie()},variant:"contained",children:s?a.jsx(T,{sx:{margin:"1px 0px 0px 0px"},children:a.jsx(Ze,{color:"inherit",size:30})}):a.jsx("span",{children:"Submit"})})]})]}),he=a.jsxs(a.Fragment,{children:[ce,a.jsx(De,{id:"s-three-name-text-input-field",value:S,error:p||u,helperText:p||u?f:Xp.s3Bucket,label:"S3 bucket name",onChange:({target:ne})=>{const{value:Y}=ne;M(Y),p&&P(!p),u&&E(!u),f!==""&&O("")},size:"small",sx:{width:300},inputProps:{maxLength:125}}),a.jsx(T,{sx:{height:25}}),a.jsx(De,{id:"s-three-folder-text-input-field",value:C,label:"Folder name",helperText:Xp.folderPath,onChange:({target:ne})=>{const{value:Y}=ne;_(Y),p&&P(!p),g!==""&&R("")},size:"small",sx:{width:300},inputProps:{maxLength:125}}),a.jsx(T,{sx:{height:25}}),a.jsx(De,{id:"s-three-key-id-text-input-field",value:w,error:p,helperText:p?x:Xp.keyId,label:"S3 key ID",onChange:({target:ne})=>{const{value:Y}=ne;D(Y),p&&P(!p),x!==""&&L("")},type:"password",size:"small",sx:{width:300},inputProps:{maxLength:125}}),a.jsx(T,{sx:{height:25}}),a.jsx(De,{id:"s-three-access-key-text-input-field",value:v,error:p,helperText:p?h:Xp.accessKey,label:"S3 access key",onChange:({target:ne})=>{const{value:Y}=ne;j(Y),p&&P(!p),h!==""&&N("")},type:"password",size:"small",sx:{width:300},inputProps:{maxLength:125}}),a.jsx(lS,{error:p,onChange:G,value:y||[]}),J]});return a.jsx(T,{sx:{minHeight:150},id:"s-three-setting-container",children:he})},N$=({onClickCancel:e,onClickSubmit:t})=>{const{engagementSfAccountInfo:n,settings:r={}}=m.useContext(_s),{apiConnections:s={}}=r,{creating:i,errorMessage:o,errorSavingShare:l,newAccountText:c,regionSelected:d,reportsSelected:u,setErrorMessage:p,setErrorSavingShare:h,setNewAccountText:f,setRegionSelected:g,setReportsSelected:x}=s,b=w=>{const S=w.map(({value:E})=>E);x(S)},y=()=>{p("This account already exists."),h(!0)},v=()=>{if(n.length===0)return!1;const w=n.filter(S=>S.name!==c);return n.length!==w.length?(y(),!0):!1};return a.jsxs(T,{sx:{minHeight:200},id:"snowflake-account-edit-container",children:[a.jsx(De,{id:"snowflake-account-text-input-field",value:c,error:l,helperText:l?o:"Snowflake account with which the data should be shared.",label:"Snowflake account number",onChange:({target:w})=>{const{value:S}=w;f(S.toUpperCase()),l&&h(!l),o!==""&&p("")},size:"small",sx:{width:300},inputProps:{maxLength:125}}),a.jsx(be,{title:"Us-West-2 is currently the only region available.",placement:"right",arrow:!0,children:a.jsx(T,{sx:{mt:"-5px",width:300},children:a.jsx(Eg,{disabled:!0,id:"settings-regions-select",error:l,width:300,value:d.id,title:d.name,label:"Select Region",onChange:w=>{const S=w?tl.findIndex(E=>E.id===w):-1;S!==-1&&g(tl[S]),l&&h(!l),o!==""&&p("")},options:tl})})}
265),a.jsx(lS,{error:l,onChange:b,value:u||[],excludeOptions:["MEDIA_DIMENSIONS","MEDIA_DIMENSIONS_DEFINITIONS"]}),a.jsxs(T,{sx:{mt:"40px",display:"flex",flexDirection:"row",maxWidth:300,justifyContent:"flex-end"},children:[a.jsx(re,{id:"snowflake-account-cancel-button",sx:{mb:"20px",minHeight:40,maxHeight:40,pointerEvents:i?"none":"auto"},variant:"outlined",onClick:e,children:"cancel"}),a.jsx(re,{id:"snowflake-account-submit-button",sx:{ml:"40px",mb:"20px",minWidth:85,maxWidth:85,minHeight:40,maxHeight:40,pointerEvents:i?"none":"auto"},disabled:!c||!d?.id||!u?.length||v(),onClick:t,variant:"contained",children:i?a.jsx(T,{sx:{margin:"1px 0px 0px 0px"},children:a.jsx(Ze,{color:"inherit",size:30})}):a.jsx("span",{children:"Submit"})})]})]})};N$.propTypes={onClickCancel:A.func.isRequired,onClickSubmit:A.func.isRequired};const{API_CONNECTIONS:fIe,CURRENT_CONNECTIONS:mIe}=ko,gIe=()=>{const{checkCurrentAccounts:e,setPageView:t,settings:n={}}=m.useContext(_s),{apiConnections:r={}}=n,{resetApiConnectionEditVariables:s}=r,{shareCreateStart:i}=M$(),o=a.jsxs(a.Fragment,{children:[a.jsx(I,{sx:{fontWeight:"bold",marginBottom:"20px"},variant:"body2",children:"NOTE: You must have an existing company Snowflake account in order to set up the connection."}),a.jsx(I,{sx:{marginBottom:"20px"},variant:"body2",children:"Please fill out all fields below to connect database specifications for Snowflake."}),a.jsx(N$,{onClickSubmit:i,onClickCancel:()=>{t(e()?mIe:fIe),s()}})]});return a.jsx(T,{sx:{minHeight:"150px"},id:"snowflake-setting-container",children:o})},{API_CONNECTIONS:tD,API_KEY:nD,CURRENT_CONNECTIONS:Kc,SF_DATA_SHARE:xIe,S_THREE_DATA_SHARE:bIe}=ko,yIe=()=>{const{checkCurrentAccounts:e,engagementSfAccountInfo:t,engagementS3AccountInfo:n,engagementKe
265yAccountInfo:r,gatherMetaData:s,gatherSfData:i,pageView:o="",setPageView:l,settings:c={},getDynamicDeliveryOptions:d}=m.useContext(_s)||{},{apiConnections:u={}}=c,{deliveryTypeSelected:p={}}=u;m.useEffect(()=>{e()&&o!==Kc&&o!==nD?l(Kc):!e()&&o===Kc&&l(tD)},[t,n,r,l]);const h=e()?a.jsx(re,{variant:"text",onClick:()=>l(Kc),id:"view-connections-link",sx:{ml:14.375,p:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:"View connections"}):null,f=a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center",marginBottom:"20px"},children:[a.jsx(I,{sx:{fontWeight:"bold"},variant:"body2",children:"Select the type of delivery method(s) to set up."}),h]}),a.jsx(I,{variant:"body2",children:"Once set up can add/delete or edit your delivery methods."}),a.jsx(T,{children:a.jsx(be,{title:"Us-West-2 is currently the only region available.",placement:"right",arrow:!0,disabled:Yc.length>1,children:a.jsx(Eg,{disabled:Yc.length===1,id:"api-delivery-connection",width:300,value:p.id,title:p.name,label:"Delivery selection",onChange:y=>{const v=y?Yc.findIndex(C=>C.id===y):-1;v!==-1&&l(Yc[v].view||"")},options:d(Yc)})})})]}),g=a.jsx(oS,{onAddAccountClick:()=>{l(tD)}});let x=f;switch(o){case xIe:x=a.jsx(gIe,{});break;case bIe:x=a.jsx(hIe,{});break;case Kc:x=g;break;case nD:x=a.jsx(dIe,{});break}return s||i?a.jsx(T,{sx:{paddingTop:"50px",textAlign:"center",width:"100%"},children:a.jsx(Ze,{size:24})}):a.jsxs(T,{sx:{minHeight:"150px",margin:"0px 16px",paddingTop:"15px",display:"flex",alignItems:"center",flexDirection:"column"},id:"api-connection-container",children:[a.jsx(I,{sx:{fontWeight:"bold",mb:4},variant:"h6",children:"API Connection Setup"}),x]})},vIe=()=>{const{pageView:e,setPageView:t}=m.useContext(_s)||{};return m.useEffect(()=>{e!=="api-connections"&&t("api-connections")},[]),a.jsx(T,{sx:{width:ks,minHeight:"500px"},children:a.jsx(yIe,{})})},CIe=()=>a.jsx(iS,{children:a.jsx(vIe,{})}),jb=[{name:"country",label:"Country"},{name:"market",label:"Market"},{name:"oohlocation",label:"Out Of Home Location"},{name:"type",label:"Type"},{name:"platform",label:"Platform"},{name:"tactic",label:"Tactic"},{name:"vehicle",label:"Vehicle"},{name:"program",label:"Program"}],wIe=99.99,O$=m.createContext(null),P$=()=>m.useContext(O$),SIe=({selectionCount:e,onBulkEdit:t,onApprove:n,approveDisabled:r,approveLoading:s=!1})=>a.jsxs(T,{sx:{mb:2,display:"flex",justifyContent:"flex-end",gap:2},children:[a.jsxs(re,{variant:"outlined",disabled:e===0,onClick:t,sx:{textTransform:"none"},children:["Bulk Edit (",e,")"]}),a.jsx(re,{variant:"contained",disabled:r||s,onClick:n,sx:{textTransform:"none",minWidth:160},children:s?a.jsx(Ze,{size:20,color:"inherit"}):"Approve Selected"})]}),jIe=300,kIe=({open:e,onClose:t,onApply:n,value:r,onChange:s,selectionCount:i,attributeName:o,engagementNiceId:l,countryCode:c,geoGranularity:d})=>{const u=o==="market",[p,h]=m.useState(""),[f,g]=m.useState(null),[x,{data:b=[],isFetching:y}]=nM(),v=m.useRef(null),C=m.useCallback(j=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{j.trim()&&x({attributeName:o,search:j,engagementNiceId:l,...u&&{countryCode:c,geoGranularity:d}})},jIe)},[o,l,c,d,x,u]);m.useEffect(()=>(e&&p.trim()&&C(p),()=>{v.current&&clearTimeout(v.current)}),[e,p,C]),m.useEffect(()=>{e||(h(""),g(null))},[e]);const w=m.useMemo(()=>{if(u){const j=new Set;return b.map(_=>{const D=_.desc||"";if(!D)return"";const M=_.country_id??"",N=_.geo_granularity||"",O=`${D}|${M}|${N}`;return j.has(O)?"":(j.add(O),O)}).filter(Boolean)}return b.map(j=>j.name||"").filter((j,_,D)=>!!j&&D.indexOf(j)===_)},[b,u]),S=m.useMemo(()=>{const j=new Map;return b.forEach(_=>{const D=u?`${_.desc||""}|${_.country_id??""}|${_.geo_granularity||""}`:_.name||"";!D||D==="||"||(j.has(D)||j.set(D,[]),j.get(D).push(_))}),j},[b,u]),E=(j,_)=>{const D=S.get(_),M=D?.map(z=>z.geo_granularity).filter(z=>!!z)??[],N=[...new Set(M)].sort(),O=D?.map(z=>z.country_name).filter(z=>!!z)??[],R=[...new Set(O)].sort(),L=u?[...new Set(D?.map(z=>z.name).filter(Boolean)??[])]:[],P=u?[L.join(", "),R.join(", "),N.join(", ")
265].filter(Boolean).join(" · "):N.join(", "),F=u?_.split("|")[0]:_;return m.createElement("li",{...j,key:_},a.jsxs(T,{children:[a.jsx(I,{variant:"body2",children:F}),P&&a.jsx(I,{variant:"caption",color:"text.secondary",children:P})]}))},k=()=>{t()};return a.jsxs(yt,{open:e,onClose:k,maxWidth:"sm",fullWidth:!0,children:[a.jsxs(vt,{children:["Bulk Edit Mapped Name (",i," rows)"]}),a.jsxs(Ct,{children:[a.jsx(gl,{value:r,inputValue:p,onInputChange:(j,_)=>{h(_),C(_)},onChange:(j,_)=>{const D=_?S.get(_)?.[0]:void 0;g(D?.id??null),s(_||"")},options:w,filterOptions:j=>j,loading:y,fullWidth:!0,disableClearable:!0,getOptionLabel:j=>u?j.split("|")[0]||"":j,renderOption:E,renderInput:j=>a.jsx(De,{...j,label:"New Mapped Name",variant:"outlined",sx:{mt:2},InputProps:{...j.InputProps,endAdornment:a.jsxs(a.Fragment,{children:[y&&a.jsx(Ze,{size:18}),j.InputProps.endAdornment]})}})}),a.jsxs(I,{variant:"body2",color:"text.secondary",sx:{mt:2},children:["This will update the mapped name for all ",i,' selected rows and change their status to "edited".']})]}),a.jsxs(un,{children:[a.jsx(re,{onClick:k,sx:{textTransform:"none"},children:"Cancel"}),a.jsxs(re,{onClick:()=>n(f),variant:"contained",disabled:!r,sx:{textTransform:"none"},children:["Apply to ",i," Rows"]})]})]})},EIe=300,_Ie=e=>{const{id:t,value:n,field:r,api:s,attributeName:i,engagementNiceId:o}=e,{engagementCountryCode:l,engagementGeoGranularity:c}=pe(),{setSelectedAttributeId:d,deleteSelectedAttributeId:u}=P$(),p=i==="market",[h,f]=m.useState(!0),[g,x]=m.useState(String(n||"")),[b,{data:y=[],isFetching:v}]=nM(),C=fs(_=>{b({attributeName:i,search:_,engagementNiceId:o,...p&&{countryCode:l,geoGranularity:c}})},EIe);m.useEffect(()=>{b({attributeName:i,search:String(n||""),engagementNiceId:o,...p&&{countryCode:l,geoGranularity:c}})},[i,n,o,p,l,c,b]);const w=m.useMemo(()=>y.map(_=>(p?_.desc:_.name)||"").filter((_,D,M)=>!!_&&M.indexOf(_)===D),[y,p]),S=m.useMemo(()=>{const _=new Map;return y.forEach(D=>{const M=(p?D.desc:D.name)||"";M&&(_.has(M)||_.set(M,[]),_.get(M).push(D))}),_},[y,p]),E=(_,D)=>{f(!1);const M=D?S.get(D)?.[0]:void 0;M?.id?d(String(t),M.id):u(String(t)),s.setEditCellValue({id:t,field:r,value:D||""}),s.stopCellEditMode({id:t,field:r})},k=(_,D,M)=>{x(D),M==="input"&&(f(!0),C(D))},j=(_,D)=>{const M=S.get(D),N=M?.map(z=>z.geo_granularity).filter(z=>!!z)??[],O=[...new Set(N)].sort(),R=M?.map(z=>z.country_name).filter(z=>!!z)??[],L=[...new Set(R)].sort(),P=p?[...new Set(M?.map(z=>z.name).filter(Boolean)??[])]:[],F=p?[P.join(", "),L.join(", "),O.join(", ")].filter(Boolean).join(" · "):O.join(", ");return m.createElement("li",{..._,key:D},a.jsxs(T,{sx:{display:"flex",justifyContent:"space-between",width:"100%",gap:2},children:[a.jsx(I,{sx:{fontSize:14},children:D}),F&&a.jsx(I,{sx:{fontSize:12,color:"text.secondary",whiteSpace:"nowrap"},children:F})]}))};return a.jsx(gl,{value:n||"",inputValue:g,onInputChange:k,onChange:E,options:w,loading:v,freeSolo:!0,autoFocus:!0,fullWidth:!0,disableClearable:!0,open:h,onClose:()=>f(!1),disablePortal:!0,filterOptions:_=>_,renderOption:j,componentsProps:{popper:{sx:({palette:_})=>({"& .MuiAutocomplete-paper":{border:"1px solid",borderColor:_.divider,boxShadow:3}})}},renderInput:_=>a.jsx(De,{..._,variant:"standard",sx:{"& .MuiInput-root":{fontSize:14,px:1}},InputProps:{..._.InputProps,endAdornment:a.jsxs(a.Fragment,{children:[v?a.jsx(Ze,{color:"inherit",size:16}):null,_.InputProps.endAdornment]})}}),sx:{height:"100%","& .MuiAutocomplete-inputRoot":{height:"100%",alignItems:"center"}}})},TIe=({status:e})=>e?a.jsx(T,{sx:{backgroundColor:e==="edited"?"info.light":e==="pending"?"warning.light":e==="approved"?"success.light":"grey.200",color:e==="edited"?"info.dark":e==="pending"?"warning.dark":e==="approved"?"success.dark":"text.primary",px:1.5,py:.5,borderRadius:1,fontSize:12,fontWeight:500,textTransform:"capitalize",display:"inline-block"},children:e}):null,Qc=[...sM().filter(e=>e.value==="isAnyOf"),...Em().filter(e=>["contains","equals","startsWith","endsWith","isEmpty","isNotEmpty"].includes(e.value))],IIe=({hasCategory:e,isMarket:t,uniqueTokens:n,uniqueAttributeNames:r,uniqueCategories:s,uniqueCountryIds:i,uniqueGeoGranularities:o,attributeName:l,engagementNiceId:c})=>{const d=[{field:"token",headerName:"INCOMING NAME",width:200,type:"singleSelect",valueOptions:n,filterable:!0,filterOperators:Qc,renderCell:u=>{const p=u.row,h=(p.match_percent??100)<wIe&&!["approved","pending"].includes(p.status||"");return a.jsx(I,{color:h?"error":"text.primary",title:p.token.trim(),sx:{fontSize:14},children:p.token.trim()})}},{field:"attribute_name",headerName:"MAPPED NAME",flex:1,minWidth:250,type:"singleSelect",valueOptions:r,editable:!0,filterable:!0,filterOperators:Qc,valueGetter:u=>{const p=u.row;return t?p.staged_attribute_desc||p.attribute_desc||"":p.staged_attribute_name||p.attribute_name||""},valueSetter:u=>{const{row:p}=u;if(t){const x=(p.staged_attribute_desc||p.attribute_desc||"")!==u.value;return{...p,attribute_desc:u.value,staged_attribute_desc:u.value,status:x?"edited":p.status}}const f=(p.staged_attribute_name||p.attribute_name||"")!==u.value;return{...p,attribute_name:u.value,staged_attribute_name:u.value,status:f?"edited":p.status}},renderEditCell:u=>a.jsx(_Ie,{...u,attributeName:l,engagementNiceId:c})}];
265return e&&d.push({field:"category",headerName:"CATEGORY",width:120,type:"singleSelect",valueOptions:s,filterable:!0,filterOperators:Qc,valueGetter:u=>{const p=u.row;return p.staged_attribute_category_id?"":p.attribute_category_name||""}}),t&&d.push({field:"country_id",headerName:"COUNTRY ID",width:120,type:"singleSelect",valueOptions:i,filterable:!0,filterOperators:sM().filter(u=>u.value==="isAnyOf")},{field:"geo_granularity",headerName:"GEO GRANULARITY",width:150,type:"singleSelect",valueOptions:o,filterable:!0,filterOperators:Qc}),d.push({field:"match_percent",headerName:"MATCH",width:100,type:"number",align:"right",headerAlign:"right",filterable:!0},{field:"status",headerName:"STATUS",width:120,type:"singleSelect",valueOptions:["edited","pending","approved"],filterable:!0,filterOperators:Qc,renderCell:u=>a.jsx(TIe,{status:u.row.status})}),d},DIe=rt(Mn)(({theme:e})=>{const{palette:t,spacing:n}=e,{background:r,border:s,text:i}=t;return{border:"1px solid",borderColor:e.palette.divider,borderRadius:n(2),[`& .${xe.main}`]:{borderRadius:n(2)},[`& .${xe.columnHeaders}`]:{backgroundColor:r.tableHeader,borderBottom:"1px solid",borderColor:e.palette.divider},[`& .${xe.columnHeader}`]:{fontSize:12,height:18,textTransform:"uppercase",color:i.secondary},[`& .${xe.columnHeaderCheckbox}`]:{paddingLeft:0,paddingRight:0},[`& .${xe.columnSeparator}`]:{color:s.default,":hover":{color:s.default}},[`& .${xe.row}:nth-of-type(n)`]:{backgroundColor:r.paper,":hover":{backgroundColor:e.palette.mode==="dark"?r.brand.subtle.hovered:r.brand.subtlest.default}},[`& .${xe.cell}`]:{border:"none"},[`& .${xe.cell}--editing`]:{border:"none !important",boxShadow:"none !important"},[` 266 & .${xe.cell}:focus, 267 & .${xe.cell}:focus-within, 268 & .${xe.columnHeader}:focus, 269 & .${xe.columnHeader}:focus-within 270 `]:{outline:"none"},"& .MuiTablePagination-selectLabel":{fontWeight:500,letterSpacing:.5,lineHeight:"20px",fontSize:12,color:i.secondary},"& .MuiTablePagination-input":{fontWeight:500,letterSpacing:.5,lineHeight:"20px",fontSize:12}}}),AIe=(e,t)=>e?"approved":t?"edited":"pending",MIe=e=>{const t=e.id?String(e.id):e.token,n=AIe(!!e.approved,e.edited),r=e.staged_attribute_name||e.attribute_name||"",s=e.staged_attribute_desc||e.attribute_desc||"",i=`${t} ${r} ${s}`.toLowerCase();return{...e,searchToken:i,status:n}},RIe=({attributeName:e,expanded:t,engagementId:n,engagementNiceId:r,mpTrack:s,userIsApprover:i})=>{const{pushNotification:o}=jt(),{engagementCountryCode:l,engagementGeoGranularity:c}=pe(),{getSelectedAttributeId:d,deleteSelectedAttributeId:u}=P$(),p=e==="market",h=e==="vehicle",f=p?"id":"token",[g,x]=m.useState([]),[b,y]=m.useState([{field:"token",sort:"asc"}]),[v,C]=m.useState(!1),[w,S]=m.useState(""),[E,k]=m.useState(!1),[j,_]=m.useState(new Map),D=zn(),{data:M=[],isLoading:N,isFetching:O,refetch:R}=eW({attributeName:e,engagementId:n,limit:1e3,offset:0,approved:!1});tW({attributeName:e},{skip:!(e==="program"||e==="vehicle")});const[P]=nW(),[F]=rW(),z=m.useMemo(()=>M.map(MIe),[M]),B=m.useMemo(()=>z.map(ne=>{const Y=String(ne[f]??""),ae=j.get(Y);return ae?{...ne,...ae,rowId:Y,status:"edited"}:{...ne,rowId:Y}}),[z,f,j]),W=m.useCallback(async()=>{s("DASHBOARDADMIN NAMECLEANING ACTIONS",{attributeName:e,actionType:"APPROVE",currentTab:"ATTRIBUTES"}),k(!0);const ne=new Set(g.map(String));try{const Y=z.filter(me=>{const ve=me[f];return ve!=null&&ne.has(String(ve))&&me.status!=="approved"}),ae=Y.reduce((me,ve)=>{const Me=ve[f];if(Me==null)return me;const q=d(String(Me));return q&&(u(String(Me)),me.push(F({tokens:[Me],attributeId:q,key:f,attribute_name:e}).unwrap())),me},[]);await Promise.all(ae);const je=Y.map(me=>me[f]).filter(me=>me!=null);je.length>0&&await P({attributeName:e,aliases:je,key:f}),x([]),_(new Map),await R()}catch{o({content:"Failed to approve. Please try again.",severity:"error",timeout:1e4})}finally{k(!1)}},[g,z,f,e,s,F,P,R,o,d,u]),{uniqueTokens:H,uniqueAttributeNames:V,uniqueCategories:G,uniqueCountryIds:X,uniqueGeoGranularities:K}=m.useMemo(()=>{const ne=new Set,Y=new Set,ae=new Set,je=new Set,me=new Set;return z.forEach(ve=>{ne.add(ve.token);const Me=p?ve.staged_attribute_desc||ve.attribute_desc||"":ve.staged_attribute_name||ve.attribute_name||"";Me&&Y.add(Me);const q=ve.staged_attribute_category_id?"":ve.attribute_category_name||"";q&&ae.add(q);const Q=ve.country_id;Q!=null&&je.add(Q);const ee=ve.geo_granularity;ee!=null&&me.add(ee)}),{uniqueTokens:[...ne].sort((ve,Me)=>
270ve.localeCompare(Me)),uniqueAttributeNames:[...Y].sort((ve,Me)=>ve.localeCompare(Me)),uniqueCategories:[...ae].sort((ve,Me)=>ve.localeCompare(Me)),uniqueCountryIds:[...je].sort((ve,Me)=>ve-Me),uniqueGeoGranularities:[...me].sort((ve,Me)=>ve.localeCompare(Me))}},[z,p]),ie=m.useMemo(()=>IIe({hasCategory:h,isMarket:p,uniqueTokens:H,uniqueAttributeNames:V,uniqueCategories:G,uniqueCountryIds:X,uniqueGeoGranularities:K,attributeName:e,engagementNiceId:r}),[h,p,H,V,G,X,K,e,r]),le=m.useCallback(()=>{C(!1),S("")},[]),ce=m.useCallback(async(ne,Y)=>{const ae=p?ne.staged_attribute_desc||ne.attribute_desc||"":ne.staged_attribute_name||ne.attribute_name||"",je=p?Y.staged_attribute_desc||Y.attribute_desc||"":Y.staged_attribute_name||Y.attribute_name||"";if(ae===je)return Y;const me=ne[f]??null;if(!ae)throw new Error("Missing required fields for update.");if(me==null)throw new Error("Missing required fields for update.");const ve=String(me),Me=d(ve)??null;if(Me)try{await F({tokens:[me],attributeId:Me,key:f,attribute_name:e}).unwrap(),u(ve)}catch{o({content:"Failed to update row. Please try again.",severity:"error",timeout:1e4})}const q={...ne,status:"edited"};return _(Q=>{const ee=new Map(Q);return ee.set(String(ne.rowId),q),ee}),q},[f,p,e,F,o,d,u]),J=m.useCallback(()=>{o({content:"Failed to update row. Please try again.",severity:"error",timeout:1e4})},[o]),he=m.useCallback(async ne=>{if(!w)return;s("DASHBOARDADMIN NAMECLEANING ACTIONS",{attributeName:e,actionType:"BULK_EDIT",currentTab:"ATTRIBUTES",rowCount:g.length});const Y=g.map(String),ae=Y.map(je=>{const me=B.find(ve=>ve.rowId===je);if(me)return z.find(ve=>String(ve[f])===String(me[f]))}).filter(je=>!!je);try{const je=ae.map(me=>f==="id"?me.id??me.token:me.token).filter(me=>me!=null);if(je.length===0)throw new Error("Missing required fields for update.");ne&&await F({tokens:je,attributeId:ne,key:f,attribute_name:e}).unwrap(),_(me=>{const ve=new Map(me),Me=p?{attribute_desc:w,staged_attribute_desc:w,status:"edited"}:{attribute_name:w,staged_attribute_name:w,status:"edited"};return Y.forEach(q=>ve.set(q,Me)),ve}),x([]),C(!1),S("")}catch{o({content:"Failed to update rows. Please try again.",severity:"error",timeout:1e4})}},[w,p,g,B,z,f,e,s,F,o]);return t?a.jsxs(T,{sx:{height:"100%",width:"100%"},children:[a.jsx(SIe,{selectionCount:g.length,onBulkEdit:()=>C(!0),onApprove:W,approveDisabled:!i||g.length===0,approveLoading:E}),a.jsx(T,{sx:{height:600},children:a.jsx(DIe,{apiRef:D,rows:B,columns:ie,loading:N||O,checkboxSelection:!0,disableRowSelectionOnClick:!0,rowSelectionModel:g,onRowSelectionModelChange:x,sortModel:b,onSortModelChange:y,getRowId:ne=>ne.rowId,pageSizeOptions:[25,50,100],initialState:{filter:{filterModel:{items:[{field:"status",operator:"isAnyOf",value:["edited","pending"]}]}},pagination:{paginationModel:{pageSize:25}}},filterMode:"client",disableColumnFilter:!1,processRowUpdate:ce,onProcessRowUpdateError:J,editMode:"cell",isRowSelectable:ne=>{const Y=ne.row;return Y.status==="edited"||Y.status==="pending"},isCellEditable:({field:ne,row:Y})=>ne==="attribute_name"&&Y.status!=="approved",onCellClick:({field:ne,id:Y,isEditable:ae,row:je})=>{const me=D.current.getCellMode(Y,ne);ne==="attribute_name"&&ae&&je.status!=="approved"&&me==="view"&&D.current.startCellEditMode({id:Y,field:ne})}})}),a.jsx(kIe,{open:v,onClose:le,onApply:he,value:w,onChange:S,selectionCount:g.length,attributeName:e,engagementNiceId:r,countryCode:l,geoGranularity:c})]}):null},NIe=({attributeName:e,expanded:t,engagementId:n,engagementNiceId:r,mpTrack:s,userIsApprover:i})=>{const o=m.useRef(new Map),l=m.useCallback((p,h)=>{o.current.set(p,h)},[]),c=m.useCallback(p=>o.current.get(p),[]),d=m.useCallback(p=>{o.current.delete(p)},[]),u=m.useMemo(()=>({setSelectedAttributeId:l,getSelectedAttributeId:c,deleteSelectedAttributeId:d}),[l,c,d]);return a.jsx(O$.Provider,{value:u,children:a.jsx(RIe,{attributeName:e,expanded:t,engagementId:n,engagementNiceId:r,mpTrack:s,userIsApprover:i})})},OIe=()=>({container:{display:"flex",flexDirection:"column",paddingBottom:30,margin:"40px 20px 0 20px"},heading:{fontSize:16,padding:0}}),L$=({classes:e})=>{const[t,n]=m.useState(jb[1].name),{engagementNiceId:r,engagementId:s}=pe(),i=yn({authorized:"DataSources.NameCleaning.Approve"}),{mpTrack:o}=tr(),{data:l=[]}=sW(),{data:c=[]}=iW(),d=jb.find(u=>u.name===t);return a.jsxs("div",{className:e.container,children:[a.jsxs(T,{sx:{mb:3,maxWidth:300},children:[a.jsx(I,{variant:"caption",sx:{color:"text.secondary",display:"block",fontSize:12,fontWeight:500,letterSpacing:.5,mb:1,textTransform:"uppercase"},children:"Cleaning Attribute"}),a.jsx(Qe,{fullWidth:!0,size:"small",children:a.jsx(tt,{id:"attribute-select",value:t,onChange:u=>n(u.target.value),sx:{backgroundColor:"background.paper","& .MuiSelect-select":{py:1}},children:jb.map(({name:u,label:p})=>
270a.jsx(Se,{value:u,children:p},`attribute-option-${u}`))})})]}),a.jsx(NIe,{attributeName:d.name,expanded:!0,engagementId:s,engagementNiceId:r,categories:l,languages:c,mpTrack:o,userIsApprover:i},d.name)]})};L$.propTypes={classes:A.object.isRequired};const PIe=Be(OIe)(L$),cS="has_error",LIe="none",FIe=["country_id","market_id","oohlocation_id","platform_id","program_id","tactic_id","type_id","vehicle_id","media_attribute_1","media_attribute_2","media_attribute_3","media_attribute_4","media_attribute_5","media_attribute_6","media_attribute_7","media_attribute_8","row_access"],dS=["country_id","market_id","type_id","vehicle_id"],Hn={PLACEMENT:{FIRST_COLUMN:41,SECOND_COLUMN:137},RULES:{FIRST_COLUMN:0,SECOND_COLUMN:178}},F$=[{data:"vendor_nice_id",header:"Vendor",width:90,visible:!0},{data:"campaign_id",header:"Campaign ID",width:92,visible:!1},{data:"campaign_name",header:"Campaign",width:92,visible:!0},{data:"account_name",header:"Account Name",width:95,visible:!1},{data:"adgroup_id",header:"Ad Group ID",width:95,visible:!1},{data:"adgroup_name",header:"Ad Group Name",width:95,visible:!1},{attributeName:"category",data:"category_name",header:"Category",width:90,visible:!0},{attributeName:"type",data:"type_name",header:"Type",width:90,visible:!0,cellType:"attribute"},{attributeName:"platform",data:"platform_name",header:"Platform",width:90,visible:!0,cellType:"attribute"},{attributeName:"tactic",data:"tactic_name",header:"Tactic",width:90,visible:!0,cellType:"attribute"},{attributeName:"vehicle",data:"vehicle_name",header:"Vehicle",width:90,visible:!0,cellType:"attribute"},{attributeName:"program",data:"program_name",header:"Program",width:90,visible:!0,cellType:"attribute"},{attributeName:"country",data:"country_name",header:"Country",width:90,visible:!0,cellType:"attribute"},{attributeName:"market",data:"market_name",header:"Market",width:90,visible:!0,cellType:"attribute"},{attributeName:"oohlocation",data:"oohlocation_name",header:"Out Of Home Location",width:90,visible:!0,filterable:!0,cellType:"attribute"},{data:"media_attribute_1",header:"Attribute 1",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_2",header:"Attribute 2",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_3",header:"Attribute 3",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_4",header:"Attribute 4",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_5",header:"Attribute 5",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_6",header:"Attribute 6",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_7",header:"Attribute 7",width:100,visible:!1,cellType:"customAttribute"},{data:"media_attribute_8",header:"Attribute 8",width:100,visible:!1,cellType:"customAttribute"},{attributeName:"row_access",data:"row_access",header:"Row Access",width:90,visible:!0,filterable:!0,cellType:"attribute"}],$$=[{data:"vendor_nice_id",header:"Vendor",name:"vendor",visible:!0,width:80},{data:"creative_id",header:"Creative ID",name:"creative_id",visible:!1,width:175},{cellType:"textEdit",data:"brand",header:"Brand",name:"brand",visible:!0,width:100},{cellType:"textEdit",data:"campaign",header:"Campaign",name:"campaign",visible:!0,width:200},{cellType:"textEdit",data:"unit_size_duration",header:a.jsxs("div",{style:{whiteSpace:"nowrap"},children:["Unit Size/",a.jsx("br",{}),"Duration"]}),name:"unit",visible:!0,width:104},{cellType:"textEdit",data:"message",header:"Message",name:"message",visible:!0,width:130},{cellType:"select",data:"a_b",header:"A/B Testing",name:"a_b",options:[{label:"A",value:"A"},{label:"B",value:"B"},{label:"N/A",value:"N/A"}],visible:!0,width:112},{cellType:"textEdit",data:"control",header:"Control",name:"control",visible:!0,width:130},{cellType:"select",data:"language",header:"Language",name:"language",options:[{label:"English",value:"English"},{label:"Spanish",value:"Spanish"},{label:"German",value:"German"}],visible:!0,width:120},{cellType:"textEdit",data:"creative_attribute_1",header:"Attribute 1",name:"attribute_1",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_2",header:"Attribute 2",name:"attribute_2",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_3",header:"Attribute 3",name:"attribute_3",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_4",header:"Attribute 4",name:"attribute_4",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_5",header:"Attribute 5",name:"attribute_5",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_6",header:"Attribute 6",name:"attribute_6",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_7",header:"Attribute 7",name:"attribute_7",searchable:!0,visible:!1,width:120},{cellType:"textEdit",data:"creative_attribute_8",header:"Attribute 8",name:"attribute_8",searchable:!0,visible:!1,width:125}],hl=[{alwaysOn:!0,data:"brand",header:"Brand",width:150,visible:!0,cellType:"select"},{data:"placement_id",header:"Placement ID",width:140,visible:!0,filterable:!0},{data:"placement_name",header:"Placement",width:120,visible:!0,sortable:!0},{data:"creative_id",header:"Creative ID",width:90,visible:!0,filterable:!0},{data:"creative_name",header:"Creative",width:150,visible:!0,filterable:!0},{data:"campaign_id",header:"Campaign ID",width:90,visible:!0,filterable:!0},{data:"campaign_name",header:"Campaign",width:90,visible:!0,filterable:!0},{data:"vendor",header:"Vendor",width:90,visible:!0,filterable:!0},{data:"type",header:"Type",width:90,visible:!0,filterable:!0},{data:"category",header:"Category",width:90,visible:!0,filterable:!0},{data:"media_id",header:"Media ID",width:90,visible:!1,filterable:!0},{data:"message",header:"Message",width:90,visible:!1,filterable:!0},{data:"platform",header:"Platform",width:90,visible:!1,filterable:!0},{data:"tactic",header:"Tactic",width:90,visible:!1,filterable:!0},{data:"vehicle",header:"Vehicle",width:90,visible:!1,filterable:!0},{data:"program",header:"Program",width:90,visible:!1,filterable:!0},{data:"market",header:"Market",width:90,visible:!1,filterable:!0},{data:"country",header:"Country",width:90,visible:!1,filterable:!0},{data:"media_attribute_1",header:"Media Attribute 1",width:100,visible:!1,filterable:!0},{data:"media_attribute_2",header:"Media Attribute 2",width:100,visible:!1,filterable:!0},{data:"media_attribute_3",header:"Media Attribute 3",width:100,visible:!1,filterable:!0},{data:"media_attribute_4",header:"Media Attribute 4",width:100,visible:!1,filterable:!0},{data:"media_attribute_5",header:"Media Attribute 5",width:100,visible:!1,filterable:!0},{data:"media_attribute_6",header:"Media Attribute 6",width:100,visible:!1,filterable:!0},{data:"media_attribute_7",header:"Media Attribute 7",width:100,visible:!1,filterable:!0},{data:"media_attribute_8",header:"Media Attribute 8",width:100,visible:!1},{data:"creative_attribute_1",header:"Creative Attribute 1",width:100,visible:!1,filterable:!0},{data:"creative_attribute_2",header:"Creative Attribute 2",width:100,visible:!1,filterable:!0},{data:"creative_attribute_3",header:"Creative Attribute 3",width:100,visible:!1,filterable:!0},{data:"creative_attribute_4",header:"Creative Attribute 4",width:100,visible:!1,filterable:!0},{data:"creative_attribute_5",header:"Creative Attribute 5",width:100,visible:!1,filterable:!0},{data:"creative_attribute_6",header:"Cretive Attribute 6",width:100,visible:!1,filterable:!0},{data:"creative_attribute_7",header:"Creative Attribute 7",width:100,visible:!1,filterable:!0},{data:"creative_attribute_8",header:"Creative Attribute 8",width:100,visible:!1,filterable:!0}],uS=e=>e.reduce((t,n)=>({...t,[n.data]:n.visible}),{}),$Ie=uS(F$),zIe=uS($$),z$=uS(hl),rn={BRAND:"mr_media_creative",CREATIVE:"mr_creative_stage",PLACEMENT:"mr_media_stage"},B$={[rn.BRAND]:{columnDefinitions:hl,defaultColumnVisibility:z$,updateEndpoint:"",createLambdaName:"",updateLambdaName:void 0,headerName:"Brand"},[rn.CREATIVE]:{columnDefinitions:$$,defaultColumnVisibility:zIe,updateEndpoint:"UpdateStagedCreatives",createLambdaName:"CreateCreatives",updateLambdaName:void 0,headerName:"Creative"},[rn.PLACEMENT]:{columnDefinitions:F$,defaultColumnVisibility:$Ie,updateEndpoint:"TriggerAsyncLambda",createLambdaName:"CreatePlacements",updateLambdaName:"UpdateStagedPlacements",headerName:"Placement"}},pS=({body:e,engagementNiceId:t,tableName:n})=>{const{data:r={},isFetching:s,refetch:i}=$a({apiName:"mediaResolution",endpoint:"GetStagedPlacements",parameters:{body:e,pathParameters:{niceId:t}}},{skip:n!==rn.PLACEMENT}),o=m.useMemo(()=>r?.placements||[],[r]),{data:l={},isFetching:c,refetch:d}=$a({apiName:"mediaResolution",endpoint:"CountStagedPlacements",parameters:{body:e,pathParameters:{niceId:t}}},{skip:n!==rn.PLACEMENT}),u=l?.count||0,p=m.useCallback(()=>{i(),d()},[d,i]),{data:h={},isFetching:f,refetch:g}=$a({apiName:"mediaResolution",endpoint:"GetStagedCreatives",parameters:{body:e,pathParameters:{niceId:t}}},{skip:n!==rn.CREATIVE}),{count:x=0,creatives:b=[]}=h||{},{data:y={},isFetching:v,refetch:C}=aW({body:e,engagementNiceId:t},{skip:n!==rn.BRAND}),{count_current_view:w=0,media_creative:S=[],...E}=y||{};let k,j,_,D,M,N;switch(n){case rn.BRAND:k=w,j=v,_=S,D=v,M=C,N=E;break;case rn.CREATIVE:k=x,j=f,_=b,D=f,M=g;break;case rn.PLACEMENT:default:k=u,j=c,_=o,D=s,M=p}return m.useMemo(()=>({count:k,countFetching:j,placements:_,placementsFetching:D,refetch:M,rest:N}),[k,j,_,D,M,N])},U$={ASC:"ASC",DESC:"DESC"},Yn={VIEW_ALL:{value:"view_all",label:"View all"},APPROVED:{value:"approved",label:"Approved"},EDITED:{value:"edited",label:"Edited"},UNEDITED:{value:"unedited",label:"Unedited"}},rD={[Yn.VIEW_ALL.value]:!0,[Yn.APPROVED.value]:!0,[Yn.EDITED.value]:!0,[Yn.UNEDITED.value]:!0},V$=e=>Object.entries(e).filter(([,t])=>t).map(([t])=>t),gr=m.createContext(null),hS=({children:e,initialStore:t})=>{const[n,r]=m.useState(t.clearFiltersLinkActive),[s,i]=m.useState(t.columnFilters),[o,l]=m.useState(t.columnVisibility),[c,d]=m.useState(t.countCurrentSelected),[u,p]=m.useState(t.currentPage),[h,f]=m.useState(t.editLockIsActive),[g,x]=m.useState(t.excludedRows),[b,y]=m.useState(t.loading),[v,C]=m.useState(t.numberOfPages),[w,S]=m.useState(t.rowsPerPage),[E,k]=m.useState(t.searchText),[j,_]=m.useState(t.selectAllActivated),[D,M]=m.useState(t.selectedRows),[N,O]=m.useState(t.sortColumn),[R,L]=m.useState(t.sortDirection),[P,F]=m.useState(t.tableView),[z,B]=m.useState(t.taskId),W=m.useMemo(()=>V$(P),[P]),H=m.useMemo(()=>hl.filter(G=>o[G.data]||G.alwaysOn||G.visible),[o]);m.useEffect(()=>{_(!1),M([]),x([])},[h]);const V=m.useMemo(()=>({clearFiltersLinkActive:n,columnDefinitions:hl,columnFilters:s,columnVisibility:o,countCurrentSelected:c,currentPage:u,currentTableView:W,editLockIsActive:h,excludedRows:g,loading:b,numberOfPages:v,rowsPerPage:w,searchText:E,selectAllActivated:j,selectedRows:D,sortColumn:N,sortDirection:R,tableView:P,taskId:z,visibleColumns:H,setClearFiltersLinkActive:r,setColumnFilters:i,setColumnVisibility:l,setCountCurrentSelected:d,setCurrentPage:p,setEditLockIsActive:f,setExcludedRows:x,setLoa
270ding:y,setNumberOfPages:C,setRowsPerPage:S,setSearchText:k,setSelectAllActivated:_,setSelectedRows:M,setSortColumn:O,setSortDirection:L,setTableView:F,setTaskId:B}),[n,s,o,c,u,W,h,g,b,v,w,E,j,D,N,R,P,z,H]);return a.jsx(gr.Provider,{value:V,children:e})};hS.propTypes={children:A.node.isRequired,initialStore:A.object};hS.defaultProps={initialStore:{clearFiltersLinkActive:!1,columnDefinitions:hl,columnFilters:[],columnVisibility:z$,countCurrentSelected:0,currentPage:0,currentTableView:V$(rD),editLockIsActive:!0,excludedRows:[],loading:!0,numberOfPages:0,rowsPerPage:25,searchText:"",selectAllActivated:!1,selectedRows:[],sortColumn:"placement_name",sortDirection:U$.ASC,tableView:rD,taskId:null,visibleColumns:hl}};const BIe=()=>{const{engagementNiceId:e}=pe(),t=yn({authorized:"DataSources.NameCleaning.Approve"}),{mpTrack:n}=tr(),[r]=Qi(),{columnFilters:s,countCurrentSelected:i,currentPage:o,currentTableView:l,editLockIsActive:c,excludedRows:d,loading:u,rowsPerPage:p,searchText:h,selectAllActivated:f,setSelectAllActivated:g,selectedRows:x,setSelectedRows:b,setTaskId:y,sortColumn:v,sortDirection:C,visibleColumns:w}=m.useContext(gr),S=t&&!u&&(f&&i>0||x.length>0),E=l.filter(M=>c&&M!=="view_all"&&M!=="approved"||!c),k=m.useMemo(()=>{const M={engagement_nice_id:e,lambdaName:"UpdateMediaCreatives",column_filters:s,data:{approved:!0},page_offset:o,page_size:p,search_text:h,sort_column:v,sort_direction:C,views:E,visible_columns:w};return f?M.excluded_media_creative_ids=d:M.media_creative_ids=x,M},[s,o,e,d,p,h,f,x,v,C,E,w]),[j,_]=m.useState(!1),D=async()=>{n("DASHBOARDADMIN NAMECLEANING ACTIONS",{actionType:"APPROVE",currentTab:"BRANDS"});const{task_id:M}=await r({apiName:"mediaResolution",endpoint:"TriggerAsyncLambda",parameters:{body:k,pathParameters:{niceId:e}}}).unwrap();y(M),b([]),f&&g(!f),_(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(re,{color:"primary",disabled:!S,id:"approve-brands-button",variant:"contained",onClick:()=>_(!0),children:"Approve"}),a.jsx(mt,{acceptLabel:"Approve",bodyText:`You are about to approve ${X4(i)} brand edits.`,handleAccept:D,handleClose:()=>_(!1),open:j,title:"Are you sure?"})]})},UIe=()=>{const{clearFiltersLinkActive:e,setClearFiltersLinkActive:t,setColumnFilters:n}=m.useContext(gr);return e&&a.jsx(re,{variant:"text",sx:{p:0,pt:3,mr:15,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},onClick:()=>{n([]),t(!1)},children:"Clear all column filters"})},VIe=e=>({menu:{border:`solid 1px ${e.palette.secondary.main}`,top:"10px !important"},menuItem:{textAlign:"left",width:160},addColumnIconFill:{fill:e.palette.secondary.main},addColumnIconPlus:{stroke:e.palette.secondary.main}}),W$=({classes:e})=>{const{palette:t}=Re(),{columnVisibility:n,setColumnVisibility:r,visibleColumns:s}=m.useContext(gr),[i,o]=m.useState(null),l=d=>{const u=n[d],p={...n,[d]:!u};r(p)},c=s.filter(d=>!d.alwaysOn).map(({data:d,header:u,visible:p})=>a.jsx(Se,{disableGutters:!0,sx:{p:0},children:a.jsxs(He,{onClick:()=>l(d),"data-testid":"column-checkbox",children:[a.jsx(et,{checked:p}),a.jsx(I,{className:e.menuItem,children:u})]})},d));return a.jsxs(a.Fragment,{children:[a.jsx(be,{title:"Add/remove columns from table.",placement:"right",arrow:!0,children:a.jsx(He,{"aria-controls":"brand-column-picker","aria-haspopup":"true","data-testid":"nc-column-selector",onClick:d=>{const{currentTarget:u}=d;o(u)},children:a.jsx(po,{color:t.secondary.main})})}),a.jsx(dr,{anchorEl:i,className:e.menu,id:"column-picker",open:!!i,onClose:()=>o(null),anchorOrigin:{vertical:"bottom",horizontal:"left"},MenuListProps:{sx:{border:"1px solid",borderColor:"secondary.main"}},transformOrigin:{vertical:"top",horizontal:"left"},PaperProps:{style:{maxHeight:224,width:220}},children:c})]})};W$.propTypes={classes:A.object.isRequired};const WIe=Be(VIe)(W$),H$={controls:{display:"flex",flexDirection:"column",marginLeft:15},bottomControlBox:{marginTop:20,alignItems:"center",display:"flex",flexDirection:"row",justifyContent:"space-between"},leftBottom:{alignItems:"center",display:"flex",flexDirection:"row"},controlBox:{alignItems:"flex-end",display:"flex",flexDirection:"row",justifyContent:"space-between",marginTop:20},viewSearch:{alignItems:"flex-end",display:"flex",flexDirection:"row"},approveButton:{alignItems:"flex-end",display:"flex",flexDirection:"row",paddingRight:15},infoText:{marginLeft:5},rowLockContainer:{display:"flex",flexDirection:"row",alignItems:"center"},search:{marginLeft:40,width:240}},q$=({classes:e})=>{const{editLockIsActive:t,excludedRows:n,selectAllActivated:r,selectedRows:s,setEditLockIsActive:i}=m.useContext(gr),[o,l]=m.useState(!1),c=a.jsxs(I,{component:"span",children:["You are about to ",a.jsx("strong",{children:"deselect all selected rows"}
270),' if you turn OFF/ ON the "Unlock approved rows to edit" toggle.']});return a.jsxs("div",{className:e.rowLockContainer,children:[a.jsx(Dn,{checked:!t,id:"edit-lock-active-switch",onClick:()=>{r||n.length>0||s.length>0?l(!0):i(!t)},value:!t}),a.jsx(I,{className:e.infoText,children:"Unlock approved rows to edit."}),a.jsx(mt,{acceptLabel:"Deselect",body:c,closeLabel:"Cancel",handleAccept:()=>{i(!t),l(!1)},handleClose:()=>l(!1),open:o,title:"Are you sure?"})]})};q$.propTypes={classes:A.object.isRequired};const HIe=Be(H$)(q$);var Jc={},sD;function qIe(){if(sD)return Jc;sD=1;var e=Pt();Object.defineProperty(Jc,"__esModule",{value:!0}),Jc.default=void 0;var t=e(Lt()),n=Ot();return Jc.default=(0,t.default)((0,n.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-6h2zm0-8h-2V7h2z"}),"Info"),Jc}var GIe=qIe();const G$=dt(GIe),YIe=(e,t)=>{const n=t.palette.divider;return{'&[x-placement*="bottom"] $arrow':{top:0,left:0,marginTop:"-0.95em",width:"3em",height:"1em","&::before":{borderWidth:"0 1em 1em 1em",borderColor:`transparent transparent ${e} transparent`},"&::after":{content:'""',position:"absolute",width:0,height:0,marginLeft:"-0.5em",top:"-6.5px",left:"6px",boxSizing:"border-box",border:"1em solid black",borderColor:`transparent transparent ${n}`,zIndex:-2,opacity:.4}},'&[x-placement*="top"] $arrow':{bottom:0,left:0,marginBottom:"-0.95em",width:"3em",height:"1em","&::before":{borderWidth:"1em 1em 0 1em",borderColor:`${e} transparent transparent transparent`},"&::after":{content:'""',position:"absolute",width:0,height:0,marginLeft:"-0.5em",top:"1px",left:"6px",boxSizing:"border-box",border:"1em solid black",borderColor:`transparent transparent ${n}`,transform:"rotate(180deg)",zIndex:-2,opacity:.4}},'&[x-placement*="right"] $arrow':{left:0,marginLeft:"-0.95em",height:"3em",width:"1em","&::before":{borderWidth:"1em 1em 1em 0",borderColor:`transparent ${e} transparent transparent`},"&::after":{content:'""',position:"absolute",width:0,height:0,marginLeft:"-0.5em",top:"0.25px",left:"-3.5px",boxSizing:"border-box",border:"1em solid black",borderColor:`transparent transparent ${n}`,transform:"rotate(-90deg)",zIndex:-2,opacity:.4}},'&[x-placement*="left"] $arrow':{right:0,marginRight:"-0.95em",height:"3em",width:"1em","&::before":{borderWidth:"1em 0 1em 1em",borderColor:`transparent transparent transparent ${e}`},"&::after":{content:'""',position:"absolute",width:0,height:0,marginLeft:"-0.5em",top:"1px",left:"6px",boxSizing:"border-box",border:"1em solid black",borderColor:`transparent transparent ${n}`,transform:"rotate(180deg)",zIndex:-2,opacity:.4}}}},KIe=e=>({arrowPopper:YIe(e.palette.action.hover,e),arrow:{position:"absolute",fontSize:6,width:"3em",height:"3em","&::before":{content:'""',margin:"auto",display:"block",width:0,height:0,borderStyle:"solid"}},lightTooltip:{backgroundColor:e.palette.action.hover,color:e.palette.text.secondary,boxShadow:e.shadows[2],fontSize:"12px",fontFamily:e.typography.fontFamily}});class fS extends Ne.Component{render(){const{classes:t,children:n,disabled:r,tooltip:s}=this.props;return r?n:a.jsx(be,{...this.props,disabled:!1,disableInteractive:!0,title:a.jsxs(a.Fragment,{children:[s,a.jsx("span",{className:t.arrow})]}),classes:{popper:t.arrowPopper,tooltip:t.lightTooltip},children:n})}}fS.propTypes={children:A.node.isRequired,classes:A.object.isRequired,disabled:A.bool,tooltip:A.object};fS.defaultProps={disabled:!1,tooltip:{}};const Y$=Be(KIe)(fS),QIe=()=>({root:{display:"flex"},searchTextField:{"& input":{fontSize:14,overflow:"visible"}
270,"& input::placeholder":{overflow:"visible"}},textField:{margin:0,width:"100%",height:"100%"}}),mS=({classes:e,placeholder:t})=>{const{palette:n}=Re(),{searchText:r,setSearchText:s}=m.useContext(gr),[i,o]=m.useState(!1);return a.jsxs("div",{className:e.root,"data-testid":"nc-search",children:[a.jsx(De,{autoComplete:"off",onChange:l=>s(l.target.value),placeholder:t,type:"search",value:r,InputProps:{classes:{root:e.textField},endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:n.text.disabled,size:20})})},variant:"standard"}),a.jsx(Bv,{onClickAway:()=>o(!1),children:a.jsx(Y$,{PopperProps:{disablePortal:!0},onClose:()=>o(!1),open:i,disableFocusListener:!0,disableHoverListener:!0,disableTouchListener:!0,placement:"right",tooltip:a.jsxs("ul",{style:{paddingLeft:20},children:[a.jsx("li",{style:{marginBottom:5},children:"Adding a hyphen in front of a token will exclude results containing the string (do not include spaces before or after the hyphen)."}),a.jsxs("li",{style:{marginBottom:5},children:["Column specific searches:",a.jsxs("ul",{style:{marginLeft:-25,marginTop:5},children:[a.jsx("li",{style:{marginBottom:5},children:"Adding a colon in between a column name and a string search will return results where the column contains the string."}),a.jsx("li",{style:{marginBottom:5},children:'Adding a "-" will negate that column Example "-category:digital" (do not include spaces before or after the hyphen).'})]})]}),a.jsx("li",{style:{marginBottom:5},children:'Each string entered in search is treated separately. Example: for "social digital" search will return results with both "social" AND "digital" in any of its columns.'}),a.jsx("li",{style:{marginBottom:5},children:'Search function searches values using substring matching. Example, the search token "ball" will match against records "baseball" and "football"'}),a.jsx("li",{style:{marginBottom:5},children:"Search strings are NOT case sensitive."})]}),children:a.jsx(He,{id:"nc-search-info-button",onClick:()=>o(!i),style:{marginLeft:6,marginTop:8},children:a.jsx(G$,{style:{color:n.text.secondary},"data-testid":"info-icon"})})})})]})};mS.propTypes={classes:A.object.isRequired,placeholder:A.string};mS.defaultProps={placeholder:""};const JIe=Be(QIe)(mS),XIe=()=>{const{countCurrentSelected:e,currentTableView:t,editLockIsActive:n,selectAllActivated:r,setExcludedRows:s,setSelectAllActivated:i,setSelectedRows:o}=m.useContext(gr);let l=r?"Deselect All":"Select All";e>0&&(l=`${l} (${e})`);const c=()=>{r?s([]):o([]),i(!r)},d=a.jsx(re,{variant:"text",onClick:c,sx:{p:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:l}),u=t.length===1&&t[0]===Yn.APPROVED.value&&n?{visibility:"hidden"}:{};return a.jsx("div",{style:{marginLeft:38,marginRight:24},"data-testid":"select-all",children:a.jsx("span",{style:u,children:d})})},K$=({counts:e})=>{const{count_approved:t,count_edited:n,count_unedited:r}=e;return a.jsxs("div",{style:{display:"flex",flexDirection:"row",marginTop:10,width:400},"data-testid":"tally-boxes",children:[a.jsx(Zo,{color:"common.white",count:r||0,label:"Unedited",tooltip:"Status indicates when a brand is unedited."}),a.jsx(Zo,{color:"background.disabled",count:n||0,label:"Edited",tooltip:"Status indicates when a brand is edited."}),a.jsx(Zo,{color:"success.main",count:t||0,label:"Approved",tooltip:"Status indicates when a brand is approved."})]})};K$.propTypes={counts:A.object.isRequired};const iD=[{label:Yn.VIEW_ALL.label,value:Yn.VIEW_ALL.value},{label:Yn.APPROVED.label,value:Yn.APPROVED.value},{label:Yn.EDITED.label,value:Yn.EDITED.value},{label:Yn.UNEDITED.label,value:Yn.UNEDITED.value}],ZIe=()=>{const{currentTableView:e,setExcludedRows:t,setSelectAllActivated:n,setSelectedRows:r,setTableView:s,tableView:i}=m.useContext(gr),o={};iD.forEach(({label:c,value:d})=>{o[d]=c});const l=c=>{const d={...i};if(c===Yn.VIEW_ALL.value){const u=!d[Yn.VIEW_ALL.value];Object.entries(d).forEach(([p])=>{d[p]=u})}else d[c]=!d[c],d[Yn.VIEW_ALL.value]=Object.keys(d).filter(u=>u!==Yn.VIEW_ALL.value).reduce((u,p)=>u&&d[p],!0);r([]),t([]),s(d),n(!1)};return a.jsxs(Qe,{id:"nc-brands-view-selector",style:{width:206},"data-testid":"view-selector",children:[a.jsx(wt,{shrink:!0,htmlFor:"nc-brands-select-multiple-chip",children:"Table View"}),a.jsx(tt,{displayEmpty:!0,input:a.jsx(Uv,{id:"nc-brands-select-multiple-chip"}),MenuProps:{PaperProps:{style:{marginTop:10,maxHeight:224,width:190}}},multiple:!0,renderValue:c=>a.jsxs("div",{children:[c.length===0?a.jsx(I,{variant:"body2",children:"Select Table View"}):null,c.length<3&&c.length>0?c.filter(d=>d!=="Select All").map(d=>a.jsx(ut,{"data-testid":"chip",label:o[d],style:{marginRight:5}},d)):null,c.length<3?null:a.jsx(ut,{"data-testid":"chip",label:"View all",style:{marginRight:5}},"View All")]}),SelectDisplayProps:{id:"nc-brands-view-selector-select"},value:e,children:iD.map(({label:c,value:d})=>a.jsx(Se,{sx:{pt:0,pb:0},"data-testid":d,children:a.jsxs(He,{onClick:()=>l(d),"data-testid":`view-option-${d}-checkbox`,children:[a.jsx(et,{checked:e.includes(d)}),a.jsx(Kt,{primary:c})]})},`view-option-${d}`))})]})},Q$=({classes:e,counts:t})=>a.jsxs("div",{className:e.controls,children:[a.jsxs("div",{className:e.controlBox,children:[a.jsxs("div",{className:e.viewSearch,children:[a.jsx(ZIe,{}),a.jsx(JIe,{classes:{root:e.search}})]}),a.jsx("div",{className:e.approveButton,children:a.jsx(BIe,{})})]}),a.jsx("div",{className:e.controlBox,children:a.jsx(K$,{counts:t})}),a.jsxs("div",{className:e.bottomControlBox,children:[a.jsxs("div",{className:e.leftBottom,children:[a.jsx(WIe,{}),a.jsx(XIe,{}),a.jsx(HIe,{})]}),a.jsx(UIe,{})]})]});Q$.propTypes={counts:A.object.isRequired,classes:A.object.isRequired};const eDe=Be(H$)(Q$),tDe=e=>({container:{display:"flex",flexDirection:"column",marginLeft:15},header:{fontWeight:"bold"},list:{fontSize:"14px",lineHeight:1.25,color:e.palette.text.primary,fontFamily:e.typography.fontFamily},table:{margin:"0 0 20px 0",padding:"3px 0 0 16px"}}),J$=({classes:e})=>a.jsxs("div",{className:e.container,children:[a.jsx(I,{className:e.header,style:{marginBottom:15},variant:"h4",children:"Brands"}),a.jsx(I,{className:e.header,variant:"body2",children:"Select rows to:"}),a.jsx("div",{children:a.jsxs("ul",{className:e.table,children:[a.jsxs("li",{className:e.list,children:[a.jsx("span",{children:"Perform "}),a.jsx("span",{style:{fontWeight:"bold"},children:"batch edits"}),a.jsx("span",{children:" on Brands."})]}),a.jsxs("li",{className:e.list,children:["Send marked ",a.jsx("strong",{children:"edited rows for approval."})]})]})})]});
270J$.propTypes={classes:A.object.isRequired};const nDe=Be(tDe)(J$);var Xc={},aD;function rDe(){if(aD)return Xc;aD=1;var e=Pt();Object.defineProperty(Xc,"__esModule",{value:!0}),Xc.default=void 0;var t=e(Lt()),n=Ot();return Xc.default=(0,t.default)((0,n.jsx)("path",{d:"M3 18h6v-2H3zM3 6v2h18V6zm0 7h12v-2H3z"}),"Sort"),Xc}var sDe=rDe();const fl=dt(sDe),iDe=()=>({menu:{border:"solid 1px",borderColor:"secondary.main",top:"10px !important"},buttonBase:{alignItems:"center",display:"flex",fontSize:14,fontWeight:"bold",lineHeight:1.14,justifyContent:"start",width:"100%"},label:{height:"auto",lineHeight:"normal",whiteSpace:"normal",wordBreak:"break-word",hyphens:"auto",wordWrap:"break-word",width:195},search:{width:190,marginLeft:10},text:{textAlign:"left"}}),aDe=(e=null,t=[])=>t.map(n=>({[e]:n})),oDe=(e=null,t=!1,n=null,r=[],s=[])=>{let i=[],o=[],l=[];switch(s.length>0&&(i=s.filter(c=>Object.keys(c)[0]===n),o=s.filter(c=>Object.keys(c)[0]!==n)),t){case!0:i.length+1!==r.length&&(l=[...i,{[n]:e}]);break;case!1:if(i.length>0){const c=i.findIndex(d=>d[n]===e);c!==-1&&(l=[...i.slice(0,c),...i.slice(c+1)])}else l=aDe(n,r.filter(c=>c!==e));break}return[...l,...o]},X$=({classes:e,columnData:t,header:n,width:r})=>{const{palette:s}=Re(),{engagementNiceId:i}=pe(),{clearFiltersLinkActive:o,columnFilters:l,currentPage:c,currentTableView:d,rowsPerPage:u,searchText:p,setClearFiltersLinkActive:h,setColumnFilters:f,sortColumn:g,sortDirection:x,visibleColumns:b}=m.useContext(gr),[y,v]=m.useState(null),[C,w]=m.useState(""),[S,E]=m.useState([]),[k,j]=m.useState(!0),_=m.useMemo(()=>({engagement_nice_id:i,column_name:t,column_filters:l,page_offset:c,page_size:u,search_text:p,sort_column:g,sort_direction:x,views:d,visible_columns:b.map(G=>G.data)}),[t,l,c,d,i,u,p,g,x]),{data:D=[],isFetching:M}=$a({apiName:"mediaResolution",endpoint:"GetMediaCreativeColumnFilterOptions",parameters:{body:_}},{skip:!y}),N=!!y,O=l.filter(G=>Object.keys(G)[0]===t),R=l.filter(G=>Object.keys(G)[0]!==t);m.useEffect(()=>{if(!D?.length)return;const G=[...D].map(K=>K).sort((K,ie)=>String(K).localeCompare(String(ie))),X=C?G.filter(K=>String(K).includes(C)):G;E(X)},[C,D]),m.useEffect(()=>{o||k||j(!0)},[o]);const L=(G,X)=>{switch(X){case!1:o||h(!o),k&&j(!k);break;case!0:O.length+1===D.length&&(j(!0),R.length===0&&o&&h(!o));break}f(oDe(G,X,t,D,l))},P=G=>{j(G),f(R.length>0?R:[]),(G&&R.length===0&&o||!o&&!G)&&h(!o)},F=D?.length||0,z=S.map(G=>a.jsx(Se,{style:{height:G?.length>35?"auto":24},children:a.jsx(sn,{className:e.label,control:a.jsx(et,{checked:O.findIndex(X=>X[t]===G)!==-1||k,onChange:({target:X})=>L(G,X.checked)}),label:G||"None"})},G)),B=a.jsx(Se,{children:a.jsx(sn,{control:a.jsx(et,{checked:k,onChange:({target:G})=>P(G.checked)}),label:"Select All"})},`select-all-option-${t}`),W=a.jsx(Se,{children:a.jsx(I,{variant:"body1",children:"No Options"})},"select-all-option"),H=a.jsx(De,{InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:s.text.disabled,size:20})})},autoComplete:"off",className:e.search,id:"standard-search",margin:"none",onChange:G=>w(G.target.value),placeholder:"Search values",type:"search"}),V=a.jsx(He,{"aria-controls":"column-picker","aria-haspopup":"true",className:e.buttonBase,id:`nc-${n}-column-selector-button`,onClick:({currentTarget:G})=>v(G),children:a.jsx(fl,{})});return a.jsxs("div",{style:{width:r},"data-testid":"column-filter",children:[V,a.jsxs(dr,{MenuListProps:{id:`nc-column-filter-${n}`,sx:{border:"1px solid",borderColor:"secondary.main"}},PaperProps:{style:{maxHeight:224,width:220}},anchorEl:y,anchorOrigin:{vertical:"bottom",horizontal:"left"},className:e.menu,disableAutoFocusItem:!0,id:"column-picker",onClose:()=>v(null),open:N,transformOrigin:{vertical:"top",horizontal:"left"},children:[M?a.jsx("div",{style:{marginTop:5,textAlign:"center",width:"100%"},children:a.jsx(Ze,{size:24})}):null,F>1&&!M?B:null,F>5&&!M?H:null,F>0&&!M?z:null,F===0&&!M?W:null]})]})};X$.propTypes={classes:A.object.isRequired,columnData:A.string.isRequired,header:A.string.isRequired,width:A.number.isRequired};const lDe=Be(iDe)(X$),cDe={cellContainer:{display:"flex",flexDirection:"row",alignItems:"center"},sortIcon:{marginLeft:5},headerCell:{paddingLeft:0}},{ASC:dDe,DESC:kb}=U$,gS=({classes:e,canSort:t,canFilter:n,columnName:r,header:s,width:i})=>{const{sortDirection:o,setSortDirection:l}=m.useContext(gr),c=o===kb?a.jsx(sC,{"data-testid":"sort-icon-za",size:20}):a.jsx(iC,{"data-testid":"sort-icon-az",size:20});
270return a.jsx($e,{className:e.headerCell,id:`nc-brand-header-cell-${r}`,"data-testid":"table-cell",style:{minWidth:i,maxWidth:i},children:a.jsxs("div",{className:e.cellContainer,children:[s,t&&a.jsx(He,{className:e.sortIcon,"data-testid":"sort-button",id:`nc-brand-sort-${r}`,onClick:()=>l(o===kb?dDe:kb),children:c}),n&&a.jsx(lDe,{"data-testid":"filter-button",id:`nc-brand-filter-${r}`,columnData:r,header:s,width:i})]})})};gS.propTypes={classes:A.object.isRequired,canFilter:A.bool,canSort:A.bool,columnName:A.string.isRequired,header:A.string.isRequired,width:A.number};gS.defaultProps={canFilter:!1,canSort:!1,width:60};const uDe=Be(cDe)(gS),pDe=e=>({headerRow:{borderTop:`1px solid ${e.palette.divider}`}}),Z$=({classes:e})=>{const{visibleColumns:t}=m.useContext(gr),n=t.map(({data:r,filterable:s,header:i,sortable:o,width:l})=>a.jsx(uDe,{canFilter:s,canSort:o,columnName:r||"",header:i||"",width:l},i));return a.jsxs(bn,{className:e.headerRow,title:"","data-test":"brands-header-row",children:[a.jsx($e,{style:{minWidth:30,maxWidth:30}}),n]})};Z$.propTypes={classes:A.object.isRequired};const hDe=Be(pDe)(Z$),fDe=()=>({root:{padding:0,paddingLeft:6,textAlign:"center",width:30,borderBottom:"none"},checkbox:{padding:0,marginBottom:-10}}),xS=({classes:e,disabled:t,id:n})=>{const{editLockIsActive:r,excludedRows:s,selectAllActivated:i,selectedRows:o,setExcludedRows:l,setSelectedRows:c}=m.useContext(gr),d=i?!s?.includes(n):o?.includes(n),u=!t||!r,p=x=>{const b=s.filter(y=>n!==y);x||b.push(n),l(b)},h=x=>{const b=o.filter(y=>n!==y);x&&b.push(n),c(b)},f=x=>{const b=x.target.checked;i?p(b):h(b)},g=u&&a.jsx(be,{title:"Select to perform batch edits or approve brands.",placement:"right",arrow:!0,children:a.jsx(et,{className:e.checkbox,checked:d,onClick:f,classes:{root:e.buttonBase}})});return a.jsx($e,{className:e.root,"data-test":"check-box-cell",children:g})};xS.defaultProps={disabled:!1};xS.propTypes={classes:A.object.isRequired,disabled:A.bool,id:A.number.isRequired};const mDe=Be(fDe)(xS),bS=e=>({approved:{borderLeft:`5px solid ${e.palette.success.main}`},cellBorder:{borderBottom:`1px solid ${e.palette.border?.default||e.palette.divider}`},dropDown:{lineHeight:"normal",whiteSpace:"normal",wordBreak:"break-word",hyphens:"auto",height:"auto"},edited:{borderLeft:`5px solid ${e.palette.neutral?.[500]||e.palette.grey[500]}`},even:{backgroundColor:e.palette.background?.neutral?.default||e.palette.action?.hover},odd:{backgroundColor:e.palette.background?.paper||"transparent"},selectCellRoot:{padding:0,textAlign:"center",margin:0,borderBottom:"none"},selectWidth:{width:130},standardText:{fontSize:13,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},superSelect:{margin:0},textCell:{fontSize:14,maxHeight:80,lineHeight:"normal",padding:0},unedited:{borderLeft:"5px solid transparent"}}),yS=({disabled:e,label:t,onChange:n,placeholder:r,preMadeMenuItems:s,value:i,width:o})=>{const l=`${t}-brand-select`;return a.jsx("div",{style:{display:"flex",flexDirection:"row",position:"relative",marginBottom:-5},children:a.jsx(Qe,{style:{marginTop:5,marginLeft:5,width:o},children:a.jsx(tt,{id:l,disabled:e,SelectDisplayProps:{id:l},sx:{color:"text.primary",textAlign:"left"},value:i||r,renderValue:i?null:c=>c,onChange:c=>n(c),inputProps:{name:`${t}-input`,id:`${t}-input`},MenuProps:{disableAutoFocusItem:!0,id:`${l}-menu`,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},marginThreshold:0,MenuListProps:{id:`${l}-menu-list`},PaperProps:{id:{id:`${l}-paper`},style:{marginTop:10,maxHeight:224,width:o}}},children:s})})})};yS.defaultProps={disabled:!1,value:null,label:"",onChange:()=>{},preMadeMenuItems:null,width:300,placeholder:"Select"};yS.propTypes={disabled:A.bool,label:A.oneOfType([A.string,A.number]),onChange:A.func,placeholder:A.string,preMadeMenuItems:A.array,value:A.oneOfType([A.string,A.number]),width:A.number};const vS=({brandSelected:e,classes:t,disabled:n,rowId:r,width:s})=>{const{engagementId:i,engagementNiceId:o}=pe(),{data:l=[]}=Qs(i),[c]=Qi(),{columnFilters:d,countCurrentSelected:u,currentTableView:p,editLockIsActive:h,excludedRows:f,searchText:g,selectAllActivated:x,selectedRows:b,setTaskId:y,visibleColumns:v}=m.useContext(gr),[C,w]=m.useState(!1),[S,E]=m.useState(null),k=n&&h,j=l?.find(O=>O.brand_nice_id===e)?.id||null,_=[{value:-1,label:"None"},...l.map(O=>({...O,value:O.id,label:O.brand_name}))],D=p.filter(O=>h&&O!=="view_all"&&O!=="approved"||!h),M=O=>{const R=l?.find(F=>F.id===O.target.value)?.brand_nice_id||null;let L={engagement_nice_id:o,lambdaName:"UpdateMediaCreatives",data:{approved:!1,brand:R}},P=!1;x?(P=!0,L={...L,column_filters:d,excluded_media_creative_ids:f,search_text:g,views:D,visible_columns:v}):b.length===0||!b.includes(r)?L.media_creative_ids=[r]:(P=b.length,L.media_creative_ids=b),P?(E(L),w(!0)):c({apiName:"mediaResolution",endpoint:"TriggerAsyncLambda",parameters:{body:L,pathParameters:{niceId:o}}}).unwrap().then(({task_id:F})=>{y(F||null)})},N=a.jsx(yS,{disabled:k,id:"brand-select",label:r||"",onChange:M,placeholder:j?"":"None",preMadeMenuItems:_.map(O=>a.jsx(Se,{id:`brand-select-item-${O.value}`,value:O.value||"",className:t.dropDown,children:O.label},`item-${O.value}`)),menuItems:_,menuItemLabelKey:"name",width:s,value:j||""});return a.jsxs($e,{style:{minWidth:s}
270,className:t.selectCellRoot,"data-testid":"selector-cell",children:[N,a.jsx(mt,{acceptLabel:"Batch Edit",bodyText:`You are about to edit ${u} rows.`,handleAccept:()=>{c({apiName:"mediaResolution",endpoint:"TriggerAsyncLambda",parameters:{body:S,pathParameters:{niceId:o}}}).unwrap().then(({task_id:O})=>{y(O||null)}).finally(()=>{w(!1),E(null)})},handleClose:()=>{w(!1),E(null)},open:C,title:"Are you sure?"})]})};vS.defaultProps={brandSelected:"",disabled:!1,width:130};vS.propTypes={brandSelected:A.string,classes:A.object.isRequired,disabled:A.bool,rowId:A.number.isRequired,width:A.number};const gDe=Be(bS)(vS),CS=({classes:e,cellWidthScalingFactor:t,dottedBorder:n,paddingLeft:r,textStyle:s,value:i,width:o})=>a.jsx($e,{classes:{root:e.cellBorder},className:e.textCell,"data-testid":"text-cell",sx:{maxWidth:o*t,borderBottom:l=>n?`1px dashed ${l.palette.divider}`:"none",paddingLeft:r},children:a.jsx(I,{style:s,"data-testid":"text-cell-typography",title:i||"",children:i||""})});CS.propTypes={classes:A.object.isRequired,cellWidthScalingFactor:A.number,dottedBorder:A.bool,paddingLeft:A.number,textStyle:A.object,value:A.string,width:A.number};CS.defaultProps={cellWidthScalingFactor:1,dottedBorder:!1,paddingLeft:0,textStyle:{fontSize:14,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},value:"",width:50};const Zp=Be(bS)(CS),xDe=30,wS=({classes:e,rowData:t,even:n})=>{const{visibleColumns:r}=m.useContext(gr),{status:s="unedited"}=t;let i=e[s];i=`${i} ${n?e.even:e.odd}`;const o=`${i} ${e.cellBorder}`,l=r.map(({data:d,width:u})=>{const p=t[d]?t[d].toString():"";return d==="brand"?a.jsx(gDe,{disabled:t.approved,brandSelected:p,rowId:t.id},d):d==="placement_id"||d==="placement_name"?a.jsx(Zp,{value:p||"",textStyle:{fontWeight:"bold",whiteSpace:"nowrap"},dottedBorder:!0,width:u},d):a.jsx(Zp,{value:"",width:u,dottedBorder:!0},d)}),c=r.map(({data:d,width:u})=>{let p=t[d]?t[d].toString():"";return(d==="brand"||d==="placement_id"||d==="placement_name")&&(p=""),a.jsx(Zp,{paddingLeft:5,value:p,width:u},d)});return a.jsxs(a.Fragment,{children:[a.jsxs(bn,{className:i,"data-testid":"brands-top-half-row",children:[a.jsx(mDe,{id:t.id,disabled:t.approved}),l]}),a.jsxs(bn,{className:o,"data-testid":"brands-bottom-half-row",children:[a.jsx(Zp,{value:"",width:xDe}),c]})]})};wS.propTypes={classes:A.object.isRequired,rowData:A.object,even:A.bool};wS.defaultProps={rowData:{},even:!1};const bDe=Be(bS)(wS),yDe=()=>({container:{display:"flex",flexDirection:"column",margin:"30px 15px 0px 15px",paddingBottom:30,overflowX:"hidden"},table:{overflow:"hidden"},tableWrapper:{overflow:"scroll",width:"100%"}}),oD=[5,10,25,50,100],ez=({classes:e,count:t,mediaCreative:n})=>{const{currentPage:r,loading:s,numberOfPages:i,rowsPerPage:o,setCurrentPage:l,setRowsPerPage:c}=m.useContext(gr),d=oD.length>0?oD[0]:1,u=n.map((p,h)=>a.jsx(bDe,{rowData:p,even:h%2!==0},h));return a.jsxs("div",{className:e.container,children:[a.jsx("div",{className:e.tableWrapper,children:a.jsxs(Ki,{className:e.table,"data-test":"brands-table",children:[a.jsx(Ya,{children:a.jsx(hDe,{})}),a.jsx(xl,{id:"brands-table-body",children:s?null:u})]})}),s&&a.jsx("div",{style:{marginTop:40,textAlign:"center",width:"100%"},children:a.jsx(Ze,{size:24})}),s||t<d?null:a.jsx(Qw,{attributeName:"brand",controlPageSizeBool:!0,currentPage:r,onChangePageSize:p=>{l(0),c(p)},onGoForward:()=>{r<i-1&&l(r+1)},onGoBackward:()=>{r>0&&l(r-1)},pageSize:o,total:t})]})};ez.propTypes={classes:A.object.isRequired,count:A.number.isRequired,mediaCreative:A.array.isRequired};const vDe=Be(yDe)(ez),CDe=rn.BRAND,wDe=()=>{const{engagementId:e,engagementNiceId:t}=pe(),{columnFilters:n,currentPage:r,currentTableView:s,editLockIsActive:i,excludedRows:o,rowsPerPage:l,searchText:c,setTaskId:d,taskId:u,selectAllActivated:p,selectedRows:h,setCountCurrentSelected:f,setCurrentPage:g,setLoading:x,setNumberOfPages:b,sortColumn:y,sortDirection:v,tableView:C,visibleColumns:w}=m.useContext(gr),S=m.useMemo(()=>({engagement_nice_id:t,column_filters:n,page_offset:r,page_size:l,search_text:c,sort_column:y,sort_direction:v,views:s,visible_columns:w.map(F=>F.data)}),[n,r,s,t,l,c,y,v]),{count:E,placements:k,placementsFetching:j,refetch:_,rest:D}=pS({body:S,engagementNiceId:t,tableName:CDe}),{data:M={},refetch:N}=$a({apiName:"mediaResolution",endpoint:"GetMediaCreativeCounts",parameters:{body:S}}),{current_page:O,number_of_pages:R}=D||{},L=m.useCallback(()=>{d(null),_(),N()},[]),{percentComplete:P}=jm({eventType:"NameCleaning",onComplete:L,taskId:u});return Qs(e),m.useEffect(()=>x(j),[j,x]),m.useEffect(()=>{O&&(g(O),b(R))},[O,R,g,b]),m.useEffect(()=>{let F=0;p?(F=E-(o?.length||0),i&&C[Yn.APPROVED.value]&&(F-=M?.count_approved||0)):
270F+=h?.length||0,f(F)},[M,o,p,h]),a.jsxs("div",{style:{display:"flex",flexDirection:"column",marginTop:30,overflowX:"hidden"},children:[a.jsx(C$,{show:!!u,message:"Please wait while brands are being processed.",percentComplete:P}),a.jsx(nDe,{style:{container:{marginBottom:5}}}),a.jsx(eDe,{counts:M||{}}),a.jsx(vDe,{count:E,mediaCreative:k})]})},SDe=()=>a.jsx(hS,{children:a.jsx(wDe,{})}),Dd=(e,t)=>!t&&dS.some(r=>!e?.[r])?cS:LIe,tz=(e=[],t="")=>e.find(r=>r.row_access===t)?.name||t,nz=({hasColumnFilter:e,onClick:t})=>a.jsx(re,{variant:"text",sx:{display:e?"inherit":"none",p:0,mb:5,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},onClick:t,children:"Clear all column filters"});nz.propTypes={hasColumnFilter:A.bool.isRequired,onClick:A.func.isRequired};const jDe=e=>({menu:{border:"solid 1px",borderColor:e.palette.secondary.main,top:"10px !important"},menuItem:{textAlign:"left",width:160},addColumnIconFill:{fill:e.palette.secondary.main},addColumnIconPlus:{stroke:e.palette.secondary.main}}),rz=({classes:e,columnDefinitions:t,columnVisibility:n,onChangeColumnVisibility:r})=>{const[s,i]=m.useState(null),{palette:o}=Re(),l=!!s,c=t.filter(({alwaysOn:d})=>!d).map(({data:d,header:u})=>a.jsx(Se,{disableGutters:!0,sx:{p:0},children:a.jsxs(He,{onClick:()=>r(d,!n[d]),children:[a.jsx(et,{checked:n[d]}),a.jsx(I,{className:e.menuItem,children:u})]})},d));return a.jsxs(a.Fragment,{children:[a.jsx(be,{title:"Add/remove columns from table. To add/edit attributes, add attribute columns to the table view.",placement:"right",arrow:!0,children:a.jsx(He,{"aria-controls":"column-picker","aria-haspopup":"true",onClick:d=>i(d.currentTarget),children:a.jsx(po,{color:o.secondary.main})})}),a.jsx(dr,{anchorEl:s,className:e.menu,id:"column-picker",open:l,onClose:()=>i(null),anchorOrigin:{vertical:"bottom",horizontal:"left"},MenuListProps:{dense:!0},children:c})]})};rz.propTypes={classes:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,onChangeColumnVisibility:A.func.isRequired};const kDe=Be(jDe)(rz),EDe=()=>({root:{height:40,width:100,padding:"4px 12px !important"}}),SS=({classes:e,disabled:t,id:n,onClick:r,width:s})=>a.jsx(re,{classes:{root:e.root},color:"primary",disabled:t,id:n,onClick:r,variant:"contained",style:{width:s},children:"Create"});SS.defaultProps={width:null};SS.propTypes={classes:A.object.isRequired,disabled:A.bool.isRequired,id:A.string.isRequired,onClick:A.func.isRequired,width:A.number};const _De=Be(EDe)(SS),TDe=()=>({searchTextField:{"& input":{fontSize:14,overflow:"visible"}
270,"& input::placeholder":{overflow:"visible"}}}),jS=({classes:e,onSearch:t,placeholder:n,value:r,width:s})=>{const{palette:i}=Re(),[o,l]=m.useState(!1);return a.jsxs("div",{children:[a.jsx(De,{autoComplete:"off",className:e.searchTextField,id:"standard-search",label:"",onChange:c=>t(c.target.value),placeholder:n,style:{margin:0,width:s},type:"search",value:r,InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:i.text.disabled,size:20})})},variant:"standard"}),a.jsx(Bv,{onClickAway:()=>l(!1),children:a.jsx(Y$,{PopperProps:{disablePortal:!0},onClose:()=>l(!1),open:o,disableFocusListener:!0,disableHoverListener:!0,disableTouchListener:!0,placement:"right",tooltip:a.jsxs("ul",{style:{paddingLeft:20},children:[a.jsx("li",{style:{marginBottom:5},children:"Adding a hyphen in front of a token will exclude results containing the string (do not include spaces before or after the hyphen)."}),a.jsxs("li",{style:{marginBottom:5},children:["Column specific searches:",a.jsxs("ul",{style:{marginLeft:-25,marginTop:5},children:[a.jsx("li",{style:{marginBottom:5},children:"Adding a colon in between a column name and a string search will return results where the column contains the string."}),a.jsx("li",{style:{marginBottom:5},children:'Adding a "-" will negate that column Example "-category:digital" (do not include spaces before or after the hyphen).'})]})]}),a.jsx("li",{style:{marginBottom:5},children:'Each string entered in search is treated separately. Example: for "social digital" search will return results with both "social" AND "digital" in any of its columns.'}),a.jsx("li",{style:{marginBottom:5},children:'Search function searches values using substring matching. Example, the search token "ball" will match against records "baseball" and "football"'}),a.jsx("li",{style:{marginBottom:5},children:"Search strings are NOT case sensitive."})]}),children:a.jsx(He,{id:"nc-search-info-button",onClick:()=>l(!o),style:{marginLeft:10,marginTop:3},children:a.jsx(G$,{style:{color:i.text.secondary}})})})})]})};jS.defaultProps={placeholder:"Incoming or mapped name",value:null,width:212};jS.propTypes={classes:A.object.isRequired,onSearch:A.func.isRequired,placeholder:A.string,value:A.string,width:A.number};const IDe=Be(TDe)(jS),kS=({canSelectAll:e,deselectedRows:t,onSelectAllRows:n,selectedRows:r,totalNumberOfPlacements:s})=>{const i=e?s-t.length:Object.keys(r).length,o=e&&!t.length,l=a.jsxs(re,{variant:"text",onClick:n,sx:{display:"flex",height:30,justifyContent:"flex-start",mr:20,minWidth:110,pl:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:[o?"Deselect All":"Select All",i>0&&` (${i})`]});return a.jsx("div",{children:l})};kS.defaultProps={totalNumberOfPlacements:0};kS.propTypes={canSelectAll:A.bool.isRequired,deselectedRows:A.array.isRequired,onSelectAllRows:A.func.isRequired,selectedRows:A.object.isRequired,totalNumberOfPlacements:A.number};const DDe=e=>({actionButton:{marginLeft:40},container:{display:"flex",flexDirection:"column",marginBottom:10},controlBox:{display:"flex",flexDirection:"row",alignItems:"flex-end",justifyContent:"space-between"},filterSearchBox:{width:490},buttonBox:{display:"flex",flexDirection:"row",alignItems:"flex-end",justifyContent:"space-between"},header:{fontWeight:"bold"},list:{fontSize:"14px",lineHeight:1.25,color:e.palette.text.primary,fontFamily:e.typography.fontFamily},table:{margin:"0 0 30px 0",padding:"3px 0 0 16px"},createButton:{width:117}}),ES=({canSelectAll:e,classes:t,clearColumnFilters:n,createPlacementButtonEnabled:r,columnDefinitions:s,columnVisibility:i,deselectedRows:o,hasColumnFilter:l,onChangeColumnVisibility:c,onCreatePlacement:d,onSelectAllRows:u,onUpdateSearchText:p,searchText:h,selectedRows:f,totalNumberOfPlacements:g})=>{const x=`${t.controlBox} ${t.filterSearchBox}`;return a.jsxs("div",{className:t.container,children:[a.jsxs("div",{className:t.controlBox,children:[a.jsx("div",{className:x,children:a.jsx(IDe,{placeholder:"Search",width:240,onSearch:p,value:h})}),a.jsx("div",{className:t.buttonBox,children:a.jsx("div",{className:t.actionButton,children:a.jsx(_De,{id:"nc-create-placement",disabled:!r,onClick:d,width:117})})})]}),a.jsxs("div",{className:t.controlBox,children:[a.jsxs("div",{style:{marginTop:15,display:"flex",flexDirection:"row"},children:[a.jsx(kS,{canSelectAll:e,deselectedRows:o,onSelectAllRows:u,selectedRows:f,totalNumberOfPlacements:g}),a.jsx(kDe,{columnDefinitions:s,columnVisibility:i,onChangeColumnVisibility:c}
270)]}),a.jsx(nz,{onClick:n,hasColumnFilter:l})]})]})};ES.propTypes={canSelectAll:A.bool.isRequired,classes:A.object.isRequired,clearColumnFilters:A.func.isRequired,createPlacementButtonEnabled:A.bool,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,deselectedRows:A.array.isRequired,hasColumnFilter:A.bool.isRequired,onChangeColumnVisibility:A.func.isRequired,onCreatePlacement:A.func.isRequired,onSelectAllRows:A.func.isRequired,onUpdateSearchText:A.func.isRequired,searchText:A.string,selectedRows:A.object.isRequired,totalNumberOfPlacements:A.number};ES.defaultProps={createPlacementButtonEnabled:!1,searchText:"",totalNumberOfPlacements:0};const ADe=Be(DDe)(ES),sz=e=>({menu:{border:"solid 1px",borderColor:e.palette.secondary.main,top:"10px !important"},addColumnIconFill:{fill:e.palette.secondary.main},addColumnIconPlus:{stroke:e.palette.secondary.main},buttonBase:{alignItems:"center",display:"flex",fontSize:14,fontWeight:"bold",lineHeight:1.14,justifyContent:"start",width:"100%"},label:{whiteSpace:"normal",wordBreak:"break-word",hyphens:"auto",wordWrap:"break-word",width:195},search:{width:190,marginLeft:10},text:{textAlign:"left"}}),MDe=e=>{const t=e.sort(([r],[s])=>r.localeCompare(s)),n=t.findIndex(([r])=>r==="null");return n>0?[t[n],...t.slice(0,n),...t.slice(n+1)]:t};let iz=class extends Ne.Component{constructor(t){super(t),this.state={anchorEl:null,searchText:null},this.closeMenu=this.closeMenu.bind(this),this.openMenu=this.openMenu.bind(this)}closeMenu(){this.setState({anchorEl:null,searchText:null})}openMenu(t){const{columnFilters:n,columnName:r,getOptions:s,setColumnFilters:i}=this.props,o={...n};this.setState({anchorEl:t.currentTarget,loading:!0}),s(r).then(l=>{o[r]=n[r]?{...n[r]}:{},l.forEach(c=>{c in o[r]||(o[r][c]=!0)}),i(o),this.setState({loading:!1})})}render(){const{children:t,classes:n,columnFilters:r,columnName:s,header:i,onCheckFilter:o,onCheckSelectAll:l,theme:c,width:d}=this.props,{anchorEl:u,loading:p,searchText:h}=this.state,f=r[s]?Object.entries(r[s]):[],g=f.length,x=!!u,b=f.every(([,k])=>k),y=MDe(f).filter(([k])=>h?k.toLocaleLowerCase().includes(h.toLocaleLowerCase()):!0).map(([k,j],_)=>a.jsx(Se,{sx:{pt:0,pb:0},children:a.jsx(sn,{className:n.label,control:a.jsx(et,{checked:b||j,onChange:({target:D})=>{o(s,k,D.checked)}}),label:k==="null"?"None":k})},`item-${k||_}-option`)),v=a.jsx(Se,{sx:{pt:0,pb:0},children:a.jsx(sn,{control:a.jsx(et,{checked:b,onChange:({target:k})=>l(k.checked)}),label:"Select All"})},"item-select-all-option"),C=a.jsx(De,{InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:c.palette.text.disabled,size:20})})},autoComplete:"off",className:n.search,id:"standard-search",margin:"none",onChange:({target:k})=>this.setState({searchText:k?.value}),placeholder:"Search values",type:"search"},"item-search-option"),w=i==="category_name"?a.jsx(be,{placement:"top",title:"Filter by categories in order to see relevance in subsequent filters.",arrow:!0,children:a.jsxs(He,{"aria-controls":"column-picker","aria-haspopup":"true",className:n.buttonBase,onClick:this.openMenu,children:[a.jsx("div",{className:n.text,children:t}),a.jsx(fl,{})]})}):a.jsxs(He,{"aria-controls":"column-picker","aria-haspopup":"true",className:n.buttonBase,id:`nc-${i}-column-selector-button`,onClick:this.openMenu,children:[a.jsx("div",{className:n.text,children:t}),a.jsx(fl,{})]}),S=a.jsx("div",{style:{justifyContent:"center",display:"flex"},children:a.jsx(Ze,{})}),E=[];return g>1&&E.push(v),g>5&&E.push(C),g>0&&E.push(y),a.jsxs("div",{style:{width:d},children:[w,a.jsx(dr,{MenuListProps:{id:`nc-column-filter-${i}`,sx:{border:"1px solid",borderColor:"secondary.main"}},PaperProps:{style:{maxHeight:224,width:220}},anchorEl:u,anchorOrigin:{vertical:"bottom",horizontal:"left"},className:n.menu,disableAutoFocusItem:!0,id:"column-picker",onClose:this.closeMenu,open:x,transformOrigin:{vertical:"top",horizontal:"left"},children:p?S:E})]})}};iz.propTypes={children:A.node.isRequired,classes:A.object.isRequired,columnFilters:A.object.isRequired,columnName:A.string.isRequired,getOptions:A.func.isRequired,header:A.string.isRequired,theme:A.object.isRequired,width:A.number.isRequired,onCheckFilter:A.func.isRequired,onCheckSelectAll:A.func.isRequired,setColumnFilters:A.func.isRequired};const RDe=Be(sz,{withTheme:!0})(iz),NDe=e=>Object.entries(e).sort((t,n)=>t[1].label==="None"?-1:n[1].label==="None"?1:t[1].label.localeCompare(n[1].label));class _S extends Ne.Component{constructor(t){super(t),this.state={anchorEl:null,searchText:null},this.closeMenu=this.closeMenu.bind(this),this.openMenu=this.openMenu.bind(this)}closeMenu(){this.setState({anchorEl:null,searchText:null})}openMenu(t){this.setState({anchorEl:t.currentTarget})}render(){const{children:t,classes:n,options:r,header:s,onCheckFilter:i,onCheckSelectAll:o,theme:l,width:c}
270=this.props,d=Object.keys(r).length,{anchorEl:u,searchText:p}=this.state,h=!!u,f=NDe(r).filter(([,{label:C}])=>p?C.toLocaleLowerCase().includes(p.toLocaleLowerCase()):!0).map(([C,{label:w,checked:S}])=>a.jsx(Se,{style:{height:s?.length>35?"inherit":24},children:a.jsx(sn,{className:n.label,control:a.jsx(et,{checked:S,onChange:({target:E})=>i(C,E.checked)}),label:w})},C)),g=Object.values(r).every(({checked:C})=>C),x=a.jsx(Se,{children:a.jsx(sn,{control:a.jsx(et,{checked:g,onChange:({target:C})=>o(C.checked)}),label:"Select All"})},"select-all-option"),b=a.jsx(Se,{children:a.jsx(I,{variant:"body1",children:"No Options"})},"select-all-option"),y=a.jsx(De,{InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:l.palette.text.disabled,size:20})})},autoComplete:"off",className:n.search,id:"standard-search",margin:"none",onChange:({target:C})=>this.setState({searchText:C?.value}),placeholder:"Search values",type:"search"}),v=s==="category_name"?a.jsx(be,{placement:"top",title:"Filter by categories in order to see relevance in subsequent filters.",arrow:!0,children:a.jsxs(He,{"aria-controls":"column-picker","aria-haspopup":"true",className:n.buttonBase,onClick:this.openMenu,children:[a.jsx("div",{className:n.text,children:t}),a.jsx(fl,{})]})}):a.jsxs(He,{"aria-controls":"column-picker","aria-haspopup":"true",className:n.buttonBase,id:`nc-${s}-column-selector-button`,onClick:this.openMenu,children:[a.jsx("div",{className:n.text,children:t}),a.jsx(fl,{})]});return a.jsxs("div",{style:{width:c},children:[v,a.jsxs(dr,{MenuListProps:{id:`nc-column-filter-${s}`,sx:{border:"1px solid",borderColor:"secondary.main"}},PaperProps:{style:{maxHeight:224,width:220}},anchorEl:u,anchorOrigin:{vertical:"bottom",horizontal:"left"},className:n.menu,disableAutoFocusItem:!0,id:"column-picker",onClose:this.closeMenu,open:h,transformOrigin:{vertical:"top",horizontal:"left"},children:[d>1?x:null,d>5?y:null,d>0?f:b]})]})}}_S.defaultProps={options:{}};_S.propTypes={children:A.node.isRequired,classes:A.object.isRequired,options:A.object,header:A.oneOfType([A.object,A.string]).isRequired,theme:A.object.isRequired,width:A.number.isRequired,onCheckFilter:A.func.isRequired,onCheckSelectAll:A.func.isRequired};const ODe=Be(sz,{withTheme:!0})(_S),PDe=()=>({show:{display:"block"},buttonBase:{alignItems:"center",display:"flex",fontSize:14,fontWeight:"bold",lineHeight:1.14,justifyContent:"start",width:"100%"},hide:{display:"none"},root:{width:"100%"},text:{paddingRight:5,textAlign:"left"}}),lD="NONE",eh="ASC",Eb="DESC",az=({children:e,classes:t,header:n,onClick:r})=>{const[s,i]=m.useState(!1),[o,l]=m.useState(eh),c=o!==lD||s?t.show:t.hide,d=o===Eb?a.jsx(sC,{className:c,size:20}):a.jsx(iC,{className:c,size:20});return a.jsx("div",{className:t.root,children:a.jsxs(He,{className:t.buttonBase,id:`nc-${n}-sort-button`,onClick:()=>{let u;o===lD&&(u=eh),o===eh&&(u=Eb),o===Eb&&(u=eh),l(u),r(u)},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[a.jsx("div",{className:t.text,children:e}),d]})})};az.propTypes={children:A.node.isRequired,classes:A.object.isRequired,header:A.string.isRequired,onClick:A.func.isRequired};const LDe=Be(PDe)(az),FDe=e=>({row:{borderTop:`1px solid ${e.palette.divider}`},filterCell:{width:"100%",display:"flex",flexDirection:"row"}}),oz=({cellWidthScalingFactor:e,classes:t,columnFilters:n,columnDefinitions:r,columnVisibility:s,getColumnFilterOptions:i,onChangeSortDirection:o,onSelectAllColumnFilters:l,onUpdateColumnFilter:c,setColumnFilters:d,tableName:u,title:p})=>{const h=r.filter(({data:f})=>s[f]).map(({data:f,header:g,width:x})=>a.jsx($e,{style:{padding:0,maxWidth:`${x*e} !important`,width:x*e},variant:"head",children:u===rn.PLACEMENT?a.jsx(RDe,{columnFilters:n,columnName:f,getOptions:i,header:g,onCheckFilter:c,onCheckSelectAll:b=>l(f,b),setColumnFilters:d,width:x*e,children:g}):a.jsx(ODe,{header:g,onCheckFilter:c,onCheckSelectAll:b=>l(f,b),options:n?n[f]:{},width:x*e,children:g})},f));return a.jsxs(bn,{className:t.row,children:[a.jsx($e,{className:t.cell,style:{width:Hn.PLACEMENT.FIRST_COLUMN}}),a.jsx($e,{className:t.cell,style:{padding:0,width:Hn.PLACEMENT.SECOND_COLUMN},children:a.jsx("div",{style:{width:"100%",overflow:"visible"},children:a.jsx(LDe,{header:"Placement",onClick:o,children:p})})}),h]})};oz.propTypes={cellWidthScalingFactor:A.number.isRequired,classes:A.object.isRequired,columnFilters:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,getColumnFilterOptions:A.func.isRequired,onChangeSortDirection:A.func.isRequired,onSelectAllColumnFilters:A.func.isRequired,onUpdateColumnFilter:A.func.isRequired,setColumnFilters:A.func.isRequired,tableName:A.string.isRequired,title:A.string.isRequired};const $De=Be(FDe)(oz),zDe=e=>({container:{display:"flex",flexDirection:"column",marginTop:-1,marginBottom:20},header:{fontWeight:"bold"},listItem:{fontSize:"14px",lineHeight:1.25,color:e.palette.text.primary,fontFamily:e.typography.fontFamily},list:{margin:0,marginBottom:10,padding:"3px 0 0 16px"}}),lz=({classes:e,title:t})=>a.jsxs("div",{className:e.container,children:[a.jsxs(I,{className:e.header,style:{marginBottom:15},variant:"h4",children:[t,"s"]}),a.jsx(I,{className:e.header,variant:"body2",children:"Select rows to:"}),a.jsx("div",{children:a.jsxs("ul",{className:e.list,children:[a.jsxs("li",{className:e.listItem,children:["Perform batch edits on ",t.toLowerCase()," attributes."]}),a.jsxs("li",{className:e.listItem,children:["Finalize ",t.toLowerCase(),"s by clicking ",a.jsx("strong",{children:"CREATE"}),"."]})]})})]});
270lz.propTypes={classes:A.object.isRequired,title:A.string.isRequired};const BDe=Be(zDe)(lz),cz=e=>({even:{backgroundColor:e.palette.background?.neutral?.default||e.palette.action?.hover},odd:{backgroundColor:e.palette.background?.paper||"transparent"},noBottomBorder:{borderBottom:"none"},cellBorderTop:{borderTop:`1px dashed ${e.palette.border?.default||e.palette.divider}`},cellText:{fontSize:14},placementText:{fontWeight:"bold",fontSize:14,whiteSpace:"nowrap"},textCell:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},error:{borderLeft:`5px solid ${e.palette.error.main}`},checkbox:{padding:0},checkboxContainer:{marginLeft:10,marginRight:10},creativeName:{overflow:"visible",whiteSpace:"nowrap"},editableCell:{borderTop:`1px dashed ${e.palette.border?.default||e.palette.divider}`,overflow:"hidden",padding:0,paddingLeft:5,textOverflow:"ellipsis",whiteSpace:"nowrap"},editControlsContainer:{alignItems:"flex-end",display:"flex",flexDirection:"row",justifyContent:"flex-end"},editSpinner:{marginBottom:-2,paddingRight:8},emptyCell:{border:"none",height:40},headerCellContainer:{alignItems:"center",display:"flex"},headerCell:{borderBottom:"none",padding:0},tableCell:{overflow:"hidden",padding:0,textOverflow:"ellipsis",whiteSpace:"nowrap"},tableRowTop:{borderBottom:"none"},tableRowBottom:{borderTop:"none"},inputWrapper:{padding:"0 5px",width:"100%"},width100:{width:"100%"}}),dz=({id:e,onBlur:t,rowKey:n})=>{const[r,s]=m.useState("");return a.jsx(De,{style:{width:"100%"},id:`nc-creatives-input-${e}-${n}`,onChange:i=>s(i.target.value),onBlur:()=>t(r),value:r||""})};dz.propTypes={id:A.number.isRequired,onBlur:A.func.isRequired,rowKey:A.string.isRequired};const TS=({classes:e,columnDefinitions:t,columnVisibility:n,creative:r,currentlyEditing:s,editLoading:i,even:o,isSelected:l,onChangeValue:c,onClickCancel:d,onClickEdit:u,onClickSubmit:p,onSelect:h})=>{const{palette:f}=Re(),{creative_name:g,id:x}=r,b=s===x,y=m.useMemo(()=>t.filter(E=>n[E.data]||E.alwaysOn),[t,n]),v=y.map(E=>a.jsx($e,{className:e.emptyCell},`cell-top-${E.name}`)),C=y.map(E=>{const k=E.data,j=r?.newValues?.[k]||r[k],_=a.jsx(I,{className:e.textCell,title:j,children:j});let D;switch(E.cellType){case"select":D=b?a.jsx("div",{className:e.inputWrapper,children:a.jsx(tt,{className:e.width100,id:`nc-creatives-select-${x}-${k}`,MenuProps:{MenuListProps:{id:`nc-creatives-select-paper-${x}-${k}`}},onChange:M=>{const N={...r,newValues:{...r.newValues,[k]:M.target.value}};c(N)},style:{marginTop:-1},value:j||"",children:E.options.map(M=>a.jsx(Se,{value:M.value,children:M.label},`menu-item-${M.value}`))})}):_;break;case"textEdit":D=b?a.jsx("div",{className:e.inputWrapper,children:a.jsx(dz,{id:x,onBlur:M=>{const N={...r,newValues:{...r.newValues,[k]:M}};c(N)},rowKey:k})}):_;break;default:D=_}return a.jsx($e,{className:e.editableCell,children:D},`cell-bottom-${E.name}`)});let w;b?w=a.jsxs("div",{className:e.editControlsContainer,children:[i?a.jsx("div",{className:e.editSpinner,children:a.jsx(Ze,{color:"inherit",size:12})}):null,a.jsx(He,{id:`nc-creatives-submit-${x}`,onClick:()=>p(r),style:{marginRight:8},children:a.jsx(eC,{color:f.success.main})}),a.jsx(He,{id:`nc-creatives-cancel-${x}`,onClick:d,children:a.jsx(Jt,{color:f.error.main})})]}):s||(w=a.jsx(He,{id:`nc-creatives-edit-${x}`,onClick:u,children:a.jsx(Ju,{style:{fontSize:20}})}));const S=o?"transparent":f.action.hover;return a.jsxs(a.Fragment,{children:[a.jsxs(bn,{className:e.tableRowTop,"data-creative-name":r.creative_name,style:{backgroundColor:S},children:[a.jsx($e,{className:e.headerCell,children:a.jsxs("div",{className:e.headerCellContainer,children:[a.jsx("div",{className:e.checkboxContainer,children:a.jsx(et,{checked:l,className:e.checkbox,disabled:b,id:`nc-creative-row-select-${x}`,onClick:h})}),a.jsx("div",{className:e.creativeName,children:a.jsx(I,{id:`nc-creative-row-creative-name-${x}`,title:g,children:a.jsx("strong",{children:g})})})]})}),a.jsx($e,{className:e.emptyCell}),v]}),a.jsxs(bn,{className:e.tableRowBottom,style:{backgroundColor:S},children:[a.jsx($e,{}),a.jsx($e,{style:{padding:"0 5px"},children:a.jsx("div",{style:{textAlign:"right"},children:w})}),C]})]})};TS.defaultProps={columnVisibility:{},currentlyEditing:null,editLoading:!1};TS.propTypes={classes:A.object.isRequired,creative:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object,editLoading:A.bool,even:A.bool.isRequired,currentlyEditing:A.number,isSelected:A.bool.isRequired,onChangeValue:A.func.isRequired,onClickCancel:A.func.isRequired,onClickEdit:A.func.isRequired,onClickSubmit:A.func.isRequired,onSelect:A.func.isRequired};
270const UDe=Be(cz)(TS),VDe=e=>({addButton:{},menuItem:{lineHeight:1,paddingBottom:10,paddingTop:10,whiteSpace:"normal",height:"inherit"},menuPaper:{border:`1px solid ${e.palette.divider}`,borderRadius:3,boxShadow:e.shadows[2],marginTop:4,maxHeight:150,width:165,overflow:"scroll"},root:{padding:0},flex:{display:"flex"},search:{marginTop:2},secondarySelect:{marginLeft:10,marginTop:-15,textAlign:"left"},secondaryText:{textAlign:"left"},secondarySelectContainer:{display:"flex",alignItems:"center",justifyContent:"flex-end",textAlign:"right",width:"100%"},secondarySelectLabelRootEmpty:{color:e.palette.text.disabled},secondarySelectLabelRoot:{display:"none"},secondarySelectLabelFocused:{display:"none"},secondarySelectLabelShrink:{display:"none"}}),WDe=(e,t)=>n=>{const{type_id:r}=t?.newValues||t;return e==="tactic"?!r||n.type_ids===null||n.type_ids.includes(r):!0},HDe=e=>t=>{switch(e){case"country":return{...t,name:t.desc};case"row_access":return{...t,name_slug:t.row_access};default:return t}},qDe=e=>(t,n)=>t[e]<n[e]?-1:t[e]>n[e]?1:0,IS=({attributeName:e,classes:t,error:n,header:r,onAttributeChange:s,placement:i,value:o})=>{const{engagementNiceId:l}=pe(),[c,d]=m.useState(null),u=e==="market"?"desc":"name",p=e==="row_access",h=p?e:`${e}_name`,f=p?r:e.charAt(0).toUpperCase()+e.slice(1),{newValues:g={}}=i,x=g[h]??i[h]??"",[b,y]=m.useState((p?o:x)??""),[v,C]=m.useState(b.slice(0,2)),{data:w=[],isFetching:S}=oW({attributeName:e,search:v??b,engagementNiceId:l}),E=j=>p?{row_access:j?.row_access||""}:{[`${e}_id`]:j?.id||"",[h]:j&&j[u]?j[u]:""};let k;return S?k=[a.jsx(Se,{className:t.menuItem,children:"Searching..."},"searching")]:k=w?.length===0?a.jsx(Se,{className:t.menuItem,children:"No Results"},"no-results"):w?.filter(WDe(e,i)).sort(qDe(u)).map(HDe(e)).map(j=>a.jsx(Se,{className:t.menuItem,onClick:()=>{d(null),y(j[u]);const _={...i,newValues:{...i.newValues,...E(j)}};s(_)},children:e==="market"?`${j[u]}(${j.country_name}, ${j.geo_granularity})`:j[u]},`result-${e}-${j.id}`)),a.jsxs("div",{children:[a.jsx(De,{className:t.search,error:n,id:`${i.id}-${e}-textfield`,onBlur:j=>{j.target.value.length===0&&s({...i,newValues:{...i.newValues,...E()}})},onChange:j=>{C(null),y(j.target.value)},onFocus:({currentTarget:j})=>{d(j)},placeholder:f,value:b}),a.jsx(uB,{anchorEl:c,id:`${i.id}-${e}-attribute-select`,open:!!c,placement:"bottom-start",children:a.jsx(Br,{className:t.menuPaper,elevation:2,children:a.jsx($v,{id:`${i.id}-${e}-options`,children:k})})})]})};IS.propTypes={attributeName:A.string.isRequired,classes:A.object.isRequired,error:A.bool.isRequired,header:A.string,onAttributeChange:A.func.isRequired,placement:A.object.isRequired,value:A.string};IS.defaultProps={value:null,header:""};const GDe=Be(VDe)(IS),YDe={container:{width:90},textField:{width:"100%"}},DS=({attributeName:e,classes:t,onTextChange:n,placement:r,value:s})=>{const[i,o]=m.useState(s),l=a.jsx(De,{autoComplete:"off",className:t.textField,value:i||"",id:`${r.id}-${e}-textfield`,onChange:c=>{Q4(c.target.value)||o(c.target.value)},onBlur:()=>{if(r[e]!==i){const c={...r,newValues:{...r.newValues,[e]:i}};n(c)}}});return a.jsx("div",{className:t.container,children:l})};DS.defaultProps={value:null};DS.propTypes={classes:A.object.isRequired,attributeName:A.string.isRequired,onTextChange:A.func.isRequired,placement:A.object.isRequired,value:A.any};const KDe=Be(YDe)(DS),QDe=()=>({button:{paddingLeft:9},root:{textAlign:"right",padding:8},buttonContainer:{display:"flex",flexDirection:"row",alignItems:"flex-end",justifyContent:"flex-end"}}),AS=({classes:e,editing:t,placementId:n,onClickCancel:r,onClickEdit:s,onClickSubmit:i,saving:o})=>{const{palette:l}=Re(),c=t?a.jsxs("div",{className:e.buttonContainer,children:[o?a.jsx("div",{style:{marginBottom:-2},children:a.jsx(Ze,{color:"inherit",size:12})}):null,a.jsx(He,{className:e.button,id:`${n}-submit-button`,onClick:()=>{i()},children:a.jsx(eC,{color:l.success.main})}),a.jsx(He,{className:e.button,id:`${n}-cancel-button`,onClick:r,children:a.jsx(Jt,{color:l.error.main})})]}):a.jsx(He,{className:e.button,id:`${n}-edit-button`,onClick:s,children:a.jsx(Ju,{})});return a.jsx($e,{className:e.root,children:c})};AS.defaultProps={editing:!1};AS.propTypes={classes:A.object.isRequired,editing:A.bool,placementId:A.oneOfType([A.string,A.number]).isRequired,onClickCancel:A.func.isRequired,onClickEdit:A.func.isRequired,onClickSubmit:A.func.isRequired,saving:A.bool.isRequired};const JDe=Be(QDe)(AS),XDe=()=>({root:{padding:0,textAlign:"center"},checkbox:{padding:0}}),MS=({classes:e,disabled:t,hidden:n,onSelect:r,selected:s})=>a.jsx($e,{className:e.root,children:a.jsx(be,{title:"Select to perform batch edits or create.",placement:"right",arrow:!0,children:a.jsx(et,{className:e.checkbox,checked:s,disabled:t,onClick:()=>r(!s),classes:{root:e.buttonBase},style:{visibility:n?"hidden":"inherit"}})})});MS.defaultProps={disabled:!1,hidden:!1,selected:!1};MS.propTypes={classes:A.object.isRequired,disabled:A.bool,hidden:A.bool,onSelect:A.func.isRequired,selected:A.bool};const ZDe=Be(XDe)(MS),RS=({classes:e,cellWidthScalingFactor:t,columnDefinitions:n,columnVisibility:r,editing:s,even:i,isSelected:o,onClickEdit:l,onEdit:c,onEditCancel:d,onEditSubmit:u,onSelect:p,placement:h,saving:f,selectedType:g})=>{const{engagementNiceId:x}=pe(),{data:b=[]}=yC({engagementNiceId:x}),{palette:y}=Re(),v=i?e.even:"",C=Dd(h,s),w=C===cS?e.error:e[C],S=`${v} ${w}`,E=!!(s||g&&g!==C),k=n.filter(({data:_})=>r[_]).map(({attributeName:_,cellType:D,data:M,header:N,width:O})=>{const{newValues:R={}}=h;let L=R[M]??h[M];_==="row_access"&&L&&(L=tz(b,L));const P=dS.includes(`${_}_id`)&&!L;let F="inherit",z="";const B=!s&&P;B&&(F=y.error.main,z=`${Pr(M.split("_")[0])} is required`);let W=a.jsx(I,{className:e.textCell,title:L,children:L});return s&&D==="attribute"?W=a.jsx(GDe,{attributeName:_,error:P,header:N,onAttributeChange:c,placement:h,value:L},M):s&&D==="customAttribute"&&(W=a.jsx(KDe,{attributeName:M,onTextChange:c,placement:h,value:L},M)),a.jsx(be,{disableHoverListener:s||!B,placement:"top",title:z,arrow:!0,children:a.jsx($e,{"data-column":M,classes:{root:[e.cellBorderTop,e.cellText]},style:{backgroundColor:F,padding:0,paddingLeft:5,width:O*t},children:W},M)},M)}),j=n.filter(({data:_})=>r[_]).map(({data:_,width:D})=>a.jsx($e,{"data-column":_,classes:{root:e.noBottomBorder},style:{backgroundColor:"inherit",width:D*t}},_));return a.jsxs(a.Fragment,{children:[a.jsxs(bn,{className:S,placementid:h.id,"data-placement-name":h.placement_name,id:`row-${h.id}-top`,"data-status":C,children:[a.jsx(ZDe,{classes:{root:e.noBottomBorder},disabled:E,onSelect:_=>p(_),placement:h,selected:o},"select"),a.jsx($e,{classes:{root:e.noBottomBorder},style:{padding:0,width:Hn.PLACEMENT.SECOND_COLUMN},children:a.jsx(I,{className:e.placementText,title:h.placement_name,children:h.placement_name})},"placement_name"),j]}),a.jsxs(bn,{className:S,placementid:h.id,id:`row-${h.id}-bottom`,children:[a.jsx($e,{style:{width:Hn.PLACEMENT.FIRST_COLUMN}}),a.jsx(JDe,{editing:s,placementId:h.id,onClickCancel:d,onClickEdit:l,onClickSubmit:u,saving:f,style:{width:Hn.PLACEMENT.SECOND_COLUMN}}),k]})]})};RS.propTypes={classes:A.object.isRequired,cellWidthScalingFactor:A.number.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,editing:A.bool,isSelected:A.bool.isRequired,placement:A.object.isRequired,onClickEdit:A.func.isRequired,onEdit:A.func.isRequired,onEditCancel:A.func.isRequired,onEditSubmit:A.func.isRequired,onSelect:A.func.isRequired,even:A.bool.isRequired,saving:A.bool.isRequired,selectedType:A.string};RS.defaultProps={editing:!1,selectedType:null};const eAe=Be(cz)(RS),tAe=()=>({container:{display:"flex",flexDirection:"column",margin:"30px 15px 0px 15px",paddingBottom:30,overflowX:"hidden"},heading:{fontSize:16,padding:0},paginatorSpinner:{width:"100%",display:"flex",alignItems:"center",justifyContent:"flex-end",marginTop:20,marginRight:20},table:{overflow:"hidden",tableLayout:"fixed"},tableWrapper:{overflow:"scroll",width:"100%"}}),uz=({classes:e,tableName:t})=>{const{columnDefinitions:n,defaultColumnVisibility:r,updateEndpoint:s,createLambdaName:i,updateLambdaName:o,headerName:l}=B$[t],c=t===rn.PLACEMENT?"deselectedPlacementIds":"deselectedCreativeIds",d=t===rn.PLACEMENT?"selectedPlacementIds":"selectedCreativeIds",{engagementNiceId:u}=pe(),p=yn({authorized:"DataSources.NameCleaning.Approve"}),{mpTrack:h}=tr(),[f]=Qi(),[g]=Qi(),[x]=Qi(),[b,y]=m.useState(!1),[v,C]=m.useState({}),[w,S]=m.useState(()=>r),[E,k]=m.useState(0),[j,_]=m.useState([]),[D,M]=m.useState(null),[N,O]=m.useState(!1),[R,L]=m.useState(!1),[P,F]=m.useState([]),[z,B]=m.useState(25),[W,H]=m.useState(!1),[V,G]=m.useState(""),[X,K]=m.useState({}),[ie,le]=m.useState("ASC"),[ce,J]=m.useState(null),he=m.useMemo(()=>Object.keys(X).length,[X]),ne=m.useMemo(()=>{const Oe=Object.entries(w).filter(([,pt])=>pt).map(([pt])=>pt),Pe={engagement_nice_id:u,keyword:V,offset:E*z,rowsPerPage:z,selectAll:b,visibleColumns:Oe},Fe=[];return Object.entries(v).forEach(([pt,_t])=>{Object.entries(_t).filter(([,Rn])=>
270Rn).forEach(([Rn])=>Fe.push([pt,Rn==="null"?null:Rn]))}),Fe.length&&(Pe.filters=Fe.map(pt=>JSON.stringify(pt))),ie&&(Pe.sortDirection=ie),Pe},[v,E,z,V,ie]),Y=m.useMemo(()=>{const Oe={selectAll:b},Pe=Object.keys(X);return!b&&Pe.length?Oe[d]=Pe:b&&j.length&&(Oe[c]=j),Oe},[c,j,b,d,X]),{count:ae,placements:je,placementsFetching:me,refetch:ve}=pS({body:ne,engagementNiceId:u,tableName:t}),Me=m.useMemo(()=>je,[je]),q=m.useRef(ve);q.current=ve;const Q=m.useCallback(()=>{J(null),q.current()},[]),{percentComplete:ee}=jm({eventType:"NameCleaning",onComplete:Q,taskId:ce});m.useEffect(()=>{if(me)return;const Oe=je.filter(({id:Fe})=>String(Fe)in X).reduce((Fe,pt)=>({...Fe,[String(pt.id)]:t===rn.PLACEMENT?Dd(pt):1}),{}),Pe=je.filter(({id:Fe})=>String(Fe)in j).map(({id:Fe})=>Fe);K(Oe),_(Pe),F(je),H(!1)},[je,t]),m.useEffect(()=>{const Oe=Object.values(v).some(Pe=>Object.values(Pe).some(Fe=>Fe));L(Oe)},[v]);const Ce=Oe=>x({apiName:"mediaResolution",endpoint:"GetPlacementColumnFilterOptions",parameters:{body:{...ne,column_name:Oe},pathParameters:{niceId:u}}}).unwrap(),se=async()=>{const Oe=P.find(_t=>_t.id===D),{newValues:Pe={}}=Oe;let Fe={};t===rn.PLACEMENT?FIe.forEach(_t=>{typeof Pe[_t]<"u"&&(Fe[_t]=Pe[_t])}):Fe=Pe;const{task_id:pt}=await g({apiName:"mediaResolution",endpoint:s,parameters:{body:{...ne,...Y,...Fe,lambdaName:o},pathParameters:{niceId:u}}}).unwrap();M(null),pt?J(String(pt)):ve()},oe=()=>{const Oe=he>1;Oe||se(),O(Oe),H(!0)},te=async()=>{h("DASHBOARDADMIN NAMECLEANING ACTIONS",{actionType:"CREATE",currentTab:"PLACEMENTS"});const{task_id:Oe}=await f({apiName:"mediaResolution",endpoint:"TriggerAsyncLambda",parameters:{body:{...ne,...Y,lambdaName:i},pathParameters:{niceId:u}}}).unwrap();Oe?J(String(Oe)):ve(),C({})},de=Oe=>P.map((Pe,Fe)=>{const pt=Object.keys(X).map(ot=>parseInt(ot,10)),_t=D===Pe.id,Rn=b?!j.includes(Pe.id):pt.includes(Pe.id);return t===rn.PLACEMENT?a.jsx(eAe,{cellWidthScalingFactor:Oe,columnDefinitions:n,columnVisibility:w,editing:_t,even:!!(Fe%2),isSelected:Rn,onClickEdit:()=>{M(Pe.id);const ot={...X};ot[Pe.id]=Dd(Pe),K(ot)},onEdit:ot=>{const Vn=[...P.slice(0,Fe),ot,...P.slice(Fe+1)];F(Vn)},onEditCancel:()=>{M(null),K({});const ot=[...P.slice(0,Fe),Me[Fe],...P.slice(Fe+1)];F(ot)},onEditSubmit:oe,onSelect:()=>{if(b){let ot;j.includes(Pe.id)?ot=j.filter(Cn=>Cn!==Pe.id):ot=[...j,Pe.id],_(ot.sort((Cn,Sr)=>Cn-Sr));const Vn={...X};delete Vn[Pe.id],K(Vn)}else{const ot={...X},Vn=new Set(Object.keys(ot).map(Sr=>parseInt(Sr,10))),Cn=Dd(Pe);Vn.has(Pe.id)?delete ot[Pe.id]:ot[Pe.id]=Cn,K(ot),y(!1)}},placement:Pe,saving:W},Pe.id):a.jsx(UDe,{columnDefinitions:n,columnVisibility:w,creative:Pe,currentlyEditing:D,editLoading:W,even:!!(Fe%2),isSelected:Rn,onChangeValue:ot=>{const Vn=[...P.slice(0,Fe),ot,...P.slice(Fe+1)];F(Vn)},onClickCancel:()=>{M(null),K({});const ot=[...P.slice(0,Fe),Me[Fe],...P.slice(Fe+1)];F(ot)},onClickEdit:()=>{M(Pe.id);const ot={...X};ot[Pe.id]=1,K(ot)},onClickSubmit:oe,onSelect:()=>{if(b){let ot;j.includes(Pe.id)?ot=j.filter(Cn=>Cn!==Pe.id):ot=[...j,Pe.id],_(ot.sort((Cn,Sr)=>Cn-Sr));const Vn={...X};delete Vn[Pe.id],K(Vn)}else{const ot={...X};new Set(Object.keys(ot).map(Cn=>parseInt(Cn,10))).has(Pe.id)?delete ot[Pe.id]:ot[Pe.id]=1,K(ot),y(!1)}}},Pe.id)}),ke=(Oe,Pe,Fe)=>{const pt={...v};pt[Oe][Pe]=Fe,C(pt)},Le=(Oe,Pe)=>{const Fe={};Object.keys(v[Oe]).forEach(pt=>{Fe[pt]=Pe}),C({...v,[Oe]:Fe})},at=Math.ceil(ae/z),Wt=m.useMemo(()=>{const Oe=n.filter(({alwaysOn:_t,data:Rn})=>w[Rn]||_t).map(({width:_t})=>_t).reduce((_t,Rn)=>_t+Rn,0),Pe=Hn.PLACEMENT.FIRST_COLUMN+Hn.PLACEMENT.SECOND_COLUMN+Oe,Fe=1180,pt=Fe-Hn.PLACEMENT.FIRST_COLUMN-Hn.PLACEMENT.SECOND_COLUMN;return Pe<Fe?pt/Oe:1},[n,w]),zt=de(Wt),Ht=m.useMemo(()=>p&&!D&&(b||Object.values(X).filter(Oe=>Oe).length>0),[b,D,X,p]);return a.jsxs("div",{className:e.container,children:[a.jsx(C$,{show:!!ce,message:`Please wait while ${l.toLowerCase()}s are being processed.`,percentComplete:ee}),a.jsx(BDe,{title:l}),a.jsx(ADe,{canSelectAll:b,clearColumnFilters:()=>C({}),columnDefinitions:n,columnFilters:v,columnVisibility:w,createPlacementButtonEnabled:Ht,deselectedRows:j,hasColumnFilter:R,onCreatePlacement:te,onChangeColumnVisibility:(Oe,Pe)=>{S({...w,[Oe]:Pe}),G("")},onSelectAllRows:()=>{const Oe=b&&!j.length;y(!Oe),K({}),_([])},onUpdateSearchText:Oe=>G(Oe),placements:P,searchText:V,selectedRows:X,totalNumberOfPlacements:ae}),a.jsx("div",{className:e.tableWrapper,children:a.jsxs(Ki,{className:e.table,id:"name-cleaning-placements-table",children:[a.jsx(Ya,{children:a.jsx($De,{cellWidthScalingFactor:Wt,columnDefinitions:n,columnFilters:v,columnVisibility:w,getColumnFilterOptions:Ce,onChangeSortDirection:Oe=>le(Oe),onSelectAllColumnFilters:Le,onUpdateColumnFilter:ke,setColumnFilters:C,sortDirection:ie,tableName:t,title:l})}),a.jsx(xl,{id:"nc-table-body",children:me?null:zt})]})}),me&&a.jsx("div",{style:{marginTop:40,textAlign:"center",width:"100%"},children:a.jsx(Ze,{size:24})}),ae!==null?a.jsx(Qw,{controlPageSizeBool:!0,currentPage:E,onChangePageSize:Oe=>{B(Oe),k(0)},onGoBackward:()=>{E>0&&k(E-1)},onGoForward:()=>{E<at-1&&k(E+1)},pageSize:z,total:ae}):a.jsx("div",{className:e.paginatorSpinner,children:a.jsx(Ze,{size:18})}),a.jsx(mt,{acceptLabel:"Batch Edit",body:a.jsxs(I,{component:"span",children:["You are about make a batch edit to ",a.jsxs("strong",{children:[he," selected rows."]})]}),handleAccept:()=>{se(),O(!1)},handleClose:()=>{H(!1),O(!1)},open:N,title:"Are you sure?"})]})};
270uz.propTypes={classes:A.object.isRequired,tableName:A.string.isRequired};const nAe=Be(tAe)(uz),rAe=e=>({menu:{border:"solid 1px",borderColor:e.palette.secondary.main,top:"10px !important"},menuItem:{textAlign:"left",width:160},addColumnIconFill:{fill:e.palette.secondary.main},addColumnIconPlus:{stroke:e.palette.secondary.main}}),pz=({classes:e,columnDefinitions:t,columnVisibility:n,onChangeColumnVisibility:r})=>{const[s,i]=m.useState(null),{palette:o}=Re(),l=!!s,c=t.filter(({alwaysOn:d})=>!d).map(({data:d,header:u})=>a.jsx(Se,{disableGutters:!0,sx:{p:0},children:a.jsxs(He,{onClick:()=>r(d,!n[d]),children:[a.jsx(et,{checked:n[d]}),a.jsx(I,{className:e.menuItem,children:u})]})},d));return a.jsxs(a.Fragment,{children:[a.jsx(be,{title:"Add/remove columns from table. To add/edit attributes, add attribute columns to the table view.",placement:"right",arrow:!0,children:a.jsx(He,{"aria-controls":"column-picker","aria-haspopup":"true",onClick:d=>i(d.currentTarget),children:a.jsx(po,{color:o.secondary.main})})}),a.jsx(dr,{anchorEl:s,className:e.menu,id:"column-picker",open:l,onClose:()=>i(null),anchorOrigin:{vertical:"bottom",horizontal:"left"},MenuListProps:{dense:!0},children:c})]})};pz.propTypes={classes:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,onChangeColumnVisibility:A.func.isRequired};const sAe=Be(rAe)(pz),iAe=()=>({container:{display:"flex",flexDirection:"column",marginBottom:10}}),hz=({classes:e,columnDefinitions:t,columnVisibility:n,onChangeColumnVisibility:r})=>a.jsx("div",{className:e.container,children:a.jsx("div",{style:{marginTop:15,display:"flex",flexDirection:"row"},children:a.jsx(sAe,{columnDefinitions:t,columnVisibility:n,onChangeColumnVisibility:r})})});hz.propTypes={classes:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,onChangeColumnVisibility:A.func.isRequired};const aAe=Be(iAe)(hz),oAe=e=>({row:{borderTop:`1px solid ${e.palette.divider}`},filterCell:{width:"100%",display:"flex",flexDirection:"row"}}),fz=({classes:e,columnDefinitions:t,columnVisibility:n,cellWidthScalingFactor:r,title:s})=>{const i=t.filter(({data:o})=>n[o]).map(({data:o,header:l,width:c})=>a.jsx($e,{style:{padding:0,maxWidth:`${c*r} !important`,width:c*r},variant:"head",children:l},o));return a.jsxs(bn,{className:e.row,children:[a.jsx($e,{className:e.cell,style:{width:Hn.RULES.FIRST_COLUMN}}),s!=="Brand"&&a.jsx($e,{className:e.cell,style:{padding:0,width:Hn.RULES.SECOND_COLUMN},children:a.jsx("div",{style:{width:"100%",overflow:"visible"},children:s})}),i]})};fz.propTypes={cellWidthScalingFactor:A.number.isRequired,classes:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,title:A.string.isRequired};const lAe=Be(oAe)(fz),mz=e=>({approved:{borderLeft:`5px solid ${e.palette.success.main}`},cellBorder:{borderBottom:`1px solid ${e.palette.divider}`},dropDown:{lineHeight:"normal",whiteSpace:"normal",wordBreak:"break-word",hyphens:"auto",height:"auto"},edited:{borderLeft:`5px solid ${e.palette.neutral?.[500]||e.palette.grey[500]}`},even:{backgroundColor:e.palette.action.hover},selectCellRoot:{padding:0,textAlign:"center",margin:0,borderBottom:"none"},selectWidth:{width:130},standardText:{fontSize:13,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},superSelect:{margin:0},textCell:{fontSize:14,maxHeight:80,lineHeight:"normal",padding:0},unedited:{borderLeft:"5px solid transparent"}}),NS=({classes:e,cellWidthScalingFactor:t,dottedBorder:n,paddingLeft:r,textStyle:s,value:i,width:o})=>a.jsx($e,{classes:{root:e.cellBorder},className:e.textCell,style:{borderBottom:l=>n?`1px dashed ${l.palette.divider}`:"none",maxWidth:o*t,paddingLeft:r},children:a.jsx(I,{style:s,"data-test":"text-cell",title:i||"",children:i||""})});NS.propTypes={cellWidthScalingFactor:A.number,classes:A.object.isRequired,dottedBorder:A.bool,paddingLeft:A.number,textStyle:A.object,value:A.string,width:A.number};NS.defaultProps={cellWidthScalingFactor:1,dottedBorder:!1,paddingLeft:0,textStyle:{fontSize:14,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},value:"",width:50};const th=Be(mz)(NS),cD=["brand","placement_id","placement_name"],OS=({classes:e,columnDefinitions:t,columnVisibility:n,even:r,rowData:s})=>{const i=m.useMemo(()=>t.filter(p=>n[p.data]||p.alwaysOn),[t,n]),{status:o="unedited"}=s;let l=e[o];l=`${l} ${r?e.even:e.odd}`;const c=`${l} ${e.cellBorder}`,d=i.map(({data:p,width:h})=>{const f=cD.includes(p)&&s[p]?s[p].toString():"",g={fontSize:13,whiteSpace:"nowrap",overflow:p==="placement_name"?"visible":"hidden",textOverflow:"ellipsis",fontWeight:"bold"};return a.jsx(th,{dottedBorder:p!=="brand",textStyle:g,value:f,width:h},p)}),u=i.map(({data:p,width:h})=>{const f=!cD.includes(p)&&s[p]?s[p].toString():"";return a.jsx(th,{paddingLeft:5,value:f,width:h},p)});return a.jsxs(a.Fragment,{children:[a.jsxs(bn,{className:l,"data-test":"brands-top-row",children:[a.jsx(th,{value:"",width:30}),d]}),a.jsxs(bn,{className:c,"data-test":"brands-bottom-row",children:[a.jsx(th,{value:"",width:30}),u]})]})};OS.propTypes={classes:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,even:A.bool,rowData:A.object};OS.defaultProps={even:!1,rowData:{}};const cAe=Be(mz)(OS),gz=e=>({even:{backgroundColor:e.palette.action.hover},noBottomBorder:{borderBottom:"none"},cellBorderTop:{borderTop:`1px dashed ${e.palette.divider}`},cellText:{fontSize:14},placementText:{fontWeight:"bold",fontSize:13,whiteSpace:"nowrap"},textCell:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},approval_requested:{borderLeft:`5px solid ${e.palette.warning.main}`},approved:{borderLeft:`5px solid ${e.palette.success.main}`},error:{borderLeft:`5px solid ${e.palette.error.main}`},for_review:{borderLeft:"5px solid transparent"},checkbox:{padding:0},checkboxContainer:{marginLeft:10,marginRight:10},creativeName:{overflow:"visible",whiteSpace:"nowrap"},editableCellContainer:{borderTop:`1px dashed ${e.palette.divider}`,display:"flex",alignItems:"center",overflow:"hidden",height:40}
270,editControlsContainer:{alignItems:"flex-end",display:"flex",flexDirection:"row",justifyContent:"flex-end"},editSpinner:{marginBottom:-2,paddingRight:8},emptyCell:{border:"none",height:40},headerCell:{borderBottom:"none",padding:0,paddingLeft:15,fontSize:13},tableCell:{borderTop:`1px dashed ${e.palette.divider}`,padding:0,paddingLeft:5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",width:"100%"},tableRowTop:{borderBottom:"none"},tableRowBottom:{borderTop:"none"},inputWrapper:{padding:"0 5px",width:"100%"},width100:{width:"100%"}}),PS=({classes:e,columnDefinitions:t,columnVisibility:n,creative:r,even:s})=>{const{palette:i}=Re(),o=m.useMemo(()=>t.filter(u=>n[u.data]||u.alwaysOn),[t,n]),l=o.map(u=>a.jsx($e,{className:e.emptyCell},`cell-top-${u.name}`)),c=o.map(u=>{const p=r[u.data];return a.jsx($e,{className:e.tableCell,children:a.jsx(I,{className:e.textCell,title:p,children:p})},`cell-bottom-${u.name}`)}),d=s?"transparent":i.palette.action.hover;return a.jsxs(a.Fragment,{children:[a.jsxs(bn,{className:e.tableRowTop,"data-creative-name":r.creative_name,style:{backgroundColor:d},children:[a.jsx($e,{className:e.headerCell,children:a.jsx(I,{className:e.creativeName,id:`nc-creative-row-creative-name-${r.id}`,title:r.creative_name,children:a.jsx("strong",{children:r.creative_name})})}),a.jsx($e,{className:e.emptyCell}),l]}),a.jsxs(bn,{className:e.tableRowBottom,style:{backgroundColor:d},children:[a.jsx($e,{}),a.jsx($e,{style:{padding:"0 5px"}}),c]})]})};PS.defaultProps={columnVisibility:{}};PS.propTypes={classes:A.object.isRequired,creative:A.object.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object,even:A.bool.isRequired};const dAe=Be(gz)(PS),xz=({classes:e,cellWidthScalingFactor:t,columnDefinitions:n,columnVisibility:r,even:s,placement:i})=>{const{palette:o}=Re(),{engagementNiceId:l}=pe(),{data:c=[]}=yC({engagementNiceId:l}),d=s?e.even:"",u=Dd(i),p=u===cS?e.error:e[u],h=`${d} ${p}`,f=n.filter(({data:x})=>r[x]).map(({attributeName:x,data:b,width:y})=>{const{newValues:v={}}=i;let C=v[b]??i[b];x==="row_access"&&C&&(C=tz(c,C));const w=dS.includes(`${x}_id`)&&!C;let S="inherit",E="";const k=w;return k&&(S=o.error.main,E=`${Pr(b.split("_")[0])} is required`),a.jsx(be,{disableHoverListener:!k,placement:"top",title:E,arrow:!0,children:a.jsx($e,{"data-column":b,classes:{root:e.cellBorderTop},style:{backgroundColor:S,padding:0,paddingLeft:5,width:y*t},children:a.jsx(I,{className:e.textCell,title:C,children:C})},b)},b)}),g=n.filter(({data:x})=>r[x]).map(({data:x,width:b})=>a.jsx($e,{"data-column":x,classes:{root:e.noBottomBorder},style:{backgroundColor:"inherit",width:b*t}},x));return a.jsxs(a.Fragment,{children:[a.jsxs(bn,{className:h,placementid:i.id,"data-placement-name":i.placement_name,id:`row-${i.id}-top`,"data-status":u,children:[a.jsx($e,{classes:{root:e.noBottomBorder},style:{width:Hn.RULES.FIRST_COLUMN}}),a.jsx($e,{classes:{root:e.noBottomBorder},style:{padding:0,width:Hn.RULES.SECOND_COLUMN},children:a.jsx(I,{className:e.placementText,title:i.placement_name,children:i.placement_name})}),g]}),a.jsxs(bn,{className:h,placementid:i.id,id:`row-${i.id}-bottom`,children:[a.jsx($e,{style:{width:Hn.RULES.FIRST_COLUMN}}),a.jsx($e,{style:{width:Hn.RULES.SECOND_COLUMN}}),f]})]})};xz.propTypes={classes:A.object.isRequired,cellWidthScalingFactor:A.number.isRequired,columnDefinitions:A.array.isRequired,columnVisibility:A.object.isRequired,placement:A.object.isRequired,even:A.bool.isRequired};const uAe=Be(gz)(xz),pAe={label:{fontWeight:"normal !important"},typography:{marginTop:9}},LS=({customProps:e,value:t,setValue:n,labelYes:r,labelNo:s,readonly:i,classes:o})=>a.jsxs(Qe,{children:[a.jsx(wt,{shrink:!0,className:o.label,children:"Value"}),a.jsx(I,{component:"div",className:o.typography,children:a.jsxs(td,{component:"label",container:!0,alignItems:"center",spacing:0,children:[a.jsx(td,{item:!0,component:"span",children:s}),a.jsx(td,{item:!0,component:"span",children:a.jsx(Dn,{checked:!!t,name:"where-switch",onChange:()=>n(!t),disabled:i,...e})}),a.jsx(td,{item:!0,component:"span",children:r})]})})]});LS.propTypes={classes:A.object.isRequired,customProps:A.object,value:A.bool,setValue:A.func.isRequired,labelNo:A.string,labelYes:A.string,readonly:A.bool};LS.defaultProps={customProps:{},value:!1,labelNo:"False",labelYes:"True",readonly:!1};const hAe=Be(pAe)(LS),fAe={label:{fontWeight:"normal !important"},paper:{maxHeight:200}},FS=({classes:e,items:t,label:n,placeholder:r,readonly:s,selectedKey:i,setField:o,width:l})=>{const c=m.useMemo(()=>Object.keys(t).map(p=>{const h=t[p],{path:f,label:g,disabled:x}=h;return a.jsx(Se,{disabled:x,name:"where-select-item",value:f,children:g},f)}),[t]),d=p=>{p.target.value!==void 0&&o(p.target.value)},u=p=>{if(!s&&!p)return r;const h=f=>f.map(g=>g.items?h(g.items):g.path===p?g.label:null);return h(t).filter(f=>Array.isArray(f)?f.some(g=>g!==null):f!==null).pop()};return a.jsxs(Qe,{style:{width:l},children:[a.jsx(wt,{shrink:!0,className:e.label,children:n}),a.jsx(tt,{name:"where-select",disabled:s,displayEmpty:!0,MenuProps:{anchorOrigin:{vertical:"bottom",horizontal:"left"},classes:{paper:e.paper},disableAutoFocusItem:!0,marginThreshold:0,style:{width:l},transformOrigin:{vertical:"top",horizontal:"left"}},onChange:d,renderValue:u,value:i??"",variant:"filled",children:c})]})};FS.propTypes={classes:A.object.isRequired,items:A.array,label:A.string.isRequired,placeholder:A.string,readonly:A.bool,selectedKey:A.string,setField:A.func.isRequired,width:A.number.isRequired};FS.defaultProps={items:[],placeholder:"",readonly:!1,selectedKey:null};const _b=Be(fAe)(FS),mAe={label:{fontWeight:"normal !important"},textField:{marginTop:17}},$S=({classes:e,value:t,setValue:n,readonly:r,customProps:s})=>a.jsxs(Qe,{style:{width:300},children:[a.jsx(wt,{className:e.label,children:"Value"}),a.jsx(Uv,{className:e.textField,name:"where-number-input",value:t||"",type:"number",disabled:r,onChange:i=>n(i.target.value===""?void 0:i.target.value),...s})]});$S.propTypes={classes:A.object.isRequired,value:A.string,setValue:A.func.isRequired,readonly:A.bool,customProps:A.object};$S.defaultProps={value:"",readonly:!1,customProps:{}};const gAe=Be(mAe)($S),_g=({customProps:e,readonly:t,setValue:n,value:r})=>a.jsxs(Qe,{sx:{width:300},children:[a.jsx(wt,{shrink:!0,sx:{fontWeight:"normal !important"},children:"Value"}),a.jsx(De,{name:"where-text-input",value:r||"",InputProps:{readOnly:t},disabled:t,onChange:s=>n(s.target.value===""?void 0:s.target.value),variant:"filled",...e})]});
270_g.propTypes={customProps:A.object,readonly:A.bool,setValue:A.func.isRequired,value:A.string};_g.defaultProps={customProps:{},readonly:!1,value:""};const xAe=e=>({listSubheader:{backgroundColor:e.palette.common.White,paddingTop:10},textField:{width:190}}),zS=Ne.forwardRef(({classes:e,id:t,onChange:n,searchTerm:r,...s},i)=>{const{palette:o}=Re();return a.jsx(Nh,{className:e.listSubheader,ref:i,...s,children:a.jsx(De,{className:e.textField,InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:o.text.disabled,size:20})}),id:`${t}-search-input`},onChange:n,placeholder:"Search",style:{width:"100%"},value:r})})});zS.propTypes={classes:A.object.isRequired,id:A.string.isRequired,onChange:A.func,searchTerm:A.string};zS.defaultProps={onChange:()=>{},searchTerm:""};const bAe=Be(xAe)(zS),yAe={label:{fontWeight:"normal !important"},menuList:{paddingTop:0},paper:{maxHeight:200},spinner:{padding:"10px 16px"}},vAe=25,dD=e=>e.reduce((t,n)=>(t.findIndex(r=>r.value===n.value)===-1&&t.push(n),t),[]).sort(({label:t},{label:n})=>t.localeCompare(n)),BS=({classes:e,customProps:t,fieldDefinition:n,label:r,listValues:s,placeholder:i,readonly:o,setValue:l,value:c,width:d})=>{const[u,p]=m.useState(!1),[h,f]=m.useState(0),[g,x]=m.useState(!1),[b,y]=m.useState([]),[v,C]=m.useState(""),[w,S]=m.useState(),{showSearch:E}=t,{asyncFetch:k,useAsyncSearch:j}=n,_=()=>{const P=async()=>await k(v,h,c);j&&(p(!0),P().then(({hasMore:F,values:z})=>{y(dD(z)),S(F),p(!1)}))};m.useEffect(_,[n,v]);const D=j?b:s,M=P=>Object.keys(P).map(F=>{const z=P[F],{label:B,value:W}=z;return a.jsx(Se,{name:"where-select-item",value:W,children:B},W)}),N=P=>{if(!o&&P==null)return i;const z=(j?b:s).find(B=>P===String(B.value));return z?z.label:""},O=a.jsx(bAe,{id:"select",searchTerm:v,onChange:({target:P})=>C(P.value)}),R=a.jsx(Se,{value:"has-more",children:a.jsx("i",{children:"Load more..."})}),L=a.jsx("div",{className:e.spinner,children:a.jsx(Ze,{})});return a.jsxs(Qe,{style:{width:d},children:[a.jsx(wt,{shrink:!0,className:e.label,children:r}),a.jsxs(tt,{open:g,onClose:()=>{},onOpen:()=>{},name:"where-select",MenuProps:{anchorOrigin:{vertical:"bottom",horizontal:"left"},classes:{paper:e.paper},disableAutoFocusItem:!0,onClose:()=>{x(!1),C("")},marginThreshold:0,MenuListProps:{disablePadding:!0},transformOrigin:{vertical:"top",horizontal:"left"}},onChange:async P=>{P.preventDefault(),P.stopPropagation();const F=P.target.value;if(F==="undefined"){x(!1),C("");return}if(F==="has-more"){p(!0);const z=h+vAe;f(z);const{hasMore:B,values:W}=await k(v,z,c),H=dD([...b,...W]);y(H),S(B),p(!1);return}l(`${F}`),x(!1),C("")},renderValue:N,SelectDisplayProps:{onClick:()=>x(!0)},value:c||"",children:[E&&O,M(D),u&&L,w&&!u&&R]})]})};BS.propTypes={classes:A.object.isRequired,customProps:A.object,fieldDefinition:A.object,label:A.string.isRequired,listValues:A.array,placeholder:A.string,readonly:A.bool,setValue:A.func.isRequired,value:A.oneOfType([A.string,A.number]),width:A.number.isRequired};BS.defaultProps={customProps:{},fieldDefinition:{},listValues:[],placeholder:"",readonly:!1,value:""};const bz=Be(yAe)(BS),CAe=({customConfig:e,engagementNiceId:t,lazyAwsApiRead:n,tableName:r})=>{const s={};return Object.entries(e.fields).forEach(([i,o])=>{s[i]={...o,excludeOperators:["select_any_in","select_not_any_in"],showSearch:!0,asyncFetch:async(l="",c=0,d=null)=>await n({apiName:"mediaResolution",endpoint:"GetRuleOptions",parameters:{queryStringParameters:{engagement_nice_id:t,table_name:r,column_name:i,offset:c,search:l,id:d}}}).unwrap(),useAsyncSearch:!0,useLoadMores:!0}}),{...qr,fields:s,operators:e.operators,settings:{...qr.settings,addRuleLabel:"Add condition",renderField:i=>a.jsx(_b,{...i,label:"Column name",width:300}),renderFunc:i=>a.jsx(_b,{...i,label:"Column name",width:300}),renderOperator:i=>a.jsx(_b,{...i,label:"Operator",width:130})},types:{...qr.types,text:{...qr.types.text,widgets:{...qr.types.text.widgets,field:{...qr.types.text.widgets.field,operators:["equal","not_equal"]},text:{...qr.types.text.widgets.text,operators:e.types.text.widgets.text.operators.filter(i=>i!=="proximity")}}}},widgets:{...qr.widgets,boolean:{...qr.widgets.boolean,factory:i=>a.jsx(hAe,{...i}),labelYes:"True",labelNo:"False"},number:{...qr.widgets.number,factory:i=>a.jsx(gAe,{...i})},select:{...qr.widgets.select,factory:i=>a.jsx(bz,{...i,width:300})},text:{...qr.widgets.text,factory:i=>a.jsx(_g,{...i})}}}},wAe=e=>({buttons:{width:275,display:"flex",justifyContent:"space-between",marginBottom:30},Accordion:{backgroundColor:"transparent",border:"none",borderLeft:"none !important",borderRight:"none !important",margin:0,boxShadow:"none","&:not(:first-child)":{borderTop:`1px solid ${e.palette.divider}`}},AccordionSummary:{border:"none",minHeight:40,padding:0,"&:hover":{cursor:"default !important"}},AccordionSummaryExpanded:{margin:"0 !important",minHeight:"40px !important",boxShadow:"none",borderBottom:`1px solid ${e.palette.divider}`},AccordionSummaryContent:{justifyContent:"space-between",margin:0,boxShadow:"none"}
270,AccordionDetails:{border:"none",boxShadow:"none",padding:0,display:"block"},name:{alignSelf:"center",width:"100%"},nameActive:{alignSelf:"center"},nameSpan:{display:"flex",width:"100%"},reorderGroup:{width:20,paddingTop:6,marginLeft:10,marginRight:20,display:"flex",flexDirection:"column"},right:{display:"flex",alignItems:"center",paddingRight:"0px !important"}}),yz=300,SAe={formControl:{marginRight:20,width:yz},paper:{maxHeight:200}},US=({classes:e,config:t,value:n,onChange:r})=>a.jsxs(Qe,{className:e.formControl,children:[a.jsx(wt,{shrink:!0,children:"Column name"}),a.jsx(tt,{value:n,MenuProps:{anchorOrigin:{vertical:"bottom",horizontal:"left"},classes:{paper:e.paper},disableAutoFocusItem:!0,marginThreshold:0,style:{width:yz},transformOrigin:{vertical:"top",horizontal:"left"}},name:"update-column-name",onChange:({target:s})=>r(s.value),children:Object.entries(t.updates).sort(([,{label:s}],[,{label:i}])=>s.localeCompare(i)).map(([s,{label:i}])=>a.jsx(Se,{value:s,id:s,children:i},s))})]});US.propTypes={classes:A.object.isRequired,config:A.object.isRequired,onChange:A.func.isRequired,value:A.string};US.defaultProps={value:""};
270const jAe=Be(SAe)(US),VS=({config:e,onChange:t,columnName:n,value:r})=>{if(!n)return null;const{type:s}=e.updates[n],i=e.conditions.fields[n];return s==="text"||s==="number"?a.jsx(_g,{setValue:t,value:r===null?"null":r}):a.jsx(bz,{customProps:{showSearch:!0},fieldDefinition:i,label:"Value",setValue:t,value:r,width:300})};VS.propTypes={config:A.object.isRequired,columnName:A.string,onChange:A.func.isRequired,value:A.oneOfType([A.string,A.number])};VS.defaultProps={columnName:"",value:""};const kAe=()=>({minusButton:{marginRight:15,marginTop:15},row:{display:"flex",alignItems:"center",marginBottom:35}}),WS=({classes:e,config:t,onChange:n,onClickRemove:r,only:s,tableName:i,columnName:o,updateValue:l})=>a.jsxs("div",{className:e.row,children:[s||a.jsx(He,{className:e.minusButton,id:"remove-row",onClick:r,children:a.jsx(Kv,{})}),a.jsx(jAe,{config:t,onChange:c=>n(c,""),tableName:i,value:o}),a.jsx(VS,{columnName:o,config:t,onChange:c=>n(o,c),tableName:i,value:l})]});WS.propTypes={classes:A.object.isRequired,config:A.object.isRequired,columnName:A.string,onChange:A.func.isRequired,onClickRemove:A.func.isRequired,only:A.bool.isRequired,tableName:A.string.isRequired,updateValue:A.oneOfType([A.string,A.number])};WS.defaultProps={columnName:"",updateValue:""};const EAe=Be(kAe)(WS),_Ae=()=>({heading:{fontSize:16,marginTop:15,marginBottom:25},root:{display:"block",marginBottom:45}}),HS=({classes:e,config:t,updates:n,onChange:r,tableName:s})=>{const i=m.useMemo(()=>Object.entries(t.updates).sort(([,{label:o}],[,{label:l}])=>o.localeCompare(l)).map(([o])=>o)[0],[t.updates]);return a.jsxs("div",{className:e.root,children:[a.jsx(I,{className:e.heading,variant:"h1",children:"Update"}),n.map(([o,l],c)=>a.jsx(EAe,{config:t,onChange:(d,u)=>r([...n.slice(0,c),[d,u],...n.slice(c+1)]),onClickRemove:()=>r(n.filter((d,u)=>c!==u)),only:n.length===1,tableName:s,columnName:o,updateValue:l},c)),a.jsxs(He,{id:"add-column-button",onClick:()=>r([...n,[i,""]]),children:[a.jsx(ca,{style:{marginRight:"15px"}}),a.jsx(I,{children:"Add column"})]})]})};HS.propTypes={classes:A.object.isRequired,config:A.object.isRequired,updates:A.array,onChange:A.func.isRequired,tableName:A.string.isRequired};HS.defaultProps={updates:[]};const TAe=Be(_Ae)(HS),IAe=e=>{let t;switch(typeof e){case"string":t=e.toLocaleLowerCase()==="null"?e:`'${e}'`;break;case"boolean":t=e?"TRUE":"FALSE";break;default:t=e}return t},DAe={builder:{marginBottom:30},heading:{fontSize:16}},vz=({classes:e,config:t,onChange:n,tree:r})=>a.jsxs("div",{children:[a.jsx(I,{className:e.heading,variant:"h1",children:"Where"}),a.jsx(kW,{...t,value:r,onChange:n,renderBuilder:s=>a.jsx("div",{className:e.builder,children:a.jsx("div",{className:"query-builder qb-lite",children:a.jsx(EW,{...s})})})})]});vz.propTypes={classes:A.object.isRequired,tree:A.object.isRequired,config:A.object.isRequired,onChange:A.func.isRequired};const AAe=Be(DAe)(vz),Cz=({active:e,classes:t,config:n,editing:r,first:s,last:i,onChangeRule:o,onClickCancel:l,onClickDelete:c,onClickEdit:d,onClickReorder:u,onClickRun:p,onClickSave:h,onClickToggle:f,rule:g,setRuleConditions:x})=>{const{palette:b}=Re(),[y,v]=m.useState(g),[C,w]=m.useState(!1),[S,E]=m.useState(!1),[k,j]=m.useState(!1),[_,D]=m.useState(),[M,N]=m.useState(!1),[O,R]=m.useState(!1),[L,P]=m.useState(!1),[F,z]=m.useState(!1),[B,W]=m.useState();m.useEffect(()=>{if(!n)return;const Y=Sa.checkTree(Sa.loadFromJsonLogic(g.conditions,n.conditions),n.conditions);W(Y)},[]),m.useEffect(()=>{if(!B)return;const{logic:Y}=Sa.jsonLogicFormat(B,n.conditions);D(Y),o({...g,conditions:Y}),e&&Sa.sqlFormat(B,n.conditions)&&x(Y)},[e,B]);const{id:H,updates:V,table_name:G}=g,X=m.useMemo(()=>V.length>0&&V.every(Y=>Y&&Y.length===2&&!!Y[1]),[V]),K=m.useMemo(()=>!Kn({...g,conditions:_},y),[y,_,g]);if(!B)return null;const ie=g.updates.map(([Y,ae])=>`${Y} = ${IAe(ae)}`).join(", "),le=Sa.sqlFormat(B,n.conditions),ce=ie&&le?le&&`SET ${ie} WHERE ${le}`:a.jsx("em",{children:"Resulting SQL will be shown here"}),J=le&&X,he=g?.id&&!K&&J&&!L&&!O,ne=K&&J&&!L;return a.jsxs(Ka,{className:t.Accordion,expanded:e,children:[a.jsxs(Qa,{classes:{root:t.AccordionSummary,content:t.AccordionSummaryContent,expanded:t.AccordionSummaryExpanded},id:"id"in g?`rule-${g.id}`:"rule-new",children:[a.jsx("span",{className:t.nameSpan,children:a.jsx(I,{className:t.name,children:e?a.jsx("strong",{children:ce}):ce})}),a.jsxs("span",{className:t.right,children:[a.jsx(He,{disabled:r,name:"rule-row-edit",onClick:d,children:a.jsx(Ju,{sx:{fill:r?"grey.300":"secondary.main",height:"20px"}})}),F?a.jsx("div",{style:{marginLeft:21,marginRight:21},children:a.jsx(Ze,{})}):a.jsx(Dn,{checked:g.active,disabled:r,id:`active-toggle-${H||"new-rule"}`,name:"rule-row-toggle",onClick:async()=>{z(!0);const Y={...g,active:!g.active};await f(Y),v(Y),z(!1)}}),a.jsxs("div",{className:t.reorderGroup,style:{opacity:r?.2:1},children:[M&&a.jsx("div",{style:{marginLeft:2},children:a.jsx(Ze,{})}),!s&&!M&&a.jsx(He,{disabled:r,id:`reorder-up-${H||"new-rule"}`,name:"rule-row-reorder-up",onClick:async()=>{N(!0),await u(-1),N(!1)},children:a.jsx(Qv,{size:20})}),!i&&!M&&a.jsx(He,{disabled:r,id:`reorder-down-${H||"new-rule"}`,name:"rule-row-reorder-down",onClick:async()=>{N(!0),await u(1),N(!1)},children:a.jsx(vs,{size:20})})]}),k?a.jsx("div",{style:{marginRight:11},children:a.jsx(Ze,{})}):a.jsxs(a.Fragment,{children:[a.jsx(He,{disabled:r,id:"delete-button",style:{marginRight:10},onClick:()=>!r&&w(!0),children:a.jsx(Xr,{color:r?b.action.disabled:b.secondary.main,size:20})}),a.jsx(mt,{acceptLabel:"DELETE RULE",bodyText:"You are about to delete a rule.",handleAccept:async()=>{j(!0),await c(),j(!1),w(!1)},handleClose:()=>w(!1),open:C,title:"Are you sure?"})]})]})]}
270),a.jsx(Ja,{className:t.AccordionDetails,children:e&&a.jsxs(a.Fragment,{children:[a.jsx(TAe,{config:n,onChange:Y=>o({...g,updates:Y}),tableName:G,updates:V}),a.jsx(AAe,{config:n.conditions,onChange:Y=>{W(Y)},tree:B}),a.jsxs("div",{className:t.buttons,children:[a.jsx(re,{"data-visible":r,disabled:!ne,id:"save-button",onClick:async()=>{P(!0);const Y=await h(g);P(!1);const ae={...g,id:Y};o(ae),v(ae)},variant:"contained",children:L?a.jsx(Ze,{size:24}):"SAVE"}),a.jsx(re,{"data-visible":r,disabled:!he,id:"run-button",onClick:async()=>{R(!0),await p(),R(!1)},variant:"contained",children:O?a.jsx(Ze,{size:24}):"RUN"}),a.jsx("div",{style:{marginTop:10},children:a.jsx(re,{variant:"text",onClick:()=>E(!0),"data-visible":r,id:"cancel-button",sx:{p:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},children:"Cancel"})}),a.jsx(mt,{acceptLabel:"CANCEL EDITING",bodyText:"You are about to lose all edits to this rule.",cancelLabel:"CONTINUE EDITING",handleAccept:()=>{o(y);const Y=Sa.checkTree(Sa.loadFromJsonLogic(y.conditions,n.conditions),n.conditions);W(Y),l(),E(!1)},handleClose:()=>E(!1),open:S,title:"Are you sure?"})]})]})})]})};Cz.propTypes={active:A.bool.isRequired,classes:A.object.isRequired,config:A.object.isRequired,editing:A.bool.isRequired,first:A.bool.isRequired,last:A.bool.isRequired,onChangeRule:A.func.isRequired,onClickCancel:A.func.isRequired,onClickDelete:A.func.isRequired,onClickEdit:A.func.isRequired,onClickReorder:A.func.isRequired,onClickRun:A.func.isRequired,onClickSave:A.func.isRequired,onClickToggle:A.func.isRequired,rule:A.object.isRequired,setRuleConditions:A.func.isRequired};const MAe=Be(wAe)(Cz),RAe=(e,t,n)=>{let r=t,s=n;const{length:i}=e;r<0?r=0:r>=i&&(r=i-1),s<0?s=0:s>=i&&(s=i-1);const o=[...e];return o.splice(s,0,o.splice(r,1)[0]),o},Tb=e=>{const t=e.updates.reduce((n,[r,s])=>({...n,[r]:typeof s=="string"&&s.toLocaleLowerCase()==="null"?null:s}),{});return{id:e.id,rule:{...e,updates:t}}},NAe=e=>({button:{marginBottom:30},heading:{fontSize:16,marginBottom:16},note:{marginBottom:16,width:720},subheading:{fontSize:16,fontWeight:"bold",marginBottom:11},root:{paddingRight:30},rules:{borderBottom:`1px solid ${e.palette.divider}`,borderTop:`1px solid ${e.palette.divider}`}}),OAe={mr_media_stage:"Placements",mr_creative_stage:"Creatives",mr_media_creative:"Brands"},wz=({classes:e,onRunRule:t,setRuleConditions:n,tableName:r})=>{const i=Re().palette.mode==="dark",{engagementNiceId:o}=pe(),{data:l=[],isFetching:c}=$a({apiName:"mediaResolution",endpoint:"GetRules",parameters:{queryStringParameters:{engagement_nice_id:o,table_name:r}}}),{data:d,isFetching:u,isUninitialized:p}=$a({apiName:"mediaResolution",endpoint:"GetRuleConfig",parameters:{queryStringParameters:{table_name:r}}}),[h]=Qi(),[f]=Qi(),[g]=lW(),[x]=Qi(),[b]=gu(),[y,v]=m.useState(null),[C,w]=m.useState([]),[S,E]=m.useState(!1),k=c||u||p,j=m.useMemo(()=>d?{...d,conditions:CAe({customConfig:d.conditions,engagementNiceId:o,lazyAwsApiRead:b,tableName:r})}:{},[o,b,d,r]);m.useEffect(()=>{if(!l?.length)return;const N=[...l].sort(({rank:O},{rank:R})=>O-R).map(O=>({...O,updates:Object.entries(O.updates)}));w(N)},[l]);const _=m.useCallback(async(N,O)=>{const R=N,L=N+O,P=RAe(C,R,L);for(let z=0;z<P.length;z+=1)P[z].rank=z;const F=P.map(Tb).map(({id:z,rule:B})=>g({engagementNiceId:o,id:z,rule:B}));await Promise.all(F),w(P)},[o,C,g]),D=m.useCallback(async N=>{const{id:O,rule:R}=Tb(N);let L=O;return O?(await g({engagementNiceId:o,id:O,rule:R}),n(R.conditions)):L=await h({apiName:"mediaResolution",endpoint:"CreateRule",parameters:{body:{...R,engagement_nice_id:o}}}).unwrap(),E(!1),L},[h,o,n,g]),M=(y??-1)>=0;return a.jsxs("div",{className:`${e.root} ${i?"query-builder-dark":""}`,children:[a.jsx(I,{className:e.heading,variant:"h1",children:OAe[r]}),a.jsxs(I,{className:e.note,children:[a.jsx("strong",{children:"NOTE:Â "}),"Select rows, edit and column filters will be disabled while creating rules.",a.jsx("br",{}),a.jsx("br",{}),"Once rules have been run or set to ON, you can go back to name cleaning functions where you will see the rules you applied. Go back to rules creation to edit, run, toggle ON/OFF or delete rules.",a.jsx("br",{}),a.jsx("br",{}),"Please note after rules are run manually or automatically there may be touchpoints that need approval."]}),k?a.jsx(Ze,{}):a.jsxs(a.Fragment,{children:[a.jsx(re,{className:e.button,disabled:S||M,id:"create-rule-button",onClick:()=>{const N={active:!1,conditions:{and:[]},engagement_nice_id:o,rank:C.length>0?C[C.length-1].rank+1:0,table_name:r,updates:[]};w([...C,N]),v(C.length),E(!0)},variant:"contained",children:"CREATE RULE"}),C.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(I,{className:e.subheading,variant:"h2",children:"Rules"}),a.jsx("div",{className:e.rules,id:"rules-table",children:C.map((N,O)=>a.jsx(MAe,{active:O===y,editing:S||M,config:j,first:O===0,last:O===C.length-1,onChangeRule:R=>w([...C.slice(0,O),R,...C.slice(O+1)]),onClickCancel:()=>{v(null),E(!1),"id"in N||w(C.slice(0,-1)),n(null)},onClickDelete:async()=>{await f({apiName:"mediaResolution",endpoint:"DeleteRule",parameters:{pathParameters:{id:N.id},queryStringParameters:{engagement_nice_id:o}}});const R=[...C];R.splice(O,1),w(R)},onClickEdit:()=>{v(O)},onClickReorder:R=>_(O,R),onClickRun:async()=>{const R=x({apiName:"mediaResolution",endpoint:"RunRule",parameters:{pathParameters:{id:N.id},body:{engagement_nice_id:o}}});v(null),await R,t()},onClickSave:D,onClickToggle:async R=>{const{id:L,rule:P}=Tb(R);await g({engagementNiceId:o,id:L,rule:P}),w([...C.slice(0,O),{...R},...C.slice(O+1)])},rule:N,setRuleConditions:n},N.id))})]})]})]})};wz.propTypes={classes:A.object.isRequired,onRunRule:A.func.isRequired,setRuleConditions:A.func.isRequired,tableName:A.string.isRequired};const PAe=Be(NAe)(wz),LAe=()=>({container:{display:"flex",flexDirection:"column",margin:"30px 15px 0px 15px",paddingBottom:30,overflowX:"hidden"},heading:{fontSize:16,padding:0},paginatorSpinner:{width:"100%",display:"flex",alignItems:"center",justifyContent:"flex-end",marginTop:20,marginRight:20},rulesListContainer:{marginBottom:12},table:{overflow:"hidden",tableLayout:"fixed"},tableWrapper:{overflow:"scroll",width:"100%"}}),Sz=({classes:e,tableName:t})=>{const{columnDefinitions:n,defaultColumnVisibility:r,headerName:s}=B$[t],{engagementNiceId:i}=pe(),[o,l]=m.useState(r),[c,d]=m.useState(0),[u,p]=m.useState(25),[h,f]=m.useState(null),g=m.useMemo(()=>{const k=Object.entries(o).filter(([,_])=>_).map(([_])=>_);let j;return t===rn.BRAND?j={engagement_nice_id:i,page_offset:c,page_size:u,views:["view_all"],visible_columns:k}:j={offset:c*u,rowsPerPage:u,visibleColumns:k},h&&(j.rule=h),j},[o,c,i,u,h,t]),{count:x,countFetching:b,placements:y,placementsFetching:v,refetch:C}=pS({body:g,engagementNiceId:i,tableName:t}),w=m.useMemo(()=>Math.ceil(x/u),[x,u]),S=m.useMemo(()=>{const k=n.filter(({alwaysOn:M,data:N})=>o[N]||M).map(({width:M})=>M).reduce((M,N)=>M+N,0),j=Hn.RULES.FIRST_COLUMN+Hn.RULES.SECOND_COLUMN+k,_=1180,D=_-Hn.RULES.FIRST_COLUMN-Hn.RULES.SECOND_COLUMN;return j<_?D/k:1},[n,o]),E=m.useMemo(()=>y.map((k,j)=>{switch(t){case rn.BRAND:return a.jsx(cAe,{columnDefinitions:n,columnVisibility:o,even:!!(j%2),rowData:k},k.id);case rn.CREATIVE:return a.jsx(dAe,{columnDefinitions:n,columnVisibility:o,even:!!(j%2),creative:k},k.id);case rn.PLACEMENT:default:return a.jsx(uAe,{cellWidthScalingFactor:S,columnDefinitions:n,columnVisibility:o,even:!!(j%2),placement:k},k.id)}}),[S,n,o,y,t]);return a.jsxs("div",{className:e.container,children:[a.jsx("div",{className:e.rulesListContainer,children:a.jsx(PAe,{onRunRule:C,setRuleConditions:f,tableName:t})}),a.jsx(aAe,{columnDefinitions:n,columnVisibility:o,onChangeColumnVisibility:(k,j)=>{l({...o,[k]:j})},placements:y}),a.jsx("div",{className:e.tableWrapper,children:a.jsxs(Ki,{className:e.table,id:"name-cleaning-placements-table",children:[a.jsx(Ya,{children:a.jsx(lAe,{cellWidthScalingFactor:S,columnDefinitions:n,columnVisibility:o,title:s})}),a.jsx(xl,{id:"nc-table-body",children:v?null:E})]})}),v&&a.jsx("div",{style:{marginTop:40,textAlign:"center",width:"100%"},children:a.jsx(Ze,{size:24})}),b?a.jsx("div",{className:e.paginatorSpinner,children:a.jsx(Ze,{size:18})}):a.jsx(Qw,{controlPageSizeBool:!0,currentPage:c,onChangePageSize:k=>{d(0),p(k)},onGoBackward:()=>{c>0&&d(k=>k-1)},onGoForward:()=>{c<w-1&&d(k=>k+1)},pageSize:u,total:x})]})};Sz.propTypes={classes:A.object.isRequired,tableName:A.string.isRequired};const FAe=Be(LAe)(Sz),$Ae=()=>({container:{marginLeft:22,marginTop:32},span:{fontWeight:"normal",fontSize:16,width:120},spanBold:{fontWeight:"bold",fontSize:16,width:120}}),jz=({classes:e,tableName:t})=>{const[n,r]=m.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsx(I,{component:"div",className:e.container,children:a.jsxs(td,{component:"label",container:!0,alignItems:"center",spacing:1,children:[a.jsx("span",{id:"name-cleaning-span",className:n?e.span:e.spanBold,children:"Name Cleaning"}),a.jsx("span",{id:"switch-span",children:a.jsx(Dn,{checked:n,id:"name-cleaning-view-switch",onChange:()=>r(!n)})}),a.jsx("span",{id:"rules-span",className:n?e.spanBold:e.span,children:"Rules Creation"})]})}),n?a.jsx(FAe,{tableName:t}):t===rn.BRAND?a.jsx(SDe,{}):a.jsx(nAe,{tableName:t})]})};jz.propTypes={classes:A.object.isRequired,tableName:A.string.isRequired};const Ib=Be($Ae)(jz),zAe=["ATTRIBUTES","PLACEMENTS","CREATIVES","BRANDS"],BAe=()=>{const{mpTrack:e}=tr(),[t,n]=m.useState("0");return m.useEffect(()=>{e("DASHBOARDADMIN NAMECLEANING ACTIONS",{actionType:"TAB VISIT",currentTab:zAe[t]})},[t,e]),a.jsx(T,{sx:{minWidth:1e3,width:ks},children:a.jsxs(co,{value:t,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default"},children:a.jsxs(uo,{onChange:(r,s)=>n(s),variant:"fullWidth",children:[a.jsx(_n,{id:"attributes-tab",label:"Attributes",value:"
2700"}),a.jsx(_n,{id:"placements-tab",label:"Placements",value:"1"}),a.jsx(_n,{id:"creatives-tab",label:"Creatives",value:"2"}),a.jsx(_n,{id:"brands-tab",label:"Brands",value:"3"})]})}),a.jsx(xt,{sx:{p:0},value:"0",children:a.jsx(PIe,{})}),a.jsx(xt,{sx:{p:0},value:"1",children:a.jsx(Ib,{tableName:rn.PLACEMENT})}),a.jsx(xt,{sx:{p:0},value:"2",children:a.jsx(Ib,{tableName:rn.CREATIVE})}),a.jsx(xt,{sx:{p:0},value:"3",children:a.jsx(Ib,{tableName:rn.BRAND})})]})})},UAe={ASC:"ASC",DESC:"DESC",NONE:"NONE"},kz=25,Rh=[5,10,25,50,100],$r="internal",va="external",_a={INTERNAL_USERS_TABLE:"0",EXTERNAL_USERS_TABLE:"1"},VAe={status:[{label:"Active",checked:!0},{label:"Inactive",checked:!0}]},Ez=Rd.filter(e=>e.startsWith("InternalRoles")),cm=Rd.filter(e=>e.startsWith("CustomerRoles")),WAe=e=>UD(e).replace("-"," -").trim(),uD=(e=[],t=[])=>{if(e.length!==t.length)return!0;const n=Array.from(new Set([...e,...t]));return e.length!==n.length||t.length!==n.length},Fa=(e=[])=>e.map(t=>({label:WAe(t),value:t})),HAe=(e=[])=>e.map(t=>({label:t,value:parseInt(t,10)})),Nv=(e=[])=>e.map(t=>t.value),Ca=m.createContext(null),qS=({children:e,initialStore:t})=>{const n=ct(),{clientId:r,engagementNiceId:s}=pe(),{userIsInternal:i=t.internalUserBool}=gt(),{data:o=t.agencyOptions}=yC({engagementNiceId:s}),{data:l=t.externalEngagementOptions}=Nd({body:{client_id:r}}),{data:c=t.engagementOptions}=Nd({body:{}},{skip:!i}),{data:d=t.usersInternal,isLoading:u=t.loadingInt,isFetching:p=t.loadingInt}=cW({internalBool:!0,clientId:r},{skip:!i}),{data:h=t.usersExternal,isLoading:f=t.loadingExt,isFetching:g=t.loadingExt}=dW({internalBool:!1,clientId:r}),{data:x=t.clientOptions}=uW({body:{}},{skip:!i}),[b,y]=m.useState(t.activeTab),v=l?.length>0,[C,w]=m.useState(t.internalEngagementOptions),[S,E]=m.useState(t.filterUserOptions),k=()=>c.map(_=>{const D=x.findIndex(N=>N.id===_.client_id),M=D!==-1?`${x[D].name} - `:"";return{..._,label:`${M}${_.brand_name} - ${_.id}`,value:_.id}}).sort((_,D)=>_.label.localeCompare(D.label));m.useEffect(()=>{c?.length>0&&x?.length>0&&w(k())},[c,x]);const j={isMounted:n,activeTab:b,agencyOptions:o,setActiveTab:y,clientHasEngagements:v,clientOptions:x,fetchingExt:g,fetchingInt:p,externalEngagementOptions:l,internalUserBool:i,internalEngagementOptions:C,setInternalEngagementOptions:w,engagementOptions:c,filterUserOptions:S,setFilterUserOptions:E,mapEngagementsToClientsForDisplay:k,usersInternal:d,usersExternal:h,loadingExt:f,loadingInt:u};return a.jsx(Ca.Provider,{value:j,children:e})};qS.propTypes={children:A.node.isRequired,initialStore:A.object};qS.defaultProps={initialStore:{activeTab:_a.EXTERNAL_USERS_TABLE,agencies:[],agencyOptions:[{value:null,label:"None"}],clientHasEngagements:!1,clientOptions:[],engagementOptions:[],externalEngagementOptions:[],filterUserOptions:VAe,internalUserBool:!1,internalEngagementOptions:[],loadingExt:!1,loadingInt:!1,usersExternal:[],usersInternal:[]}};const ni=m.createContext(null),qAe=e=>{try{return kC(e)||null}catch{return null}},Tg=({children:e,initialStore:t})=>{const[n,r]=m.useState(t.agency),[s,i]=m.useState(t.agencyEditMade),[o,l]=m.useState(t.autofillUsername),[c,d]=m.useState(t.disableAdd),[u,p]=m.useState(t.editing),[h,f]=m.useState(t.email),[g,x]=m.useState(t.emailEditMade),[b,y]=m.useState(t.emailError),[v,C]=m.useState(t.emailHasError),[w,S]=m.useState(t.engagements),[E,k]=m.useState(t.engagementsEditMade),[j,_]=m.useState(t.firstName),[D,M]=m.useState(t.firstNameEditMade),[N,O]=m.useState(t.hasErrors),[R,L]=m.useState(t.lastName),[P,F]=m.useState(t.lastNameEditMade),[z,B]=m.useState(t.loading),[W,H]=m.useState(t.phoneNumber),[V,G]=m.useState(t.phoneNumberEditMade),[X,K]=m.useState(t.roles),[ie,le]=m.useState(t.rolesEditMade),[ce,J]=m.useState(t.saving),[he,ne]=m.useState(t.statusEditMade),[Y,ae]=m.useState(t.username),[je,me]=m.useState(t.usernameError),[ve,Me]=m.useState(t.usernameHasError),de={agency:n,agencyEditMade:s,autofillUsername:o,buildBodyInitObject:()=>{const ke={};return D&&(ke.first_name=j),P&&(ke.last_name=R),g&&(ke.email=h),V&&(ke.phone_number=W?.number||""),ie&&(ke.groups=X),E&&(ke.engagements=w),s&&(ke.row_access=n),{body:ke}},buildStatusInitObject:ke=>{const Le={};return he&&(Le.username=ke.user_name||"Null",Le.disabled=!ke.disabled_by),{body:Le}},disableAdd:c,checkForBlankNames:()=>D&&!j||P&&!R,checkIsAgencyUser:ke=>ke===va&&X.indexOf("CustomerRoles-AgencyUser")>-1,editing:u,email:h,emailEditMade:g,emailError:b,emailHasError:v,engagements:w,engagementsEditMade:E,firstName:j,firstNameEditMade:D,hasEditBeenMade:()=>s||g||D||P||V||E||ie,hasErrors:N,lastName:R,lastNameEditMade:P,loading:z,phoneNumber:W,phoneNumberEditMade:V,resetUserFormVariables:()=>{r(t.agency),i(t.agencyEditMade),l(t.autofillUsername),d(t.disableAdd),f(t.email),x(t.emailEditMade),y(t.emailError),C(t.emailHasError),S(t.engagements),k(t.engagementsEditMade),_(t.firstName),M(t.firstNameEditMade),O(t.hasErrors),L(t.lastName),F(t.lastNameEditMade),B(t.loading),H(t.phoneNumber),G(t.phoneNumberEditMade),K(t.roles),le(t.rolesEditMade),J(t.saving),ne(t.
270statusEditMade),ae(t.username),me(t.usernameError),Me(t.usernameHasError)},roles:X,rolesEditMade:ie,saving:ce,statusEditMade:he,username:Y,usernameError:je,usernameHasError:ve,setAgency:r,setAgencyEditMade:i,setAutofillUsername:l,setCurrentUserToForm:ke=>{r(ke.row_access||null),f(ke.email||""),S(ke.engagements||[]),_(ke.first_name||""),L(ke.last_name||""),H(qAe(ke.phone_number)),K(ke.groups||[]),ae(ke.user_name||"")},setDisableAdd:d,setEditing:p,setEmail:f,setEmailEditMade:x,setEmailError:y,setEmailHasError:C,setEngagements:S,setEngagementsEditMade:k,setFirstName:_,setFirstNameEditMade:M,setHasErrors:O,setLastName:L,setLastNameEditMade:F,setLoading:B,setPhoneNumber:H,setPhoneNumberEditMade:G,setRoles:K,setRolesEditMade:le,setSaving:J,setStatusEditMade:ne,setUsername:ae,setUsernameError:me,setUsernameHasError:Me};return a.jsx(ni.Provider,{value:de,children:e})};Tg.propTypes={children:A.node.isRequired,initialStore:A.object};Tg.defaultProps={initialStore:{agency:null,agencyEditMade:!1,autofillUsername:!0,disableAdd:!0,editing:null,email:"",emailEditMade:!1,emailError:"Enter user's email information.",emailHasError:!1,engagements:[],engagementsEditMade:!1,firstName:"",firstNameEditMade:!1,hasErrors:!1,lastName:"",lastNameEditMade:!1,loading:!1,phoneNumber:null,phoneNumberEditMade:!1,roles:[],rolesEditMade:!1,saving:!1,statusEditMade:!1,username:"",usernameError:"",usernameHasError:!1}};const GS=({disabled:e,internalUserBool:t,onClickCreate:n,variant:r})=>{m.useEffect(()=>{},[]);let s="Add a User";return r===$r?s="Add Internal User":r!==$r&&t&&(s="Add External User"),a.jsx(re,{sx:{height:"40px",marginTop:"30px",marginRight:"15px"},color:"primary",id:"create-user-button",onClick:()=>{n()},variant:"contained",disabled:r===va&&e,children:s})};GS.propTypes={disabled:A.bool,internalUserBool:A.bool.isRequired,onClickCreate:A.func.isRequired,variant:A.string.isRequired};GS.defaultProps={disabled:!1};const YS=Ne.forwardRef(({disabled:e,error:t,errorText:n,filterFunction:r,id:s,items:i,onChange:o,placeholder:l,searchTerm:c,width:d,...u},p)=>a.jsx(T,{sx:{paddingBottom:"10px",paddingLeft:"15px",paddingRight:"15px"},ref:p,...u,children:a.jsx(De,{sx:{pointerEvents:e?"none":"inherit"},disabled:e,error:t,width:d,helperText:t&&n,InputProps:{id:`${s}-search-input`,endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{size:20})})},onChange:({target:h})=>{const{value:f}=h,g=f===""?i:i.filter(x=>r(x,f));o(g,f)},placeholder:l,style:{width:d},value:c,auocomplete:"off",type:"search",margin:"none",variant:"standard"})}));YS.propTypes={disabled:A.bool,error:A.bool,errorText:A.string,id:A.string.isRequired,items:A.array,onChange:A.func,placeholder:A.string,filterFunction:A.func,searchTerm:A.string,width:A.number};YS.defaultProps={disabled:!1,error:!1,errorText:"",items:[],onChange:()=>{},placeholder:"Search",filterFunction:(e,t)=>e!==t,width:300,searchTerm:""};const su=({disabled:e,id:t,filterFunction:n,onSelect:r,items:s,label:i,multipleText:o,onChangeSearch:l,placeholder:c,searchable:d,value:u,width:p,menuWidth:h})=>{const[f,g]=m.useState(s),[x,b]=m.useState(""),y=s?.length||0,v=(S,E)=>{const k=Array.from(new Set([...S.map(j=>j.value),...E.map(j=>j.value)]));return k.length===S.length&&k.length===E.length},C=d&&a.jsx(YS,{filterFunction:n,width:h-50,id:`${t}-search-input`,items:s,onChange:(S,E)=>{g(S),b(E),l(E)},searchTerm:x}),w=i?a.jsx(wt,{id:`${t}-input-label`,sx:{color:e?"text.disabled":"inherit"},shrink:!0,children:i}):null;return a.jsxs(Qe,{style:{minWidth:p,maxWidth:p},children:[w,a.jsxs(tt,{displayEmpty:!0,disabled:e,SelectDisplayProps:{id:`multiple-select-${t}`},MenuProps:{PaperProps:{id:`${t}-list`,style:{marginTop:10,maxHeight:224,maxWidth:h}},disableAutoFocusItem:!0,TransitionProps:{onExited:()=>{b(""),g(s)}}},inputProps:{sx:{"&.Mui-disabled":{WebkitTextFillColor:"text.default"}}},sx:{"& .MuiSelect-select":{color:"text.default"}},multiple:!0,renderValue:S=>{let E=c;if(S.length===s.length&&s.length!==1)E="All";else if(S.length>1)E=`(${S.length}) ${o}`;else if(S.length===1){const k=s.findIndex(j=>j.value===S[0]);[E]=k===-1?S:[s[k].label]}return a.jsx(T,{sx:{color:E==="Select"?"text.secondary":"text.default",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",width:`${p-30}px`},title:E,children:E})},value:u?.map(S=>S.value)||[],variant:"standard",children:[y>1&&a.jsx(Se,{sx:{padding:0},children:a.jsxs(He,{id:`multiple-select-${t}-select-all-button`,onClick:()=>{const S=u.length===f.length&&v(u,f)?[]:[...f];r(S)},children:[a.jsx(et,{checked:u.length===f.length&&f.length!==0&&v(u,f)}),a.jsx(Kt,{primary:"Select all"})]})}),d&&y>5&&a.jsx(Se,{id:"multiple-select-search-item",sx:{padding:0},children:C}),f.map(({label:S,value:E})=>a.jsx(Se,{sx:{padding:0},children:a.jsxs(He,{id:`multiple-select-${t}-${vM(E)}`,onClick:()=>{const k=[...u];let j=k.findIndex(_=>_.value===E);j!==-1?k.splice(j,1):(j=f.findIndex(_=>_.value===E),k.push(f[j]),k.sort((_,D)=>_.label.localeCompare(D.label))),r(k)}
270,children:[a.jsx(et,{checked:u.findIndex(k=>k.value===E)!==-1}),a.jsx(Kt,{sx:{textAlign:"left"},primary:S,primaryTypographyProps:{title:S}})]})},`view-option-${E}`))]})]})};su.defaultProps={filterFunction:(e,t)=>{const{label:n=""}=e||{};return n.toLowerCase().includes(t.toLowerCase())},disabled:!1,label:"",multipleText:"Multiple",onChangeSearch:()=>{},onSelect:()=>{},placeholder:"Select",items:[],searchable:!1,value:[],width:300,menuWidth:300};su.propTypes={disabled:A.bool,id:A.string.isRequired,filterFunction:A.func,label:A.string,multipleText:A.string,onChangeSearch:A.func,onSelect:A.func,placeholder:A.string,items:A.array,searchable:A.bool,value:A.array,width:A.number,menuWidth:A.number};const Ov="x",Pv=e=>e.length?e.startsWith("+")?e:`+${e}`:"",_z=e=>e.startsWith("+")?e.slice(1):e,pD=e=>{try{return _z(e?.formatInternational())}catch{return""}},GAe=e=>{if(!e.length)return Ov;const t=new cM;return t.input(Pv(e)),`${t.getTemplate().slice(1)}${Ov}`},Tz=m.forwardRef(({value:e,...t},n)=>a.jsx(qU,{isAllowed:({value:r})=>r.length<=15,format:GAe(e),getInputRef:n,patternChar:Ov,value:e,...t}));Tz.propTypes={value:A.string.isRequired};const KS=({allowEmpty:e=!1,onBlur:t,phoneObj:n=null,setPhoneObj:r,...s})=>{const[i,o]=m.useState(pD(n)),[l,c]=m.useState(!1),d=({target:{value:p}})=>{let h;try{h=kC(Pv(p))}catch{h=null}const f=h?.isPossible(),g=f?h:null;e&&!p.length||f?(t&&t(g),r(g),c(!1)):(o(pD(n)),c(!0))},u=({target:{value:p}})=>{const h=new cM;h.input(Pv(p)),o(_z(h.getChars()))};return a.jsx(De,{error:l,helperText:l&&"Invalid number",InputProps:{inputComponent:Tz,startAdornment:a.jsx("span",{children:"+"})},onBlur:d,onChange:u,value:i,variant:"standard",...s})};KS.propTypes={allowEmpty:A.bool,onBlur:A.func,phoneObj:A.object,setPhoneObj:A.func.isRequired};const Iz=({variant:e})=>{const{agencyOptions:t,externalEngagementOptions:n,internalEngagementOptions:r}=m.useContext(Ca),{agency:s,checkIsAgencyUser:i,email:o,emailError:l,emailHasError:c,engagements:d,firstName:u,lastName:p,phoneNumber:h,roles:f,username:g,usernameError:x,usernameHasError:b,setAgency:y,setAutofillUsername:v,setRoles:C,setFirstName:w,setHasErrors:S,setLastName:E,setUsername:k,setEmail:j,setEmailError:_,setEmailHasError:D,setEngagements:M,setPhoneNumber:N,setUsernameError:O,setUsernameHasError:R}=m.useContext(ni),[L]=hC();m.useEffect(()=>{if(e!==$r&&n.length===1){const[z={}]=n;M([{...z}])}},[n,M,e]),m.useEffect(()=>{S(c||b)},[c,b,S]);const P=()=>{u&&p||g?L({parameter:"username",value:g}).then(({data:z})=>{const{error:B}=z||{};B?(O(B),R(!0)):(O(""),R(!1))}):(O(""),R(!1))},F=e===$r?r:n;return a.jsxs(T,{sx:{display:"flex",flexDirection:"column",width:"300px"},children:[a.jsx(T,{sx:{marginBottom:"10px",marginTop:"10px"},children:a.jsx(De,{id:"user-first-name-text-input",value:u,label:"First name",onChange:({target:z})=>{const{value:B}=z,W=B&&B.length>0;w(W?B:"")},onBlur:({target:z})=>{const B=z.value.trim();B!==""&&u!==B&&w(B),P()},inputProps:{maxLength:75},fullWidth:!0,size:"small"})}),a.jsx(T,{sx:{marginBottom:"10px",marginTop:"10px"},children:a.jsx(De,{id:"user-last-name-text-input",value:p,label:"Last name",onChange:({target:z})=>{const{value:B}=z,W=B&&B.length>0;E(W?B:"")},onBlur:({target:z})=>{const B=z.value.trim();B!==""&&p!==B&&E(B),P()},inputProps:{maxLength:75},fullWidth:!0,size:"small"})}),a.jsx(T,{sx:{marginBottom:"10px",marginTop:"10px"},children:a.jsx(De,{id:"user-email-text-input",error:c,helperText:c?l:"",value:o,label:"Email",type:"email",onChange:({target:z})=>{j(z.value),_("Enter user's email information."),D(!1)},onBlur:({target:z})=>{const{value:B}=z;B&&B.length>0?L({parameter:"email",value:B}).then(({data:H})=>{const{error:V=null}=H||{};V?(_(V),D(!0)):j(B)}):(j(""),D(!1))},inputProps:{maxLength:75},fullWidth:!0,size:"small"})}),a.jsx(T,{sx:{marginBottom:"10px",marginTop:"10px"},children:a.jsx(KS,{allowEmpty:!0,fullWidth:!0,label:"Mobile phone (optional)",phoneObj:h,setPhoneObj:N})}),a.jsx(T,{sx:{marginBottom:"10px",marginTop:"10px"},children:a.jsx(De,{id:"username-text-input",error:b,helperText:b?x:"",value:g,label:"Username",onChange:({target:z})=>
270{v(!1),k(z.value)},onBlur:P,inputProps:{maxLength:75,pattern:"^[a-zA-Z1-9\\.\\._\\-]*$"},fullWidth:!0,size:"small"})}),a.jsx(T,{sx:{marginTop:"15px"},children:a.jsx(su,{width:300,id:"user-roles-select",placeholder:"",items:Fa(e===$r?[...Ez,...cm]:cm),label:"Role(s)",multipleText:"Roles",searchable:!0,onSelect:z=>C(Nv(z)),value:Fa(f)})}),i(e)&&a.jsx(T,{sx:{marginTop:"18px"},children:a.jsx(kg,{width:300,id:"user-agency-select",placeholder:"Agency name",items:t,label:"Row level access (optional)",onChange:y,value:s,searchable:t?.length>5,showSearchAdornment:!0,renderValue:()=>t.find(z=>z.value===s)?.label||"None"})}),a.jsx(T,{sx:{marginTop:"18px"},children:a.jsx(su,{width:300,disabled:F.length===1,id:"user-engagement-select",placeholder:"",items:F,label:"Engagements",multipleText:"Engagements",searchable:!0,onSelect:M,value:d})})]})};Iz.propTypes={variant:A.string.isRequired};const Dz=({open:e,onClickCancel:t,onClickConfirm:n,variant:r})=>{const{internalUserBool:s}=m.useContext(Ca)||{},{agency:i,autofillUsername:o,disableAdd:l,email:c,engagements:d,firstName:u,hasErrors:p,lastName:h,loading:f,phoneNumber:g,roles:x,username:b,resetUserFormVariables:y,setDisableAdd:v,setLoading:C,setUsername:w}=m.useContext(ni),[S]=IA(),{mpTrack:E}=tr();m.useEffect(()=>{o&&(u.trim()||h.trim()?w(`${u}.${h}`.replace(/[^a-zA-Z0-9._]/g,"").toLowerCase()):w(""))},[u,h]),m.useEffect(()=>{v(p||x.length<1||d<1||!c||!u||!h||!b)},[u,h,c,d,x,p,v,b]);let k="Create a user";return r===$r?k="Create an internal user":r!==$r&&s&&(k="Create an external user"),a.jsxs(yt,{PaperProps:{id:"create-user-form"},open:e,disableEnforceFocus:!0,children:[a.jsxs(T,{sx:{paddingTop:"20px",paddingLeft:"20px",display:"flex",flexDirection:"row",justifyContent:"space-between"},children:[a.jsx(vt,{sx:{fontSize:"20px",fontWeight:"500"},variant:"body1",children:k}),a.jsx(ji,{sx:{marginRight:"28px"},onClick:()=>{t(),y()}})]}),a.jsx(Ct,{sx:{paddingBottom:"20px",paddingLeft:"20px",width:"480px"},children:a.jsx(Iz,{variant:r})}),a.jsxs(un,{sx:{justifyContent:"flex-end",paddingLeft:"15px"},children:[a.jsx(re,{sx:{marginBottom:"20px"},id:"create-user-form-cancel-button",variant:"outlined",onClick:()=>{t(),y()},children:"Cancel"}),a.jsx(re,{sx:{marginRight:"20px",marginBottom:"20px",height:"40px"},id:"create-user-form-confirm-button",disabled:l,onClick:()=>{C(!0);const j={is_employee:r===$r,email:c,first_name:u,last_name:h,phone_number:g?.number||null,groups:x,username:b,engagements:d.map(_=>_.id)};i&&(j.row_access=i),E("DASHBOARDADMIN USERMANAGEMENT ACTIONS",{actionType:"CREATE USER",userEdited:j||{}}),S(j).then(({data:_})=>{_?console.log("error creating user:: ",_):(n(),y())}).catch(()=>{console.log("error creating user:: ")}).finally(()=>{C(!1)})},variant:"contained",children:f?a.jsx(T,{sx:{margin:"0px 0px 0px 0px"},children:a.jsx(Ze,{color:"inherit",size:30})}):a.jsx("span",{id:"create-user-add-button-span",children:"ADD"})})]})]})};Dz.propTypes={onClickCancel:A.func.isRequired,onClickConfirm:A.func.isRequired,open:A.bool.isRequired,variant:A.string.isRequired};const QS=({onChangeView:e,pageSize:t})=>{const[n,r]=m.useState(t),s=a.jsx(I,{variant:"body1",sx:{marginRight:"12px",marginBottom:"10px"},children:"Rows per page"}),i=Rh.map(l=>a.jsx(Se,{value:l,sx:{fontSize:14,height:"15px"},children:l},l)),o=a.jsx(Qe,{sx:{marginTop:"2px",marginRight:"5px","& div":{"&:focus":{backgroundColor:"transparent"}}},children:a.jsx(tt,{sx:{fontSize:14,"& svg":{paddingBottom:"5px"}},MenuProps:{disableAutoFocusItem:!0,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},PaperProps:{style:{marginTop:-20,maxHeight:150,width:60}}},onChange:l=>{const{target:c}=l,{value:d}=c;r(d),e(d)},value:n,children:i})});return a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"flex-end"},children:[s,o]})};QS.propTypes={onChangeView:A.func.isRequired,pageSize:A.number};QS.defaultProps={pageSize:kz};const JS=({controlPageSizeBool:e,pageSize:t,currentPage:n,total:r,onChangePageSize:s,onGoForward:i,onGoBackward:o})=>{if(r===0)return null;const l=Rh&&Rh.length>0?Rh[0]:5,c=n*t+1;let d=c+t-1;d>r&&(d=r);const u=a.jsx(QS,{onChangeView:s,pageSize:t});return a.jsxs(T,{sx:{alignItems:"center",display:"flex",justifyContent:"flex-end",marginTop:"10px"},children:[e&&r>l?u:null,a.jsx(I,{children:`${c}-${d} of ${r}`}),a.jsx(He,{onClick:o,children:a.jsx(GU,{})}),a.jsx(He,{onClick:i,children:a.jsx(YU,{})})]})};JS.propTypes={onChangePageSize:A.func,onGoBackward:A.func.isRequired,onGoForward:A.func.isRequired,pageSize:A.number.isRequired,controlPageSizeBool:A.bool,currentPage:A.number.isRequired,total:A.number.isRequired};JS.defaultProps={controlPageSizeBool:!1,onChangePageSize:()=>{}};const XS=({disabled:e,placeholder:t,searchText:n,setSearchText:r})=>{const{palette:s}=Re();return a.jsx(T,{sx:{marginLeft:"15px",marginRight:"5px",marginTop:"40px"},children:a.jsx(De,{autoComplete:"off",sx:{"& input":{fontSize:14,overflow:"visible"}
270,"& input::placeholder":{overflow:"visible"}},disabled:e,id:"standard-search",label:"",onChange:({target:i})=>r(i.value.toLowerCase()),placeholder:t,style:{margin:0,width:215},type:"search",value:n,InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{color:s.text.disabled,size:20})})},inputProps:{style:{paddingTop:"12px"}}})})};XS.propTypes={disabled:A.bool,placeholder:A.string,searchText:A.string,setSearchText:A.func.isRequired};XS.defaultProps={disabled:!1,placeholder:"Search name or email or role",searchText:""};const YAe=(e,t,n)=>{const r=e*t;let s=r+t;return s>n.length&&(s=n.length),n.slice(r,s)},KAe=e=>{if(!e)return"N/A";const t=new Date(parseFloat(e)),n=t.getMonth()+1,r=n<10?`0${n}`:`${n}`,s=t.getDate(),i=s<10?`0${s}`:`${s}`,o=t.getFullYear(),l=t.getHours(),c=l>12?`${l-12}`:`${l}`,d=t.getMinutes(),u=d<10?`0${d}`:`${d}`;return`${r}/${i}/${o} 271 272${c}:${u} ${l>12?"PM":"AM"}`},QAe=e=>{let t=e;return e==="user_name"?t="last_name":e==="status"&&(t="disabled_by"),t},JAe=(e,t,n)=>e==="status"?t==="ASC"?(r,s)=>(s[n]===null)-(r[n]===null):(r,s)=>(r[n]===null)-(s[n]===null):t==="ASC"?(r,s)=>r[n]?.localeCompare(s[n]||""):(r,s)=>s[n]?.localeCompare(r[n]||""),XAe=["full_name","user_name","email","groups"],ZAe=(e=[],t="")=>[...e].filter(r=>XAe.map(i=>i==="full_name"&&r.first_name&&r.last_name?r.first_name.concat(" ",r.last_name).toLowerCase().includes(t):i==="groups"&&r[i]?r[i].filter(l=>l.toLowerCase().includes(t.replace(/\s/g,""))).length!==0:r[i]&&r[i].toLowerCase().includes(t)).reduce((i,o)=>i||o,!1)),hD=(e=[],t={})=>{let n=[...e];if(Object.keys(t).length===0)return n;const{status:s}=t;return s.forEach(i=>{const{checked:o=!0,label:l}=i||{},c=l==="Active";o||(n=n.filter(d=>c?d.disabled_by:!d.disabled_by))}),n},Az=[{data:"selected",header:void 0,id:1,width:45,visible:!0,sortable:!1,type:"checked"},{data:void 0,header:"Actions",id:2,width:75,visible:!0,sortable:!1,type:"actions"},{data:"user_name",header:"Name",id:3,width:140,visible:!0,sortable:!0,type:"name"},{data:"email",header:"Email",id:4,width:205,visible:!0,sortable:!0,type:"email"},{data:"phone_number",header:"Mobile",id:5,width:125,visible:!0,sortable:!1,type:"number"},{data:"status",header:"Status",id:6,width:110,visible:!0,sortable:!1,filterable:!0,type:"switch"},{data:"groups",header:"Roles",id:7,width:145,visible:!0,sortable:!1,type:"select"},{data:"clients",header:"Assigned Engagements",id:8,width:130,visible:!0,sortable:!1,type:"select"},{data:"has_tableau_user",header:"Tableau Access",id:9,width:65,visible:!1,sortable:!1,type:"select"},{data:"last_login",header:"Last Login",id:10,width:80,visible:!0,sortable:!0,type:"date"},{data:"deleted",header:void 0,id:11,width:45,visible:!0,sortable:!1,type:"delete"}],Mz=[{data:"selected",header:void 0,id:1,width:45,visible:!0,sortable:!1,type:"checked"},{data:void 0,header:"Actions",id:2,width:75,visible:!0,sortable:!1,type:"actions"},{data:"user_name",header:"Name",id:3,width:140,visible:!0,sortable:!0,type:"name"},{data:"email",header:"Email",id:4,width:150,visible:!0,sortable:!0,type:"email"},{data:"phone_number",header:"Mobile",id:5,width:110,visible:!0,sortable:!1,type:"number"},{data:"status",header:"Status",id:6,width:100,visible:!0,sortable:!1,filterable:!0,type:"switch"},{data:"groups",header:"Roles",id:7,width:140,visible:!0,sortable:!1,type:"select"},{data:"row_access",header:"Row Level Access",id:8,width:140,visible:!0,sortable:!1,type:"select"},{data:"engagements",header:"Assigned Engagements",id:9,width:140,visible:!0,sortable:!1,type:"select"},{data:"last_login",header:"Last Login",id:10,width:80,visible:!0,sortable:!0,type:"date"},{data:"deleted",header:void 0,id:11,width:45,visible:!0,sortable:!1,type:"delete"}],ZS=({children:e,options:t=[],header:n,onCheckFilter:r,onCheckSelectAll:s,width:i})=>{const{palette:o}=Re(),[l,c]=m.useState(null),[d,u]=m.useState(null),p=()=>{c(null)},h=S=>{const{currentTarget:E}=S||{};c(E)},f=Object.keys(t).length,g=!!l,x=t.filter(({label:S})=>d?S.toLocaleLowerCase().includes(d.toLocaleLowerCase()):!0).map(({label:S,checked:E})=>a.jsx(Se,{style:{height:n?.length>35?"inherit":24},children:a.jsx(sn,{sx:{whiteSpace:"normal",wordBreak:"break-word",hyphens:"auto",wordWrap:"break-word",width:"195px"},control:a.jsx(et,{checked:E,onChange:({target:k})=>{const{checked:j}=k||{},_=[...t],D=_.findIndex(M=>M.label===S);_[D].checked=j,r(_)}}),label:S})},S)),b=Object.values(t).every(({checked:S})=>S),y=a.jsx(Se,{children:a.jsx(sn,{control:a.jsx(et,{checked:b,onChange:({target:S})=>s(S.checked)}),label:"Select All"})},"select-all-option"),v=a.jsx(Se,{children:a.jsx(I,{variant:"body1",children:"No Options"})},"select-all-option"),C=a.jsx(De,{InputProps:{endAdornment:a.jsx(Bn,{position:"end",children:a.jsx(er,{size:20,color:o.text.secondary})})},autoComplete:"off",sx:{width:"190px",marginLeft:"10px"},id:"standard-search",margin:"none",onChange:({target:S})=>u(S?.value),placeholder:"Search values",type:"search"}),w=a.jsxs(He,{"aria-controls":"column-picker","aria-haspopup":"true",sx:{alignItems:"center",display:"flex",fontSize:14,fontWeight:"bold",lineHeight:1.14,justifyContent:"start",width:"100%"},id:`${n}-column-selector-button`,onClick:h,children:[a.jsx(T,{sx:{textAlign:"left",marginRight:"5px"},children:e}),a.jsx(KU,{size:16})]});return a.jsxs("div",{style:{width:i},children:[w,a.jsxs(dr,{MenuListProps:{id:`column-filter-${n}`,sx:{border:"1px solid",borderColor:"secondary.main"}},PaperProps:{style:{maxHeight:224,width:160}},anchorEl:l,anchorOrigin:{vertical:"bottom",horizontal:"left"},sx:{border:"solid 1px",borderColor:"secondary.main",top:"10px !important"},disableAutoFocusItem:!0,id:"column-picker",onClose:p,open:g,transformOrigin:{vertical:"top",horizontal:"left"},children:[f>2?y:null,f>5?C:null,f>0?x:v]})]})};ZS.defaultProps={options:{}};ZS.propTypes={children:A.node.isRequired,options:A.oneOfType([A.object,A.array]),header:A.oneOfType([A.object,A.string]).isRequired,width:A.number.isRequired,onCheckFilter:A.func.isRequired,onCheckSelectAll:A.func.isRequired};const{NONE:eMe,ASC:nh,DESC:rh}=UAe,Rz=({children:e,column:t,onClick:n})=>{const[r,s]=m.useState(nh);let i=r===rh?a.jsx(sC,{size:20}):a.jsx(iC,{size:20});
272return t==="last_login"&&(i=a.jsx(fl,{sx:{transform:r===rh?"scaleX(-1)":"scale(-1, -1)"}})),a.jsx(T,{sx:{width:"100%"},children:a.jsxs(He,{sx:{alignItems:"center",display:"flex",fontSize:14,fontWeight:"bold",lineHeight:1.14,justifyContent:"start",width:"100%"},onClick:()=>{let o;r===eMe&&(o=nh),r===nh&&(o=rh),r===rh&&(o=nh),s(o),n(o)},children:[a.jsx(T,{sx:{inlineSize:"min-content",paddingRight:5,textAlign:"left"},children:e}),i]})})};Rz.propTypes={children:A.node.isRequired,column:A.string.isRequired,onClick:A.func.isRequired};const ej=({onChangeSortDirection:e,cellWidthScalingFactor:t,variant:n})=>{const{palette:r}=Re(),{setFilterUserOptions:s,filterUserOptions:i}=m.useContext(Ca)||{},{status:o}=i||{},c=(n===$r?Az:Mz).map(({data:d,filterable:u,sortable:p,header:h,id:f,visible:g,width:x})=>{if(!g)return null;let b=5;return d==="status"&&(b=15),p?a.jsx($e,{style:{padding:0,paddingLeft:b,maxWidth:`${x*t} !important`,width:x*t},variant:"head",children:a.jsx(T,{sx:{width:x*t,overflow:"visible"},children:a.jsx(Rz,{column:d,onClick:y=>e(d,y),children:h})})},`${f}-${d}`):u?a.jsx($e,{style:{padding:0,paddingLeft:b,maxWidth:`${x*t} !important`,width:x*t},variant:"head",children:a.jsx(T,{sx:{width:x*t,overflow:"visible"},children:a.jsx(ZS,{width:x,header:h,options:o,onCheckFilter:y=>s({...i,...y}),onCheckSelectAll:()=>{},children:h})})},`${f}-${d}`):a.jsx($e,{style:{padding:0,paddingLeft:b,maxWidth:`${x*t} !important`,width:x*t},variant:"head",children:h},f)});return a.jsx(bn,{sx:{borderTop:"1px solid",borderColor:r.divider},children:c})};ej.defaultProps={cellWidthScalingFactor:1,onChangeSortDirection:()=>{},variant:va};ej.propTypes={cellWidthScalingFactor:A.number,variant:A.string,onChangeSortDirection:A.func};const tj=({editing:e,onClickCancel:t,onClickEdit:n,onClickSubmit:r,user:s})=>{const{palette:i}=Re(),{isMounted:o}=m.useContext(Ca)||{},{saving:l,statusEditMade:c,setEmailHasError:d,setEmailError:u,setSaving:p,email:h,emailHasError:f,emailEditMade:g,engagements:x,buildBodyInitObject:b,buildStatusInitObject:y,checkForBlankNames:v,hasEditBeenMade:C,resetUserFormVariables:w,roles:S}=m.useContext(ni),[E,k]=m.useState(!1),[j,_]=m.useState(!1),[D,M]=m.useState(!1),[N]=pW(),[O]=hW(),[R]=fW(),[L]=hC(),{mpTrack:P}=tr(),{disabled_by:F=null}=s,z=!F,B=(ce=!0)=>{const J=b();g&&ce?L("email",h).then(({data:he})=>{const{error:ne=null}=he||{};ne&&o()?(u(ne),d(!0),p(!1)):r(s,J,w,ce)}).catch(()=>p(!1)):r(s,J,w,ce)},W=()=>{const ce=C(s);if(!ce&&!c||ce&&!z&&!c){t(),w();return}c?(P("DASHBOARDADMIN USERMANAGEMENT ACTIONS",{actionType:`${z?"INACTIVATE":"ACTIVATE"} USER`,userEdited:s}),R(y(s)).then(({data:J})=>{J?o()&&p(!1):B(!z)})):B()},H=f||v()||!S.length||!x.length,V=e?a.jsx(mt,{acceptLabel:z?"Inactivate":"Activate",bodyText:`You are about to ${z?"inactivate":"activate"} user(s).`,handleAccept:()=>{p(!0),W(),_(!1)},handleClose:()=>{_(!1)},open:j,title:"Are you sure?"}):null,G=z?a.jsx(mt,{acceptLabel:"Send Reset Password",bodyText:"You are about to send a reset password email for this user(s).",handleAccept:()=>{P("DASHBOARDADMIN USERMANAGEMENT ACTIONS",{actionType:"RESET PASSWORD",userEdited:s}),O({body:{username:s.user_name}}).catch(We),k(!1)},handleClose:()=>{k(!1)},open:E,title:"Are you sure?"}):null,X=e?a.jsx(mt,{acceptLabel:"Recreate User",bodyText:"You are about to recreate this user.",handleAccept:()=>{P("DASHBOARDADMIN USERMANAGEMENT ACTIONS",{actionType:"RECREATE USER",userEdited:s}),p(!0),M(!1),N(s.user_name).catch(ce=>We(ce)).finally(()=>{o()&&(p(!1),w(),t())})},handleClose:()=>M(!1),open:D,title:"Are you sure?"}):null,K=a.jsx(be,{title:"Reset password",placement:"top",disableHoverListener:!z||E,children:a.jsx(He,{sx:{marginLeft:"10px"},id:`reset-email-button-${s.id}`,disabled:!z,onClick:()=>{z&&k(!0)},children:a.jsx(QU,{color:z?i.secondary.main:i.action.disabled,size:20})})}),ie=e?a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center"},children:[l?a.jsx(T,{sx:{marginLeft:"15px",marginTop:"5px",marginRight:"2px"},children:a.jsx(Ze,{color:"inherit",size:12})}):a.jsx(He,{sx:{marginLeft:"10px"},disabled:H,id:"confirm-edit-button",onClick:()=>{c?_(!0):(p(!0),W())},children:H?a.jsx(iM,{color:"disabled",style:{marginLeft:-2,marginRight:-4}}):a.jsx(Oh,{color:i.success.main,size:20})}),a.jsx(He,{sx:{marginLeft:"10px"},id:"cancel-edit-button",onClick:()=>{w(),t()},children:a.jsx(Jt,{color:i.error.main,size:20})})]}):a.jsx(be,{title:"Edit user",placement:"top",children:a.jsx(He,{sx:{marginLeft:"10px"},id:`edit-user-button-${s.id}`,onClick:n,children:a.jsx(Ju,{sx:{height:"18px",width:"18px"}})})}),le=e&&z?a.jsx(be,{title:"Recreate user",placement:"top",children:a.jsx(He,{sx:{marginLeft:"10px"},id:`recreate-user-button-${s.id}`,onClick:()=>M(!0),children:a.jsx(BD,{color:i.action.active,size:20})})}):null;return a.jsx($e,{sx:{textAlign:"right",padding:"8px"},children:a.jsxs(T,{sx:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"flex-end"},children:[le,K,ie,V,G,X]})})};tj.defaultProps={editing:!1,onClickCancel:()=>{},onClickEdit:()=>{},onClickSubmit:()=>{},user:{}};tj.propTypes={editing:A.bool,onClickCancel:A.func,onClickEdit:A.func,onClickSubmit:A.func,user:A.object};const nj=({cellWidthScalingFactor:e,editing:t,value:n,width:r})=>{const s=n!=="N/A"?KAe(n*1e3):n;return a.jsx(be,{title:s,placement:"top",disableHoverListener:t||!0,children:a.jsx($e,{sx:{fontSize:14,height:"auto",hyphens:"auto",lineHeight:"normal",padding:0,paddingLeft:"5px",whiteSpace:"normal",wordBreak:"break-word",maxWidth:r*e},children:a.jsx(T,{children:s})})})};nj.propTypes={cellWidthScalingFactor:A.number,value:A.string,editing:A.bool,width:A.number};nj.defaultProps={cellWidthScalingFactor:1,value:"",editing:!1,width:50};const rj=({editing:e,onClick:t,status:n,user:r})=>{const{palette:s}=Re(),{saving:i,setSaving:o,resetUserFormVariables:l}=m.useContext(ni),[c,d]=m.useState(!1),u=a.jsx(Cl,{bodyText:"You are about to delete user(s).",handleClose:()=>{d(!1)},handleDelete:()=>{d(!1),o(!0),t(r,l)},open:c,title:"Are you sure?"});return a.jsxs($e,{sx:{padding:0,textAlign:"center"},children:[a.jsx(be,{title:"User must be inactive",placement:"top",disableHoverListener:i||!e&&!n,children:a.jsx(He,{sx:{marginLeft:"10px",width:"30px",justifyContent:"left"},"data-testid":"delete-user-button",onClick:()=>{n||d(!0)},id:"delete-user-button",children:a.jsx(Xr,{color:n?s.action.disabled:s.secondary.main,size:20})})}),u]})};rj.defaultProps={editing:!1,onClick:()=>{},user:{}};rj.propTypes={editing:A.bool,onClick:A.func,status:A.bool.isRequired,user:A.object};const Ad=({componentOptions:e,columnName:t,disabled:n,editing:r,id:s,label:i,multiple:o,multipleText:l,onCh
272ange:c,placeholder:d,width:u,value:p})=>{const{palette:h}=Re(),f=o?a.jsx(su,{width:130,menuWidth:320,disabled:!r,id:s,placeholder:d,items:e,label:i,multipleText:l,searchable:!0,onSelect:c,value:p}):a.jsx(kg,{width:130,id:s,disabled:!r||n,placeholder:d,items:e,label:i,onChange:c,value:p,searchable:e.length>5,showSearchAdornment:!0,renderValue:()=>e.find(g=>g.value===p)?.label||"None",inputProps:{sx:{"&.Mui-disabled":{WebkitTextFillColor:h.text.primary}}},MenuProps:{PaperProps:{id:`${s}-list`,style:{marginTop:10,maxHeight:224,maxWidth:320}},disableAutoFocusItem:!0},style:{marginBottom:0,marginTop:0}});return a.jsx($e,{sx:{hyphens:"auto",lineHeight:"normal",padding:0,paddingLeft:"5px",whiteSpace:"normal",wordBreak:"break-word",maxWidth:u,height:"40px"},children:a.jsx(be,{title:`Select ${t}.`,placement:"right",arrow:!0,children:f})})};Ad.defaultProps={componentOptions:[],disabled:!1,columnName:"",id:"user-multiple-select",editing:!1,label:"",multiple:!0,multipleText:"Selections",onChange:()=>{},placeholder:"",width:150,value:[]};Ad.propTypes={componentOptions:A.array,columnName:A.string,disabled:A.bool,editing:A.bool,id:A.string,label:A.string,multiple:A.bool,multipleText:A.string,onChange:A.func,placeholder:A.string,width:A.number,value:A.oneOfType([A.string,A.array])};const Zu=({cellWidthScalingFactor:e,value:t,width:n})=>a.jsx($e,{sx:{fontSize:14,height:"auto",hyphens:"auto",lineHeight:"normal",padding:0,paddingLeft:"5px",whiteSpace:"normal",wordBreak:"break-word",maxWidth:n*e},children:a.jsx(T,{title:t||"",children:t||""})});Zu.propTypes={cellWidthScalingFactor:A.number,value:A.string,width:A.number};Zu.defaultProps={cellWidthScalingFactor:1,value:"",width:50};const sj=({cellWidthScalingFactor:e,editing:t,value:n,width:r})=>{const{email:s,emailEditMade:i,emailError:o,emailHasError:l,setEmail:c,setEmailEditMade:d,setEmailError:u,setEmailHasError:p}=m.useContext(ni),h=f=>{const g=J4(f);!g&&!l?(p(!l),u("Not a valid email format.")):g&&l&&(u("Enter user's email information."),p(!l))};return t?a.jsx($e,{sx:{padding:0},children:a.jsx(De,{id:"user-email-text-input",error:l,helperText:l?o:"",value:s||"",type:"email",onChange:({target:f})=>{const{value:g}=f||{},x=g&&g.length>0;c(x?g:""),h(g),(!i&&g!==n||i&&g===n)&&d(!i)},onBlur:({target:f})=>{const{value:g}=f;if(!(g&&g.length>0)){c(n),p(!1);return}g!==n?(c(g),i||d(!i)):(c(n),p(!1),i&&d(!i))},sx:{width:r},inputProps:{maxLength:75},size:"small"})}):a.jsx(Zu,{value:n||"N/A",width:r*e})};sj.propTypes={cellWidthScalingFactor:A.number,value:A.string,editing:A.bool,width:A.number};sj.defaultProps={cellWidthScalingFactor:1,value:"",editing:!1,width:50};const ij=({cellWidthScalingFactor:e,editing:t,user:n,width:r})=>{const{firstName:s,firstNameEditMade:i,lastName:o,lastNameEditMade:l,setFirstName:c,setFirstNameEditMade:d,setLastName:u,setLastNameEditMade:p}=m.useContext(ni),{first_name:h="",last_name:f=""}=n,g=`${h||""} ${f||""}`,x=(b,y,v,C)=>{(!b&&y!==v||b&&y===v)&&C(!b)};return t?a.jsx($e,{sx:{paddingLeft:0},children:a.jsxs(T,{sx:{display:"flex",flexDirection:"row"},children:[a.jsx(De,{id:"user-first-name-text-input",value:s||"",onChange:({target:b})=>{const{value:y}=b;c(y||""),x(i,y,h,d)},onBlur:({target:b})=>{const y=b.value.trim();s!==y&&c(y),x(i,y,h,d)},sx:{width:r/2},inputProps:{maxLength:75},size:"small"}),a.jsx(T,{sx:{marginLeft:"10px"},children:a.jsx(De,{id:"user-last-name-text-input",value:o||"",onChange:({target:b})=>{const{value:y}=b;u(y||""),x(l,y,f,p)},onBlur:({target:b})=>{const y=b.value.trim();f!==y&&u(y),x(l,y,f,p)},sx:{width:r/2},inputProps:{maxLength:75},size:"small"})})]})}):a.jsx($e,{id:`standard-name-cell-${g}`,sx:{fontSize:14,height:"auto",hyphens:"auto",lineHeight:"normal",padding:0,paddingLeft:"5px",whiteSpace:"normal",wordBreak:"break-word",maxWidth:r*e},children:a.jsx(T,{title:g||"",children:g||""})})};ij.propTypes={cellWidthScalingFactor:A.number,user:A.object,editing:A.bool,width:A.number};ij.defaultProps={cellWidthScalingFactor:1,user:{},editing:!1,width:50};const tMe=e=>{try{return kC(e)||null}catch{return null}},Nz=({cellWidthScalingFactor:e=1,editing:t=!1,value:n=null,width:r=50})=>{const{phoneNumberEditMade:s,setPhoneNumber:i,setPhoneNumberEditMade:o}=m.useContext(ni),[l,c]=m.useState(tMe(n)),d=l?.formatInternational()||"N/A",u=p=>{i(p);const h=p?.nunmber||"";!s&&h!==n?o(!0):s&&h===n&&o(!1)};return t?a.jsx($e,{style:{padding:0},children:a.jsx(KS,{onBlur:u,phoneObj:l,setPhoneObj:c})}):a.jsx(Zu,{value:d,width:r*e})};Nz.propTypes={cellWidthScalingFactor:A.number,editing:A.bool,value:A.string,width:A.number};const aj=({disabled:e,hidden:t,onSelect:n,selected:r,user:s})=>a.jsx($e,{sx:{padding:0,textAlign:"center"},children:a.jsx(be,{title:`Select ${s.first_name||""} ${s.last_name||""}`,placement:"right",arrow:!0,disabled:t,children:a.jsx(et,{sx:{padding:0},checked:r,disabled:e,onClick:()=>n(!r),style:{visibility:t?"hidden":"inherit"}})})});aj.defaultProps={disabled:!1,hidden:!0,onSelect:()=>{},selected:!1,user:{}};aj.propTypes={disabled:A.bool,hidden:A.bool,onSelect:A.func,selected:A.bool,user:A.object};const nMe=rt(Dn)(({theme:e})=>({width:70,height:28,padding:0,"& .MuiSwitch-switchBase":{padding:0,margin:2,transitionDuration:"300ms","&.Mu
272i-checked":{transform:"translateX(42px)",color:e.palette.common.white,"& + .MuiSwitch-track":{backgroundColor:e.palette.primary.main,opacity:1,border:0},"&.Mui-disabled + .MuiSwitch-track":{opacity:.5}},"&.Mui-disabled .MuiSwitch-thumb":{color:e.palette.action.disabledBackground},"&.Mui-disabled + .MuiSwitch-track":{opacity:.3}},"& .MuiSwitch-thumb":{boxSizing:"border-box",width:24,height:24},"& .MuiSwitch-track":{borderRadius:28/2,backgroundColor:e.palette.action.disabled,opacity:1,transition:e.transitions.create(["background-color"],{duration:500})}})),oj=({editing:e,onClick:t,status:n,setStatus:r,user:s,width:i})=>{const{statusEditMade:o,setStatusEditMade:l}=m.useContext(ni);return a.jsx($e,{sx:{width:i,padding:"8px"},children:a.jsx(be,{title:`Switch ${s.user_name} status.`,placement:"right",children:a.jsxs(T,{sx:{position:"relative",display:"inline-flex",alignItems:"center"},children:[a.jsx(nMe,{disabled:!e,id:e?"edit-switch-button":"switch-button",checked:n,onChange:c=>{const d=c.target.checked;t(d),r(d),l(!o)}}),a.jsx(I,{sx:{position:"absolute",left:n?"6px":"27px",fontSize:"10px",fontWeight:600,color:c=>n?c.palette.common.white:c.palette.text.disabled,pointerEvents:"none",userSelect:"none",transition:"all 300ms"},children:n?"Active":"Inactive"})]})})})};oj.defaultProps={editing:!1,onClick:()=>{},status:!1,setStatus:()=>{},width:130,user:{}};oj.propTypes={editing:A.bool,onClick:A.func,setStatus:A.func,status:A.bool,user:A.object,width:A.number};const lj=({cellWidthScalingFactor:e,editing:t,isSelected:n,onClickEdit:r,onEditCancel:s,onEditSubmit:i,onClickDelete:o,onSelect:l,user:c,variant:d})=>{const{agencyOptions:u,internalEngagementOptions:p,externalEngagementOptions:h}=m.useContext(Ca),{agency:f,checkIsAgencyUser:g,engagements:x,engagementsEditMade:b,roles:y,rolesEditMade:v,setAgency:C,setAgencyEditMade:w,setCurrentUserToForm:S,setEngagements:E,setEngagementsEditMade:k,setRoles:j,setRolesEditMade:_}=m.useContext(ni),{disabled_by:D=null,groups:M=[],engagements:N=[]}=c||{},O=!D,[R,L]=m.useState(O);m.useEffect(()=>{!t&&O!==R&&L(O)},[O,t]),m.useEffect(()=>{t&&S(c)},[t]),m.useEffect(()=>{f&&!g(d)&&(C(null),w(!!c.row_access))},[y]);const F=(d===$r?Az:Mz).map(({header:z,data:B,id:W,type:H,visible:V,width:G})=>{if(!B||!z||!V)return null;const X=c[B];if(H==="switch")return a.jsx(oj,{user:c,status:R,setStatus:L,columnName:B,editing:t,width:G*e},W);if(H==="select"){if(B==="groups")return a.jsx(Ad,{multipleText:"Roles",placeholder:"Select",id:t?"edit-user-roles":"roles",columnName:B,componentOptions:Fa(d===$r?[...Ez,...cm]:cm),editing:t&&R,onChange:K=>{const ie=Nv(K),le=uD(ie,M);(le&&!v||!le&&v)&&_(!v),j(ie)},width:G*e,user:c,value:Fa(t?y:M)},W);if(B==="row_access")return a.jsx(Ad,{placeholder:"Select",id:t?"edit-user-agency":"agency",columnName:B,componentOptions:u,editing:t&&R,disabled:!g(d),onChange:K=>{K!==c.row_access?w(!0):w(!1),C(K)},width:G*e,user:c,multiple:!1,value:t?f:c.row_access},W);if(B==="engagements"||B==="clients")return a.jsx(Ad,{multipleText:"Engmts",placeholder:"Select",id:t?"edit-user-engagement":"engagement",columnName:B,componentOptions:d===$r?p:h,editing:t&&R,onChange:K=>{const ie=Nv(K),le=uD(ie,N);(le&&!b||!le&&b)&&k(!b),E(ie)},width:G*e,user:c,value:HAe(t?x:N)},W)}return H==="date"?a.jsx(nj,{value:X||"N/A",editing:t,width:G*e},W):H==="name"?a.jsx(ij,{user:c||{},editing:t&&R,width:G*e},W):H==="number"?a.jsx(Nz,{data:B,value:X,editing:t&&R,width:G*e},W):H==="email"?a.jsx(sj,{data:B,value:X,editing:t&&R,width:G*e},W):a.jsx(Zu,{data:B,value:X||"N/A",editing:t,width:G*e},W)});return a.jsxs(bn,{children:[a.jsx(aj,{onSelect:z=>l(z),user:c,selected:n},"select"),a.jsx(tj,{editing:t,onClickCancel:s,onClickEdit:r,onClickSubmit:i,style:{maxWidth:90},user:c}),F,a.jsx(rj,{editing:t,status:O,onClick:o,style:{maxWidth:90},user:c})]})};lj.propTypes={cellWidthScalingFactor:A.number,editing:A.bool,isSelected:A.bool,onClickEdit:A.func,onEditCancel:A.func,onEditSubmit:A.func,onClickDelete:A.func,onSelect:A.func,user:A.object,variant:A.string};lj.defaultProps={cellWidthScalingFactor:1,editing:!1,isSelected:!1,onClickEdit:()=>{},onEditCancel:()=>{},onEditSubmit:()=>{},onClickDelete:()=>{},onSelect:()=>{},user:{},variant:va};const cj=({cellWidthScalingFactor:e,editing:t,isSelected:n,onClickEdit:r,onEditCancel:s,onEditSubmit:i,onClickDelete:o,onSelect:l,user:c,variant:d})=>a.jsx(Tg,{children:a.jsx(lj,{cellWidthScalingFactor:e,editing:t,isSelected:n,onClickEdit:r,onEditCancel:s,onEditSubmit:i,onClickDelete:o,onSelect:l,user:c,variant:d})});cj.propTypes={cellWidthScalingFactor:A.number,editing:A.bool,isSelected:A.bool,onClickEdit:A.func,onClickDelete:A.func,onEditCancel:A.func,onEditSubmit:A.func,onSelect:A.func,user:A.object,variant:A.string};cj.defaultProps={cellWidthScalingFactor:1,editing:!1,isSelected:!1,onClickEdit:()=>{},onEditCancel:()=>{},onEditSubmit:()=>{},onClickDelete:()=>{},onSelect:()=>{},user:{},variant:va};const dm=({fetching:e,invalidateUsers:t,loading:n,users:r,variant:s})=>{const{clientHasEngagements:i,isMounted:o,internalUserBool:l,filterUserOptions:c}=m.useContext(Ca)||{},[d,u]=m.useState(0),[p,h]=m.useState(()=>()=>{}),[f,g]=m.useState(null),[x,b]=m.useState(kz),[y,v]=m.useState(""),[C,w]=m.useState([]),[S,E]=m.useState([]),[k,j]=m.useState(!1),{mpTrack:_}=tr(),[D]=mW(),{userId:M}=gt(),[N,O]=m.useState([...r]),[R]=uC(),[L]=_A(),P=(V,G=!1)=>{t(),!G&&o()&&h(()=>()=>V())},F=async(V,G)=>{const{user_name:X="",id:K=null}=V||{};f||g(K),_("DASHBOARDADMIN USERMANAGEMENT ACTIONS",{actionType:"DELETE USER",userEdited:V||{}}),await D({body:{username:X}}).unwrap().then(()=>P(G,!0)).catch(()=>{console.log("error deleting:: ",X),o()&&(G(),g(null))})},z=(V,G,X,K)=>{const{id:ie}=V||{},le=G.body?.engagements&&M&&M===Number(ie);K&&Object.keys(G.body||{}).length!==0?(_("DASHBOARDADMIN USERMANAGEMENT ACTIONS",{actionType:"EDIT USER",userEdited:V,editsMade:G.body||{}}),R({...G,username:V.user_name}).unwrap().then(async()=>{P(X),le&&L()}).catch(()=>console.log("error updating user"))):P(X)};m.useEffect(()=>{!e&&!n&&f&&(p(),g(null))},[e]),m.useEffect(()=>{r?.length>0&&O([...r])},[r]),m.useEffect(()=>{N?.length>0&&(E(y?ZAe(hD(N,c),y):hD(N,c)),d>0&&u(0))},[y,N,c]);const B=(V,G)=>{const X=QAe(V),K=JAe(V,G,X);O([...N.sort(K)])},H=(S.length>0?YAe(d,x,S):[]).map(V=>{const{id:G}=V||{},X=C.indexOf(G)!==-1;return a.jsx(cj,{id:`user-row-${G}`,isSelected:X,onSelect:K=>{w(K?[...C,G].sort((ie,le)=>ie-le):C.filter(ie=>ie!==G))},editing:f===G,onClickEdit:()=>{g(G),X||w([...C,G].sort((K,ie)=>K-ie))},onEditCancel:()=>g(null),onEditSubmit:z,onClickDelete:F,even:!1,user:V,variant:s},G)}
272);return a.jsxs(a.Fragment,{children:[a.jsxs(T,{sx:{display:"flex",flexDirection:"row",justifyContent:"space-between"},children:[a.jsx(XS,{searchText:y,setSearchText:v}),a.jsx(be,{title:"This client has no active engagements.",placement:"left",disableHoverListener:s!==va||i,children:a.jsx(T,{children:a.jsx(GS,{internalUserBool:l,onClickCreate:()=>{f&&g(null),j(!k)},variant:s,disabled:!i})})})]}),a.jsxs(T,{sx:{marginLeft:"15px",marginRight:"15px",marginTop:"40px",paddingBottom:"30px",overflow:"auto"},children:[a.jsxs(Ki,{sx:{overflow:"hidden",tableLayout:"fixed",minWidth:"1200px"},id:"users-table",children:[a.jsx(Ya,{id:"users-table-head",children:a.jsx(ej,{onChangeSortDirection:B,variant:s})}),a.jsx(xl,{id:"users-table-body",children:n?null:H})]}),n&&a.jsx(T,{sx:{marginTop:"40px",textAlign:"center",width:"100%"},children:a.jsx(Ze,{size:24})}),!n&&a.jsx(JS,{pageSize:x,currentPage:d,total:S.length,onGoForward:()=>{d<=Math.floor(S.length/x)-1&&u(d+1)},onGoBackward:()=>{d>0&&u(d-1)},controlPageSizeBool:!0,onChangePageSize:V=>{b(V),u(0)}})]}),a.jsx(Tg,{children:a.jsx(Dz,{open:k,onClickConfirm:()=>{j(!1),P()},onClickCancel:()=>j(!1),variant:s})})]})};dm.propTypes={fetching:A.bool,invalidateUsers:A.func.isRequired,loading:A.bool,users:A.array,variant:A.string};dm.defaultProps={fetching:!1,loading:!1,users:[],variant:va};const rMe=()=>{const{loadingInt:e=!1,loadingExt:t=!1,fetchingExt:n,fetchingInt:r,activeTab:s,setActiveTab:i,internalUserBool:o,usersInternal:l,usersExternal:c}=m.useContext(Ca)||{},[d]=AA(),[u]=gW();return m.useEffect(()=>{const p=o?_a.INTERNAL_USERS_TABLE:_a.EXTERNAL_USERS_TABLE;p!==s&&i(p)},[o,i]),a.jsx(T,{sx:{width:ks,marginBottom:"50px"},children:a.jsxs(co,{value:s,children:[a.jsx(T,{sx:{borderBottom:1,borderColor:"border.default"},children:a.jsxs(uo,{onChange:(p,h)=>i(h),variant:"fullWidth",children:[o&&a.jsx(_n,{id:"user-management-internal-tab",label:"Internal Users",value:_a.INTERNAL_USERS_TABLE}),a.jsx(_n,{id:"user-management-external-tab",label:o?"Client Users":"Users",value:_a.EXTERNAL_USERS_TABLE})]})}),a.jsx(xt,{sx:{overflowX:"auto",p:0},value:_a.INTERNAL_USERS_TABLE,children:a.jsx(dm,{fetching:r,invalidateUsers:u,loading:e,users:l,variant:$r})}),a.jsx(xt,{sx:{overflowX:"auto",p:0},value:_a.EXTERNAL_USERS_TABLE,children:a.jsx(dm,{fetching:n,invalidateUsers:d,loading:t,users:c,variant:va})})]})})},sMe=()=>a.jsx(qS,{children:a.jsx(rMe,{})});function um(e){"@babel/helpers - typeof";return um=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},um(e)}function xs(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function Vt(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function Ut(e){Vt(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||um(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function iMe(e,t){Vt(2,arguments);var n=Ut(e),r=xs(t);return isNaN(r)?new Date(NaN):(r&&n.setDate(n.getDate()+r),n)}function aMe(e,t){Vt(2,arguments);var n=Ut(e).getTime(),r=xs(t);return new Date(n+r)}var oMe={};function Vl(){return oMe}function pm(e,t){var n,r,s,i,o,l,c,d;Vt(1,arguments);var u=Vl(),p=xs((n=(r=(s=(i=t?.weekStartsOn)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(l=o.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&s!==void 0?s:u.weekStartsOn)!==null&&r!==void 0?r:(c=u.locale)===null||c===void 0||(d=c.options)===null||d===void 0?void 0:d.weekStartsOn)!==null&&n!==void 0?n:0);if(!(p>=0&&p<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var h=Ut(e),f=h.getDay(),g=(f<p?7:0)+f-p;return h.setDate(h.getDate()-g),h.setHours(0,0,0,0),h}function lMe(e){var t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function fD(e){Vt(1,arguments);var t=Ut(e);return t.setHours(0,0,0,0),t}function cMe(e,t){Vt(2,arguments);var n=xs(t),r=n*7;return iMe(e,r)}function dMe(e,t){Vt(2,arguments);var n=Ut(e),r=Ut(t),s=n.getTime()-r.getTime();return s<0?-1:s>0?1:s}function Oz(e,t){Vt(2,arguments);var n=fD(e),r=fD(t);return n.getTime()===r.getTime()}function uMe(e){return Vt(1,arguments),e instanceof Date||um(e)==="object"&&Object.prototype.toString.call(e)==="[object Date]"}function pMe(e){if(Vt(1,arguments),!uMe(e)&&typeof e!="number")return!1;var t=Ut(e);return!isNaN(Number(t))}function hMe(e,t){var n;Vt(1,arguments);var r=e||{},s=Ut(r.start),i=Ut(r.end),o=i.getTime();if(!(s.getTime()<=o))throw new RangeError("Invalid interval");var l=[],c=s;c.setHours(0,0,0,0);var d=Number((n=void 0)!==null&&n!==void 0?n:1);if(d<1||isNaN(d))throw new RangeError("`options.step` must be a number greater than 1");for(;c.getTime()<=o;)l.push(Ut(c)),c.setDate(c.getDate()+d),c.setHours(0,0,0,0);return l}function fMe(e){Vt(1,arguments);var t=e||{},n=Ut(t.start),r=Ut(t.end),s=r.getTime(),i=[];if(!(n.getTime()<=s))throw new RangeError("Invalid interval");var o=n;for(o.setHours(0,0,0,0),o.setDate(1);o.getTime()<=s;)i.push(Ut(o)),o.setMonth(o.getMonth()+1);return i}function mMe(e,t){Vt(1,arguments);var n=e||{},r=Ut(n.start),s=Ut(n.end),i=s.getTime();if(!(r.getTime()<=i))throw new RangeError("Invalid interval");var o=pm(r,t),l=pm(s,t);o.setHours(15),l.setHours(15),i=l.getTime();for(var c=[],d=o;d.getTime()<=i;)d.setHours(0),c.push(Ut(d)),d=cMe(d,1),d.setHours(15);return c}function gMe(e,t){var n,r,s,i,o,l;Vt(1,arguments);var c=Vl(),d=xs((n=(r=(s=(i=void 0)!==null&&i!==void 0?i:void 0)!==null&&s!==void 0?s:c.weekStartsOn)!==null&&r!==void 0?r:(o=c.locale)===null||o===void 0||(l=o.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&n!==void 0?n:0);if(!(d>=0&&d<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var u=Ut(e),p=u.getDay(),h=(p<d?-7:0)+6-(p-d);return u.setDate(u.getDate()+h),u.setHours(23,59,59,999),u}function xMe(e,t){Vt(2,arguments);var n=xs(t);return aMe(e,-n)}var bMe=864e5;function yMe(e){Vt(1,arguments);var t=Ut(e),n=t.getTime();t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0);var r=t.getTime(),s=n-r;return Math.floor(s/bMe)+1}function hm(e){Vt(1,arguments);var t=1,n=Ut(e),r=n.getUTCDay(),s=(r<t?7:0)+r-t;return n.setUTCDate(n.getUTCDate()-s),n.setUTCHours(0,0,0,0),n}function Pz(e){Vt(1,arguments);var t=Ut(e),n=t.getUTCFullYear(),r=new Date(0);r.setUTCFullYear(n+1,0,4),r.setUTCHours(0,0,0,0);var s=hm(r),i=new Date(0);i.setUTCFullYear(n,0,4),i.setUTCHours(0,0,0,0);var o=hm(i);return t.getTime()>=s.getTime()?n+1:t.getTime()>=o.getTime()?n:n-1}function vMe(e){Vt(1,arguments);var t=Pz(e),n=new Date(0);n.setUTCFullYear(t,0,4),n.setUTCHours(0,0,0,0);var r=hm(n);return r}var CMe=6048e5;function wMe(e){Vt(1,arguments);var t=Ut(e),n=hm(t).getTime()-vMe(t).getTime();return Math.round(n/CMe)+1}function fm(e,t){var n,r,s,i,o,l,c,d;Vt(1,arguments);var u=Vl(),p=xs((n=(r=(s=(i=t?.weekStartsOn)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(l=o.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&s!==void 0?s:u.weekStartsOn)!==null&&r!==void 0?r:(c=u.locale)===null||c===void 0||(d=c.options)===null||d===void 0?void 0:d.weekStartsOn)!==null&&n!==void 0?n:0);if(!(p>=0&&p<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var h=Ut(e),f=h.getUTCDay(),g=(f<p?7:0)+f-p;return h.setUTCDate(h.getUTCDate()-g),h.setUTCHours(0,0,0,0),h}function Lz(e,t){var n,r,s,i,o,l,c,d;Vt(1,arguments);var u=Ut(e),p=u.getUTCFullYear(),h=Vl(),f=xs((n=(r=(s=(i=t?.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(l=o.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&s!==void 0?s:h.firstWeekContainsDate)!==null&&r!==void 0?r:(c=h.locale)===null||c===void 0||(d=c.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&n!==void 0?n:1);if(!(f>=1&&f<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var g=new Date(0);g.setUTCFullYear(p+1,0,f),g.setUTCHours(0,0,0,0);var x=fm(g,t),b=new Date(0);b.setUTCFullYear(p,0,f),b.setUTCHours(0,0,0,0);var y=fm(b,t);return u.getTime()>=x.getTime()?p+1:u.getTime()>=y.getTime()?p:p-1}function SMe(e,t){var n,r,s,i,o,l,c,d;Vt(1,arguments);var u=Vl(),p=xs((n=(r=(s=(i=t?.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(l=o.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&s!==void 0?s:u.firstWeekContainsDate)!==null&&r!==void 0?r:(c=u.locale)===null||c===void 0||(d=c.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&n!==void 0?n:1),h=Lz(e,t),f=new Date(0);f.setUTCFullYear(h,0,p),f.setUTCHours(0,0,0,0);var g=fm(f,t);return g}
272var jMe=6048e5;function kMe(e,t){Vt(1,arguments);var n=Ut(e),r=fm(n,t).getTime()-SMe(n,t).getTime();return Math.round(r/jMe)+1}function At(e,t){for(var n=e<0?"-":"",r=Math.abs(e).toString();r.length<t;)r="0"+r;return n+r}var Ri={y:function(t,n){var r=t.getUTCFullYear(),s=r>0?r:1-r;return At(n==="yy"?s%100:s,n.length)},M:function(t,n){var r=t.getUTCMonth();return n==="M"?String(r+1):At(r+1,2)},d:function(t,n){return At(t.getUTCDate(),n.length)},a:function(t,n){var r=t.getUTCHours()/12>=1?"pm":"am";switch(n){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h:function(t,n){return At(t.getUTCHours()%12||12,n.length)},H:function(t,n){return At(t.getUTCHours(),n.length)},m:function(t,n){return At(t.getUTCMinutes(),n.length)},s:function(t,n){return At(t.getUTCSeconds(),n.length)},S:function(t,n){var r=n.length,s=t.getUTCMilliseconds(),i=Math.floor(s*Math.pow(10,r-3));return At(i,n.length)}},Lo={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},EMe={G:function(t,n,r){var s=t.getUTCFullYear()>0?1:0;switch(n){case"G":case"GG":case"GGG":return r.era(s,{width:"abbreviated"});case"GGGGG":return r.era(s,{width:"narrow"});default:return r.era(s,{width:"wide"})}},y:function(t,n,r){if(n==="yo"){var s=t.getUTCFullYear(),i=s>0?s:1-s;return r.ordinalNumber(i,{unit:"year"})}return Ri.y(t,n)},Y:function(t,n,r,s){var i=Lz(t,s),o=i>0?i:1-i;if(n==="YY"){var l=o%100;return At(l,2)}return n==="Yo"?r.ordinalNumber(o,{unit:"year"}):At(o,n.length)},R:function(t,n){var r=Pz(t);return At(r,n.length)},u:function(t,n){var r=t.getUTCFullYear();return At(r,n.length)},Q:function(t,n,r){var s=Math.ceil((t.getUTCMonth()+1)/3);switch(n){case"Q":return String(s);case"QQ":return At(s,2);case"Qo":return r.ordinalNumber(s,{unit:"quarter"});case"QQQ":return r.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(s,{width:"narrow",context:"formatting"});default:return r.quarter(s,{width:"wide",context:"formatting"})}},q:function(t,n,r){var s=Math.ceil((t.getUTCMonth()+1)/3);switch(n){case"q":return String(s);case"qq":return At(s,2);case"qo":return r.ordinalNumber(s,{unit:"quarter"});case"qqq":return r.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(s,{width:"narrow",context:"standalone"});default:return r.quarter(s,{width:"wide",context:"standalone"})}},M:function(t,n,r){var s=t.getUTCMonth();switch(n){case"M":case"MM":return Ri.M(t,n);case"Mo":return r.ordinalNumber(s+1,{unit:"month"});case"MMM":return r.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(s,{width:"narrow",context:"formatting"});default:return r.month(s,{width:"wide",context:"formatting"})}},L:function(t,n,r){var s=t.getUTCMonth();switch(n){case"L":return String(s+1);case"LL":return At(s+1,2);case"Lo":return r.ordinalNumber(s+1,{unit:"month"});case"LLL":return r.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(s,{width:"narrow",context:"standalone"});default:return r.month(s,{width:"wide",context:"standalone"})}},w:function(t,n,r,s){var i=kMe(t,s);return n==="wo"?r.ordinalNumber(i,{unit:"week"}):At(i,n.length)},I:function(t,n,r){var s=wMe(t);return n==="Io"?r.ordinalNumber(s,{unit:"week"}):At(s,n.length)},d:function(t,n,r){return n==="do"?r.ordinalNumber(t.getUTCDate(),{unit:"date"}):Ri.d(t,n)},D:function(t,n,r){var s=yMe(t);return n==="Do"?r.ordinalNumber(s,{unit:"dayOfYear"}):At(s,n.length)},E:function(t,n,r){var s=t.getUTCDay();switch(n){case"E":case"EE":case"EEE":return r.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(s,{width:"short",context:"formatting"});default:return r.day(s,{width:"wide",context:"formatting"})}},e:function(t,n,r,s){var i=t.getUTCDay(),o=(i-s.weekStartsOn+8)%7||7;switch(n){case"e":return String(o);case"ee":return At(o,2);case"eo":return r.ordinalNumber(o,{unit:"day"});case"eee":return r.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(i,{width:"short",context:"formatting"});default:return r.day(i,{width:"wide",context:"formatting"})}},c:function(t,n,r,s){var i=t.getUTCDay(),o=(i-s.weekStartsOn+8)%7||7;switch(n){case"c":return String(o);case"cc":return At(o,n.length);case"co":return r.ordinalNumber(o,{unit:"day"});case"ccc":return r.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(i,{width:"narrow",context:"standalone"});case"cccccc":return r.day(i,{width:"short",context:"standalone"});default:return r.day(i,{width:"wide",context:"standalone"})}},i:function(t,n,r){var s=t.getUTCDay(),i=s===0?7:s;switch(n){case"i":return String(i);case"ii":return At(i,n.length);case"io":return r.ordinalNumber(i,{unit:"day"});case"iii":return r.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(s,{width:"short",context:"formatting"});default:return r.day(s,{width:"wide",context:"formatting"})}},a:function(t,n,r){var s=t.getUTCHours(),i=s/12>=1?"pm":"am";switch(n){case"a":case"aa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(i,{width:"narrow",context:"formatting"});default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,n,r){var s=t.getUTCHours(),i;switch(s===12?i=Lo.noon:s===0?i=Lo.midnight:i=s/12>
272=1?"pm":"am",n){case"b":case"bb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(i,{width:"narrow",context:"formatting"});default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,n,r){var s=t.getUTCHours(),i;switch(s>=17?i=Lo.evening:s>=12?i=Lo.afternoon:s>=4?i=Lo.morning:i=Lo.night,n){case"B":case"BB":case"BBB":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(i,{width:"narrow",context:"formatting"});default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,n,r){if(n==="ho"){var s=t.getUTCHours()%12;return s===0&&(s=12),r.ordinalNumber(s,{unit:"hour"})}return Ri.h(t,n)},H:function(t,n,r){return n==="Ho"?r.ordinalNumber(t.getUTCHours(),{unit:"hour"}):Ri.H(t,n)},K:function(t,n,r){var s=t.getUTCHours()%12;return n==="Ko"?r.ordinalNumber(s,{unit:"hour"}):At(s,n.length)},k:function(t,n,r){var s=t.getUTCHours();return s===0&&(s=24),n==="ko"?r.ordinalNumber(s,{unit:"hour"}):At(s,n.length)},m:function(t,n,r){return n==="mo"?r.ordinalNumber(t.getUTCMinutes(),{unit:"minute"}):Ri.m(t,n)},s:function(t,n,r){return n==="so"?r.ordinalNumber(t.getUTCSeconds(),{unit:"second"}):Ri.s(t,n)},S:function(t,n){return Ri.S(t,n)},X:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();if(o===0)return"Z";switch(n){case"X":return gD(o);case"XXXX":case"XX":return Ta(o);default:return Ta(o,":")}},x:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();switch(n){case"x":return gD(o);case"xxxx":case"xx":return Ta(o);default:return Ta(o,":")}},O:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();switch(n){case"O":case"OO":case"OOO":return"GMT"+mD(o,":");default:return"GMT"+Ta(o,":")}},z:function(t,n,r,s){var i=s._originalDate||t,o=i.getTimezoneOffset();switch(n){case"z":case"zz":case"zzz":return"GMT"+mD(o,":");default:return"GMT"+Ta(o,":")}},t:function(t,n,r,s){var i=s._originalDate||t,o=Math.floor(i.getTime()/1e3);return At(o,n.length)},T:function(t,n,r,s){var i=s._originalDate||t,o=i.getTime();return At(o,n.length)}};function mD(e,t){var n=e>0?"-":"+",r=Math.abs(e),s=Math.floor(r/60),i=r%60;if(i===0)return n+String(s);var o=t;return n+String(s)+o+At(i,2)}function gD(e,t){if(e%60===0){var n=e>0?"-":"+";return n+At(Math.abs(e)/60,2)}return Ta(e,t)}function Ta(e,t){var n=t||"",r=e>0?"-":"+",s=Math.abs(e),i=At(Math.floor(s/60),2),o=At(s%60,2);return r+i+n+o}var xD=function(t,n){switch(t){case"P":return n.date({width:"short"});case"PP":return n.date({width:"medium"});case"PPP":return n.date({width:"long"});default:return n.date({width:"full"})}},Fz=function(t,n){switch(t){case"p":return n.time({width:"short"});case"pp":return n.time({width:"medium"});case"ppp":return n.time({width:"long"});default:return n.time({width:"full"})}},_Me=function(t,n){var r=t.match(/(P+)(p+)?/)||[],s=r[1],i=r[2];if(!i)return xD(t,n);var o;switch(s){case"P":o=n.dateTime({width:"short"});break;case"PP":o=n.dateTime({width:"medium"});break;case"PPP":o=n.dateTime({width:"long"});break;default:o=n.dateTime({width:"full"});break}return o.replace("{{date}}",xD(s,n)).replace("{{time}}",Fz(i,n))},TMe={p:Fz,P:_Me},IMe=["D","DD"],DMe=["YY","YYYY"];function AMe(e){return IMe.indexOf(e)!==-1}function MMe(e){return DMe.indexOf(e)!==-1}function bD(e,t,n){if(e==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(t,"`) for formatting years to the input `").
vendor: 9,652 bytes, line 272
272concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(t,"`) for formatting years to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(t,"`) for formatting days of the month to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(t,"`) for formatting days of the month to the input `").concat(n,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var RMe={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},NMe=function(t,n,r){var s,i=RMe[t];return typeof i=="string"?s=i:n===1?s=i.one:s=i.other.replace("{{count}}",n.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+s:s+" ago":s};function Db(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=t.width?String(t.width):e.defaultWidth,r=e.formats[n]||e.formats[e.defaultWidth];return r}}var OMe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},PMe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},LMe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},FMe={date:Db({formats:OMe,defaultWidth:"full"}),time:Db({formats:PMe,defaultWidth:"full"}),dateTime:Db({formats:LMe,defaultWidth:"full"})},$Me={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},zMe=function(t,n,r,s){return $Me[t]};function Zc(e){return function(t,n){var r=n!=null&&n.context?String(n.context):"standalone",s;if(r==="formatting"&&e.formattingValues){var i=e.defaultFormattingWidth||e.defaultWidth,o=n!=null&&n.width?String(n.width):i;s=e.formattingValues[o]||e.formattingValues[i]}else{var l=e.defaultWidth,c=n!=null&&n.width?String(n.width):e.defaultWidth;s=e.values[c]||e.values[l]}var d=e.argumentCallback?e.argumentCallback(t):t;return s[d]}}var BMe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},UMe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},VMe={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},WMe={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},HMe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},qMe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},GMe=function(t,n){var r=Number(t),s=r%100;if(s>20||s<10)switch(s%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},YMe={ordinalNumber:GMe,era:Zc({values:BMe,defaultWidth:"wide"}),quarter:Zc({values:UMe,defaultWidth:"wide",argumentCallback:function(t){return t-1}}),month:Zc({values:VMe,defaultWidth:"wide"}),day:Zc({values:WMe,defaultWidth:"wide"}),dayPeriod:Zc({values:HMe,defaultWidth:"wide",formattingValues:qMe,defaultFormattingWidth:"wide"})};function ed(e){return function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=t.match(s);if(!i)return null;var o=i[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?QMe(l,function(p){return p.test(o)}):KMe(l,function(p){return p.test(o)}),d;d=e.valueCallback?e.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;var u=t.slice(o.length);return{value:d,rest:u}}}function KMe(e,t){for(var n in e)if(e.hasOwnProperty(n)&&t(e[n]))return n}function QMe(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return n}function JMe(e){return function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=t.match(e.matchPattern);if(!r)return null;var s=r[0],i=t.match(e.parsePattern);if(!i)return null;var o=e.valueCallback?e.valueCallback(i[0]):i[0];o=n.valueCallback?n.valueCallback(o):o;var l=t.slice(s.length);return{value:o,rest:l}}}var XMe=/^(\d+)(th|st|nd|rd)?/i,ZMe=/\d+/i,eRe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},tRe={any:[/^b/i,/^(a|c)/i]},nRe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},rRe={any:[/1/i,/2/i,/3/i,/4/i]},sRe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},iRe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},aRe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},oRe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},lRe={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},cRe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},dRe={ordinalNumber:JMe({matchPattern:XMe,parsePattern:ZMe,valueCallback:function(t){return parseInt(t,10)}}),era:ed({matchPatterns:eRe,defaultMatchWidth:"wide",parsePatterns:tRe,defaultParseWidth:"any"}),quarter:ed({matchPatterns:nRe,defaultMatchWidth:"wide",parsePatterns:rRe,defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:ed({matchPatterns:sRe,defaultMatchWidth:"wide",parsePatterns:iRe,defaultParseWidth:"any"}),day:ed({matchPatterns:aRe,defaultMatchWidth:"wide",parsePatterns:oRe,defaultParseWidth:"any"}),dayPeriod:ed({matchPatterns:lRe,defaultMatchWidth:"any",parsePatterns:cRe,defaultParseWidth:"any"})},uRe={code:"en-US",formatDistance:NMe,formatLong:FMe,formatRelative:zMe,localize:YMe,match:dRe,options:{weekStartsOn:0,firstWeekContainsDate:1}},pRe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,hRe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,fRe=/^'([^]*?)'?$/,mRe=/''/g,gRe=/[a-zA-Z]/;function hi(e,t,n){var r,s,i,o,l,c,d,u,p,h,f,g,x,b;Vt(2,arguments);var y=String(t),v=Vl(),C=(r=(s=void 0)!==null&&s!==void 0?s:v.locale)!==null&&r!==void 0?r:uRe,w=xs((i=(o=(l=(c=void 0)!==null&&c!==void 0?c:void 0)!==null&&l!==void 0?l:v.firstWeekContainsDate)!==null&&o!==void 0?o:(d=v.locale)===null||d===void 0||(u=d.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&i!==void 0?i:1);if(!(w>=1&&w<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var S=xs((p=(h=(f=(g=void 0)!==null&&g!==void 0?g:void 0)!==null&&f!==void 0?f:v.weekStartsOn)!==null&&h!==void 0?h:(x=v.locale)===null||x===void 0||(b=x.options)===null||b===void 0?void 0:b.weekStartsOn)!==null&&p!==void 0?p:0);if(!(S>=0&&S<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!C.localize)throw new RangeError("locale must contain localize property");if(!C.formatLong)throw new RangeError("locale must contain formatLong property");var E=Ut(e);if(!pMe(E))throw new RangeError("Invalid time value");var k=lMe(E),j=xMe(E,k),_={firstWeekContainsDate:w,weekStartsOn:S,locale:C,_originalDate:E},D=y.match(hRe).map(function(M){var N=M[0];if(N==="p"||N==="P"){var O=TMe[N];return O(M,C.formatLong)}return M}).join("").match(pRe).map(function(M){if(M==="''")return"'";var N=M[0];if(N==="'")return xRe(M);var O=EMe[N];
272if(O)return MMe(M)&&bD(M,t,String(e)),AMe(M)&&bD(M,t,String(e)),O(j,M,C.localize,_);if(N.match(gRe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+N+"`");return M}).join("");return D}function xRe(e){var t=e.match(fRe);return t?t[1].replace(mRe,"'"):e}function $z(e,t,n){Vt(2,arguments);var r=pm(e,n),s=pm(t,n);return r.getTime()===s.getTime()}function zz(e,t){Vt(2,arguments);var n=Ut(e),r=Ut(t);return n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()}const yD=e=>Array.isArray(e)?e.slice().sort((t,n)=>t.localeCompare(n)).join(", "):`${e}`,zr={DAILY:0,WEEKLY:1,MONTHLY:2},bRe=e=>({row:{borderBottomColor:e.palette.divider,borderBottomStyle:"solid",borderBottomWidth:1,borderTopColor:e.palette.divider,borderTopStyle:"solid",borderTopWidth:1,height:"unset"},cell:{borderTop:"none",borderBottom:"none",borderLeft:"none",borderRightStyle:"solid",borderRightWidth:1,borderRightColor:e.palette.divider,whiteSpace:"pre","&:last-child":{paddingRight:0}},firstCell:{padding:"10px 0 30px",maxWidth:200,width:200},otherCell:{padding:"10px 0 0",textAlign:"center",verticalAlign:"top",width:66,minWidth:66}}),yRe=({date:e,timeFrame:t})=>{let n;switch(t){case zr.WEEKLY:n=a.jsxs(a.Fragment,{children:[hi(e,"M/d/yy"),"-",a.jsx("br",{}),hi(gMe(e),"M/d/yy")]});break;case zr.MONTHLY:n=hi(e,"MMM, yy");break;case zr.DAILY:default:n=hi(e,"M/d/yy");break}return n},dj=({classes:e,dates:t,timeFrame:n})=>a.jsxs(bn,{className:e.row,children:[a.jsx($e,{className:`${e.cell} ${e.firstCell}`,children:"Dates"}),t.map(r=>a.jsx($e,{className:`${e.cell} ${e.otherCell}`,children:a.jsx(yRe,{date:r,timeFrame:n})},r.valueOf()))]});dj.propTypes={classes:A.object.isRequired,dates:A.array,timeFrame:A.number};dj.defaultProps={dates:[],timeFrame:zr.DAILY};const vRe=Be(bRe)(dj),CRe=e=>({box:{width:15,height:15,marginRight:5},green:{backgroundColor:e.palette.success.main},orange:{backgroundColor:e.palette.warning.main},red:{backgroundColor:e.palette.error.main},root:{display:"flex",marginBottom:26},text:{marginRight:19},white:{backgroundColor:e.palette.common.white,borderStyle:"solid",borderWidth:1,borderColor:e.palette.divider}}),Bz=({classes:e})=>a.jsxs("div",{className:e.root,children:[a.jsx("div",{className:`${e.box} ${e.green}`}),a.jsx(I,{className:e.text,children:"Succeeded"}),a.jsx("div",{className:`${e.box} ${e.orange}`}),a.jsx(I,{className:e.text,children:"Running"}),a.jsx("div",{className:`${e.box} ${e.red}`}),a.jsx(I,{className:e.text,children:"Errors"}),a.jsx("div",{className:`${e.box} ${e.white}`}),a.jsx(I,{className:e.text,children:"No Status"})]});Bz.propTypes={classes:A.object.isRequired};const wRe=Be(CRe)(Bz),SRe={SUCCEEDED:"Succeeded",FAILED:"Errors",RUNNING:"Running",ABORTED:"Errors"},jRe=e=>({lozenge:{height:20,width:40,borderRadius:8},NONE:{backgroundColor:"none",border:`1px solid ${e.palette.divider}`},SUCCEEDED:{backgroundColor:e.palette.success.main},RUNNING:{backgroundColor:e.palette.secondary.info},FAILED:{backgroundColor:e.palette.error.main},ABORTED:{backgroundColor:e.palette.error.main}}),uj=({date:e,classes:t,onClick:n,task:r})=>{const s=r===void 0?t.NONE:t[r.state],i=r?`${r.task_nice_id}-${r.kpi_nice_id}-${r.date}`:"",o=r?SRe[r.state]:"No Status";return a.jsx(He,{id:i,name:"task-status-lozenge",onClick:()=>n(r,e),children:a.jsx("div",{className:`${t.lozenge} ${s}`,title:o})})};uj.propTypes={date:A.string.isRequired,classes:A.object.isRequired,onClick:A.func.isRequired,task:A.object};uj.defaultProps={task:void 0};const kRe=Be(jRe)(uj),ERe=e=>({headerCell:{border:"none",borderBottom:`1px solid ${e.palette.divider}`,paddingLeft:23},cell:{borderRight:`1px solid ${e.palette.divider}`,borderLeft:`1px solid ${e.palette.divider}`},row:{height:55}}),Uz=({attribute:e,classes:t,dates:n,name:r,onClick:s,tasks:i,timeFrame:o})=>{let l=Oz;return o===zr.WEEKLY&&(l=(c,d)=>$z(c,d,{weekStartsOn:1})),o===zr.MONTHLY&&(l=zz),a.jsxs(bn,{className:t.row,children:[a.jsx($e,{className:t.headerCell,children:r}),n.map(c=>{const d=i.find(u=>l(u.date,c));return a.jsx($e,{className:t.cell,children:a.jsx(kRe,{attribute:e,date:Z(c).format("M/D/YY"),onClick:s,task:d})},c)})]})};Uz.propTypes={attribute:A.string.isRequired,classes:A.object.isRequired,dates:A.array.isRequired,name:A.string.isRequired,onClick:A.func.isRequired,tasks:A.array.isRequired,timeFrame:A.number.isRequired};const _Re=Be(ERe)(Uz),TRe=e=>({counterCell:{borderTop:`1px solid ${e.palette.divider}`,borderRight:`1px solid ${e.palette.divider}`,borderLeft:`1px solid ${e.palette.divider}`,textAlign:"center",verticalAlign:"bottom"},grayBottomBorder:{borderBottom:`3px solid ${e.palette.divider}`},green:{backgroundColor:e.palette.success.main},greenBottomBorder:{borderBottom:`3px solid ${e.palette.success.main}`},headerCell:{border:"none",paddingLeft:23,paddingTop:20},headerText:{marginBottom:15},orange:{backgroundColor:e.palette.warning.main},orangeBottomBorder:{borderBottom:`3px solid ${e.palette.warning.main}`},pill:{width:30,borderRadius:8,textAlign:"center",color:e.palette.common.white,fontSize:14,marginRight:15,cursor:"default"},pillBox:{display:"flex",marginBottom:8},red:{backgroundColor:e.palette.error.main},redBottomBorder:{borderBottom:`3px solid ${e.palette.error.main}`},root:{borderTop:`3px solid ${e.palette.divider}`,"&:first":{borderTop:"none"}}}),Vz=({classes:e,dates:t,tasks:n,taskName:r,timeFrame:s})=>{let i=0,o=0,l=0;
272n.forEach(({state:d})=>{switch(d){case"SUCCEEDED":i+=1;break;case"RUNNING":o+=1;break;case"ABORTED":case"FAILED":l+=1;break}});let c=Oz;return s===zr.WEEKLY&&(c=(d,u)=>$z(d,u,{weekStartsOn:1})),s===zr.MONTHLY&&(c=zz),a.jsxs(bn,{className:e.root,children:[a.jsxs($e,{className:e.headerCell,children:[a.jsx(I,{className:e.headerText,children:a.jsx("strong",{children:r})}),a.jsxs("div",{className:e.pillBox,children:[a.jsx("div",{className:`${e.pill} ${e.green}`,title:"Succeeded",children:i}),a.jsx("div",{className:`${e.pill} ${e.orange}`,title:"Running",children:o}),a.jsx("div",{className:`${e.pill} ${e.red}`,title:"Errors",children:l})]})]}),t.map(d=>{let u=0,p=0,h=0,f=0;n.forEach(x=>{c(x.date,d)&&(p+=1,x.state==="SUCCEEDED"&&(u+=1),x.state==="RUNNING"&&(h+=1),x.state==="ABORTED"&&(f+=1),x.state==="FAILED"&&(f+=1))});let g=e.grayBottomBorder;return u>0&&(g=e.greenBottomBorder),h>0&&(g=e.orangeBottomBorder),f>0&&(g=e.redBottomBorder),a.jsx($e,{className:`${e.counterCell} ${g}`,children:a.jsxs(I,{className:e.counterText,children:[u,"/",p]})},d)})]})};Vz.propTypes={classes:A.object.isRequired,dates:A.array.isRequired,tasks:A.array.isRequired,taskName:A.string.isRequired,timeFrame:A.number.isRequired};const IRe=Be(TRe)(Vz),DRe=e=>({root:{color:e.palette.primary.main,marginBottom:15,padding:0,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},label:{justifyContent:"left"}}),pj=({children:e,classes:t,id:n,onClick:r})=>a.jsx(re,{classes:{root:t.root,text:t.label},id:n,disableFocusRipple:!0,onClick:r,variant:"text",children:e});pj.propTypes={children:A.node.isRequired,classes:A.object.isRequired,id:A.string,onClick:A.func};pj.defaultProps={id:"my-link-button",onClick:()=>{}};const ARe=Be(DRe)(pj),vD=e=>t=>"__data__"in t&&"stateName"in t.__data__&&t.__data__.stateName===e,MRe=["InProgress","Succeeded","Failed","Cancelled","CaughtError"],hj=({executionHistory:e,stateDefinition:t})=>{const n=m.useRef();return m.useEffect(()=>{const r=[];let s;const i=Array.from(n.current.querySelectorAll("g.state"));let o;e.forEach(l=>{const{type:c}=l,d=Object.keys(l).find(g=>g.endsWith("Details")),u=d&&l[d].name,p=c.split(/(?=[A-Z])/),h=p[p.length-1];if(h==="Entered"?r.push({name:u,events:[]}):r.length&&r[r.length-1].events.push(h),(["Aborted","Failed","Cancelled","CaughtError"].includes(h)||h==="Exited")&&r.length){const{events:g,name:x}=r.pop();s=x;let b;const y=g.pop(),v=g.pop();if(y===void 0?b="Succeeded":y==="Exited"?v?b=v:b="Succeeded":b=y,y==="Aborted"){const C=i.find(vD(s));C&&(C.classList.remove("NotYetStarted"),C.classList.add("Aborted"))}o=i.find(vD(x)),o&&(o.classList.remove("NotYetStarted"),MRe.includes(b)&&o.classList.add(b))}})},[]),a.jsx("div",{id:"state-machine-graph",ref:n,children:a.jsx(LH,{data:t,width:400,height:415,onError:console.log})})};hj.propTypes={executionHistory:A.array,stateDefinition:A.object};hj.defaultProps={executionHistory:void 0,stateDefinition:void 0};const RRe=e=>({action:{color:e.palette.info.main,padding:0,marginBottom:18,fontWeight:"normal",textTransform:"none","&:hover":{textDecoration:"underline"}},actionHeader:{marginBottom:18},closeButton:{width:78},closeButtonContainer:{display:"flex",width:"100%",justifyContent:"flex-end"},closeIconButton:{color:e.palette.secondary.main,padding:0,"&:hover":{backgroundColor:"transparent"}},date:{width:"50%"},dateContainer:{marginBottom:30},dateLabel:{width:"50%"},dateRow:{alignItems:"end",display:"flex"},diagramContainer:{border:`1px solid ${e.palette.divider}`,borderRadius:3,height:415,width:400},dialogContent:{display:"flex",padding:20},dialogTitle:{alignItems:"center",display:"flex",justifyContent:"space-between",padding:20},paper:{boxShadow:e.shadows[24]},rightContainer:{display:"flex",flexDirection:"column",justifyContent:"space-between",paddingLeft:10,width:200},spinnerContainer:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}}),fj=({classes:e,onClose:t,open:n,task:r,taskNames:s})=>{const[i]=gu(),{engagementNiceId:o}=pe(),[l,c]=m.useState(!0),[d,u]=m.useState(!1),[p,h]=m.useState(),[f,g]=m.useState();m.useEffect(()=>{if(o&&r&&r.service){c(!0);const v={engagement_nice_id:o,task_nice_id:r.task_nice_id,service:r.service,start_date:hi(r.date,"yyyy-MM-dd"),[r.service==="ML"?"kpi_nice_id":"data_source"]:r.service==="ML"?r.kpi_nice_id:r.datasource};
272i({apiName:"dataOrchestration",endpoint:"getTaskDetails",parameters:{queryStringParameters:v}}).unwrap().then(C=>{if(!C||!C?.execution_history||!C?.state_definition)throw new Error("Execution does not exist.");h(C.execution_history),g(C.state_definition?JSON.parse(C.state_definition):null),u(!1)}).catch(()=>{h(null),h(null),u(!0)}).finally(()=>c(!1))}},[i,o,r]);const x=a.jsx("div",{className:e.spinnerContainer,children:a.jsx(Ze,{})}),y=r&&r.state&&a.jsxs(a.Fragment,{children:[l===!1&&d===!1&&a.jsx(hj,{stateDefinition:f,executionHistory:p}),l===!0&&x,l===!1&&d&&a.jsx("div",{className:e.spinnerContainer,children:a.jsx(I,{children:"Can't load diagram."})})]});return a.jsxs(yt,{BackdropProps:{id:"task-modal-backdrop"},classes:{paper:e.paper},maxWidth:!1,open:n,onClose:t,children:[a.jsxs(vt,{classes:{root:e.dialogTitle},children:[r&&s[r.task_nice_id],a.jsx(Ie,{className:e.closeIconButton,id:"task-modal-close-icon-button",onClick:t,size:"large",children:a.jsx(ji,{})})]}),a.jsxs(Ct,{className:e.dialogContent,children:[a.jsx("div",{className:e.diagramContainer,children:y}),a.jsxs("div",{className:e.rightContainer,children:[a.jsxs("div",{children:[a.jsxs("div",{className:e.dateContainer,children:[a.jsxs("div",{className:e.dateRow,style:{marginBottom:10},children:[a.jsx(I,{className:e.dateLabel,children:a.jsxs("strong",{children:[r&&r.service==="ML"?"Model date":"Partition date","Â "]})}),a.jsx(I,{className:e.date,children:r&&r.date&&hi(r.date,"M/d/yy")})]}),a.jsxs("div",{className:e.dateRow,children:[a.jsx(I,{className:e.dateLabel,children:a.jsx("strong",{children:"Job start:Â "})}),a.jsx(I,{className:e.date,children:r&&r.start_ts&&hi(new Date(r.start_ts),"M/d/yy")})]}),a.jsxs("div",{className:e.dateRow,children:[a.jsx(I,{className:e.dateLabel,children:a.jsx("strong",{children:"Job end:Â "})}),a.jsx(I,{className:e.date,children:r&&r.end_ts&&hi(new Date(r.end_ts),"M/d/yy")})]}),a.jsxs("div",{className:e.dateRow,style:{marginTop:10},children:[a.jsx(I,{className:e.dateLabel,children:a.jsx("strong",{children:"Number of retries:Â "})}),a.jsx(I,{className:e.date,children:r&&r.number_of_retries})]})]}),a.jsxs("div",{children:[a.jsx(I,{className:e.actionHeader,children:a.jsx("strong",{children:"Actions:"})}),a.jsx(ARe,{id:"rerun-action",onClick:()=>{const v={engagement_nice_id:o,task_nice_id:r.task_nice_id,service:r.service,start_date:hi(r.date,"yyyy-MM-dd"),[r.service==="ML"?"kpi_nice_id":"data_source"]:r.service==="ML"?r.kpi_nice_id:r.datasource};i({apiName:"dataOrchestration",endpoint:"rerunTask",parameters:{body:v}}).unwrap(),t()},children:"Rerun"})]})]}),a.jsx("div",{className:e.closeButtonContainer,children:a.jsx(re,{className:e.closeButton,color:"primary",id:"task-modal-close-button",onClick:t,variant:"contained",children:"Close"})})]})]})]})};fj.propTypes={classes:A.object.isRequired,onClose:A.func.isRequired,open:A.bool.isRequired,task:A.object,taskNames:A.object};fj.defaultProps={task:void 0,taskNames:{}};const NRe=Be(RRe)(fj),ORe={[String(zr.DAILY)]:"Daily",[String(zr.WEEKLY)]:"Weekly",[String(zr.MONTHLY)]:"Monthly"},mj=({value:e,onChange:t})=>a.jsx(Ar,{value:String(e),onChange:n=>t(Number(n.target.value)),options:ORe,sx:{width:100}});mj.propTypes={value:A.number,onChange:A.func.isRequired};mj.defaultProps={value:void 0};const PRe=e=>({controlRow:{display:"flex",marginBottom:30},header:{fontSize:16,fontWeight:"bold",marginBottom:15},list:{margin:0,marginBottom:10,padding:"3px 0 0 16px"},listItem:{fontSize:"14px",lineHeight:1.25,color:e.palette.secondary.main,fontFamily:e.typography.fontFamily},root:{padding:"30px 15px 38px"},table:{width:"auto",maxWidth:"100%",tableLayout:"fixed",borderBottom:`3px solid ${e.palette.divider}`},tableWrapper:{width:"100%",overflow:"auto"}}),CD=({endDate:e,startDate:t})=>!!t&&!!e&&t.isValid()&&e.isValid()&&e>=t,Wz=({classes:e,service:t})=>{const[n]=gu(),{engagementCountry:r,engagementNiceId:s}=pe(),[i,o]=m.useState(),[l,c]=m.useState([]),[d,u]=m.useState([]),[p,h]=m.useState(zr.DAILY),[[f,g],x]=m.useState([Z().subtract(30,"day"),Z()]),[b,y]=m.useState(),[v,C]=m.useState(!1),w=t==="ML"?"kpi_nice_id":"datasource";m.useEffect(()=>{const k=async()=>{const _=await n({apiName:"dataOrchestration",endpoint:"listTaskNames"}).unwrap();u(_.slice().sort((D,M)=>D.execution_order-M.execution_order))},j=async()=>{const _={engagement_nice_id:s,start_date:f.format("YYYY-MM-DD"),end_date:g.format("YYYY-MM-DD"),service:t},D=await n({apiName:"dataOrchestration",endpoint:"listTaskStatuses",parameters:{queryStringParameters:_}}).unwrap();c(D.map(M=>({...M,date:Z(M.date).toDate()})).slice().sort((M,N)=>dMe(M.date,N.date)))};s&&f&&g&&v===!1&&(k(),j())},[s,f,g,v,n,t]),m.useEffect(()=>{if(CD({endDate:g,startDate:f})){const k={start:f.toDate(),end:g.toDate()},{DAILY:j,WEEKLY:_,MONTHLY:D}=zr;switch(p){case j:y(hMe(k));break;case _:y(mMe(k,{weekStartsOn:1}
272));break;case D:y(fMe(k));break}}},[f,g,p]);const S=Object.fromEntries(d.map(k=>[k.nice_id,[]]));l.forEach(({[w]:k,task_nice_id:j})=>{const _=yD(k);j in S&&!S[j].includes(_)&&(S[j].push(_),S[j].sort())});const E=Object.fromEntries(d.map(({nice_id:k,name:j})=>[k,j]));return a.jsxs("div",{className:e.root,children:[a.jsxs(I,{className:e.header,children:[t," Groups"]}),a.jsx(I,{children:a.jsx("strong",{children:"Table Functions:"})}),a.jsx("ul",{className:e.list,children:a.jsx("li",{className:e.listItem,children:a.jsx(I,{children:"Click on a status in table to get info and perform actions."})})}),a.jsxs(T,{sx:{display:"flex",gap:2,mb:3.75,alignItems:"center"},children:[a.jsx(mj,{value:p,onChange:h}),a.jsx(ts,{value:[f,g],setValue:x,locale:r})]}),a.jsx(wRe,{}),CD({endDate:g,startDate:f})&&a.jsxs("div",{className:e.tableWrapper,children:[a.jsxs(Ki,{className:e.table,children:[a.jsx(Ya,{children:a.jsx(vRe,{dates:b,timeFrame:p})}),a.jsx(xl,{children:d.filter(k=>k.service===t).map(({nice_id:k,name:j})=>a.jsxs(Ne.Fragment,{children:[a.jsx(IRe,{dates:b,tasks:l.filter(({task_nice_id:_})=>_===k),taskNiceId:k,taskName:j,timeFrame:p},`${k}-summary`),S[k].map(_=>a.jsx(_Re,{attribute:w,dates:b,onClick:(D,M)=>{o(D||{date:new Date(M),task_nice_id:k}),C(!0)},tasks:l.filter(({[w]:D,task_nice_id:M})=>yD(D)===_&&M===k),taskNames:E,timeFrame:p,name:_},`${k}-${_}`))]},k))})]}),a.jsx(NRe,{onClose:()=>{o(void 0),C(!1)},open:v,task:i,taskNames:E})]})]})};Wz.propTypes={classes:A.object.isRequired,service:A.string.isRequired};const wD=Be(PRe)(Wz),LRe=[{authorized:"DataPipeline.Processing.MLGroups",label:"ML Groups",value:"0"},{authorized:"DataPipeline.Processing.DIGroups",label:"DI Groups",value:"1"}],FRe=()=>a.jsx(T,{sx:{width:ks},children:a.jsxs(fo,{tabs:LRe,variant:"fullWidth",children:[a.jsx(xt,{sx:{p:0},value:"0",children:a.jsx(wD,{service:"ML"})}),a.jsx(xt,{sx:{p:0},value:"1",children:a.jsx(wD,{service:"DI"})})]})}),Lv={Overview:{Component:W1e,path:"/overview"},Planning:{Component:Ske,path:"/planning/my-plans",dependents:{"/planning/view-plan":M1e}},"Planning.NewPlan":{Component:cke,path:"/planning/new-plan"},"ReportsInsights.ConversionSummary":{Component:$ve,path:"/reports-insights/conversion-summary"},"ReportsInsights.ConversionLookback":{Component:uCe,path:"/reports-insights/conversion-lookback"},"ReportsInsights.Journey":{Component:a0e,path:"/reports-insights/journey"},"ReportsInsights.Geography":{Component:zCe,path:"/reports-insights/geography"},"ReportsInsights.ExternalFactors":{Component:U0e,path:"/reports-insights/external-factors"},"ReportsInsights.Audiences":{Component:xie,path:"/reports-insights/audiences"},"ReportsInsights.MediaReporting":{Component:cle,path:"/reports-insights/media-reporting"},"Exports.Attribution":{Component:coe,path:"/exports/attribution"},"Exports.ExportConfiguration":{Component:CIe,path:"/exports/export-configuration"},"DataPipeline.Processing":{Component:FRe,path:"/data-pipeline/processing"},"DataPipeline.DataDictionary":{Component:gce,path:"/data-pipeline/data-dictionary"},"DataSources.Configurations":{Component:Yhe,path:"/data-sources/configurations"},"DataPipeline.DataValidation":{Component:Age,path:"/data-pipeline/data-validation"},"DataPipeline.MachineLearning":{Component:Jfe,path:"/data-pipeline/machine-learning",dependents:{"/data-pipeline/machine-learning/objective/:objective_id":dme}},"DataSources.NameCleaning":{Component:BAe,path:"/data-sources/name-cleaning"},"DataPipeline.DisplaySettings":{Component:tIe,path:"/data-pipeline/display-settings"},"DataSources.Connections":{Component:qme,path:"/data-sources/connections"},"DataSources.FileUpload":{Component:cbe,path:"/data-sources/file-upload"},"Visualize.Dashboards":{Component:Cle,path:"/visualize/dashboards",dependents:{"/visualize/dashboards/:id":mce}},"Visualize.MediaDashboard":{Component:_we,path:"/visualize/media-dashboard"},"DataSources.QueryStudio":{Component:jye,path:"/data-sources/query-studio"},"Settings.Alerts":{Component:uTe,path:"/settings/alerts"},"Settings.Configuration":{Component:Jae,path:"/settings/configuration",dependents:{"/settings/configuration/:id":Uye}},"Settings.UserManagement":{Component:sMe,path:"/settings/user-management"},"Settings.UserActivity":{Component:Ese,path:"/settings/user-activity"}},$Re=e=>Object.entries(e).filter(([r,s])=>s&&r in Lv).map(([r])=>r).map(r=>{const{dependents:s,path:i,Component:o}=Lv[r],l={path:i,Component:o};return s?Object.entries(s).map(([d,u])=>({path:d,Component:u})).concat([l]):l}).flat(),zRe=["Overview","Planning","ReportsInsights.ConversionSummary","ReportsInsights.ConversionLookback","ReportsInsights.Geography","ReportsInsights.Journey","ReportsInsights.Audiences","ReportsInsights.MediaReporting","Exports.Attribution","Exports.ExportConfiguration","DataPipeline.Processing","DataSources.Configurations","DataPipeline.DataValidation","DataPipeline.MachineLearning","DataSources.NameCleaning","DataPipeline.DisplaySettings","Settings.Alerts","Settings.Configuration","Settings.UserActivity","Settings.UserManagement"],Ab="/error",BRe=e=>{const t=zRe.find(n=>!!e[n]);if(t){const n=Lv[t];if(n)return n.path}return null},URe=e=>{switch(e){case"/exports/export-configuration":return"Data Delivery";
272case"/data-pipeline/display-settings":return"Data Display Settings";case"/data-pipeline/processing":return"Data Orchestration";case"/data-pipeline/data-validation":return"Data Verification";case"/data-sources/name-cleaning":return"Name Cleaning";case"/settings/alerts":return"Alerts";case"/settings/configuration":return"Configuration";case"/settings/user-management":return"User Management";default:return null}},VRe=({to:e})=>{const t=Cm(),n=XU(e,t);return a.jsx(Nb,{to:n,replace:!0})},WRe=()=>{const e=_l(),{pathname:t}=es(),{userIsFeaturesAdmin:n,userVerified:r}=gt(),{userLoading:s}=jt();FY();const i=m.useMemo(()=>$Re(e).map(({path:d,Component:u})=>a.jsx(ns,{path:d,element:a.jsx(u,{})},d)),[e]),o=m.useMemo(()=>BRe(e)??Ab,[e]),l=URe(t);let c;return s?c=a.jsxs(a.Fragment,{children:[a.jsx(ns,{path:"oauth2/idpresponse",element:a.jsx(xk,{})}),a.jsx(ns,{path:"oauth2/IdpResponse",element:a.jsx(xk,{})}),a.jsx(ns,{path:"*",element:a.jsx($Y,{})})]}):r?c=a.jsxs(ns,{element:a.jsx(bE,{pageName:l}),children:[i,n&&a.jsx(ns,{path:_M,element:a.jsx(OY,{})}),Bre.map(([d,u])=>a.jsx(ns,{path:d,element:a.jsx(VRe,{to:u})},d)),a.jsx(ns,{path:"*",element:a.jsx(Nb,{to:o,replace:!0})}),o===Ab&&a.jsx(ns,{path:Ab,element:a.jsx(a.Fragment,{children:"Something went wrong"})})]}):c=a.jsxs(a.Fragment,{children:[a.jsx(ns,{path:"login",element:a.jsx(LY,{})}),a.jsx(ns,{path:"*",element:a.jsx(Nb,{to:"login",replace:!0})})]}),a.jsx(m.Suspense,{fallback:a.jsx(bE,{suspense:!0}),children:a.jsx(JU,{children:c})})};u5.configure(hs.amplify);const HRe=()=>a.jsx(Jq,{children:a.jsx(WRe,{})});TD.render(a.jsx(m.StrictMode,{children:a.jsx(HRe,{})}),document.getElementById("root"));export{pre as m};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.