import{j as e,K as g,_ as ue,s as R,a0 as K,V as U,r as f,a1 as fe,y as v,a2 as Me,a3 as ze,o as E,a4 as oe,a5 as We,H as I,Y as Q,T as $,a6 as He,v as B,$ as Ve,D as qe,t as Ye,X as xe,C as ge,a7 as Ke,a8 as Qe,a9 as Xe,u as N,p as Je,aa as M,n as se,B as Ze,ab as re,A as ye,q as ne,ac as et,W as ae,L as X,w as we,x as J,ad as tt,ae as ke,af as st,b as P,ag as le,ah as ot,I as rt,ai as nt,aj as at,M as it,i as lt,f as ct,ak as dt,al as be,am as Se,an as ve,ao as L,ap as je,aq as Re,ar as Ce,as as Pe,at as Te,au as pt,av as ce}from"./index-CCv_8omK.js";import{t as mt}from"./toLower-CL0ukT8_.js";import{a as W,u as ht,W as ut,P as Ee,L as Be}from"./index-Cacyj92F.js";import{A as ft,D as ie,u as xt,W as gt,P as yt,a as De,L as Ue}from"./wait-container-CCe_xsZw.js";import{g as Z}from"./get-safe-url-B_yWzv49.js";import{u as de}from"./useLocalStorage-CbBU4OS9.js";import{L as wt}from"./Launch-DITLracb.js";import{D as kt}from"./DeleteOutline-DmEDUBgP.js";import{g as bt,i as St}from"./spaces-Dif7Qa2a.js";import{I as vt}from"./MoreVert-BUlWqUnK.js";import{y as jt}from"./index-DkBdKcP-.js";import"./url-join-DGMfgD17.js";import"./use-mobile-DvM8SqYH.js";import"./api-CWyPHkC_.js";function Oe({children:s,selected:a=!1}){return e.jsxs(Rt,{children:[s,e.jsx(g,{className:`selected-container ${a?"selected":""}`,children:e.jsx(ue,{className:"selected-icon"})})]})}const Rt=R(g)`
  position: relative;

  .selected-container {
    display: flex !important;
    position: absolute;
    right: 0px;
    bottom: 0px;
    -webkit-box-pack: end;
    justify-content: flex-end;
    align-items: flex-end;
    width: 32px;
    height: 32px;
    border-radius: 0px 0px 8px;
    color: rgb(255, 255, 255);
    overflow: hidden;
    transition: all 0.4s ease 0s;

    &::after {
      position: absolute;
      z-index: 0;
      left: 60px;
      top: 60px;
      display: block;
      width: 0px;
      height: 0px;
      border-width: 16px;
      border-style: solid;
      border-color: transparent #1dc1c7 #1dc1c7 transparent;
      transition: all 0.1s ease 0s;
      content: '';
    }

    .selected-icon {
      visibility: hidden;
      width: 60%;
      height: 60%;
      position: relative;
      z-index: 2;
      margin: 0px 1px 1px 0px;
      font-size: 16px;
      transition: all 0.2s ease 0s;
    }
  }

  .selected-container.selected {
    &::after {
      left: 0px;
      top: 0px;
    }

    .selected-icon {
      visibility: visible;
    }
  }
`;Oe.propTypes={children:K.node.isRequired,selected:K.bool};const _e=f.createContext({}),{Provider:Ct,Consumer:us}=_e;function Ae({children:s}){const{t:a}=U(),[t,l]=de("spaceGatewaysForRestore",[{name:"Prod DID Spaces",url:"https://www.didspaces.com/app",protected:!0},{name:"Staging DID Spaces",url:"https://spaces.staging.arcblock.io/app",protected:!0}]),[p,u]=de("selectedSpaceGatewayForRestore",t.find(n=>n.url==="https://www.didspaces.com/app")),d=n=>{const o=t.find(m=>n.url===m.url);if(o)throw new Error(a("storage.spaces.gateway.add.duplicate",{name:o.name}));l(()=>[...t,ze(n)]),u(n)},i=n=>{if(n.url===p.url)throw new Error(a("storage.spaces.gateway.delete.failedForSelected"));l(()=>t.filter(o=>o.url!==n.url))},x=n=>{u(n)};return f.useEffect(()=>{async function n(){const o=await Promise.all(t.map(async m=>{const{data:r}=await fe.get(v(m.url,"/__blocklet__.js?type=json"),{timeout:5e3}).catch(C=>(console.error(C),{data:{}})),h=r.appName??m.name;return Me(m,{name:h})}));l(o)}n()},[]),e.jsx(Ct,{value:{spaceGateways:t,selectedSpaceGateway:p,addSpaceGateway:d,deleteSpaceGateway:i,handleSelectSpaceGateway:x},children:s})}Ae.propTypes={children:E.any.isRequired};function Pt(){return f.useContext(_e)}function Fe({spaceGateway:s,onDeleteSpaceGateway:a=()=>{}}){const{t}=U(),[l,p]=f.useState(!1),[u,d]=f.useState(!1),i=(n,o)=>{n?.stopPropagation(),p(o)},x=async n=>{try{n?.stopPropagation(),d(!0),await a(s),p(!1)}catch(o){console.error(o),I.error(`${t("storage.spaces.gateway.delete.failed")}: ${Q(o)}`)}finally{d(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx(oe,{size:"small",onClick:n=>i(n,!0),children:e.jsx(kt,{})}),e.jsx(We,{title:t("common.delConfirmDescription",{data:`${s?.name}`}),open:l,confirmButton:{text:t("common.confirm"),props:{variant:"contained",color:"error",loading:u}},cancelButton:{text:t("common.cancel"),props:{variant:"contained",color:"primary"}},onConfirm:x,onCancel:n=>i(n,!1)})]})}Fe.propTypes={onDeleteSpaceGateway:E.func,spaceGateway:E.shape({name:E.string.isRequired,url:E.string.isRequired,protected:E.bool}).isRequired};function $e({spaceGateway:s,onDeleteSpaceGateway:a=()=>{},onSelectGateway:t=()=>{},...l}){const p=d=>{d.stopPropagation(),window.open(Z(s.url,{allowDomains:null}))},u=async()=>{await a(s)};return e.jsxs(Tt,{...l,onClick:t,children:[e.jsx(g,{sx:{display:"inline-flex",marginRight:"8px",alignItems:"center"},children:e.jsx("img",{alt:s.name,src:v(s.url,"favicon.ico"),width:"48px",height:"48px"})}),e.jsxs(g,{className:{minWidth:0,display:"flex",flex:1,flexDirection:"row",paddingRight:"64px","& span":{display:"inline-block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},children:[e.jsxs($,{sx:{display:"flex"},component:"span",variant:"subtitle1",style:{fontWeight:"400"},children:[s?.name," "]}),e.jsx($,{sx:{display:"flex"},className:"url",component:"span",variant:"inherit",children:s?.url})]}),e.jsxs(He,{children:[e.jsx(oe,{onClick:p,size:"small",children:e.jsx(wt,{})}),s?.protected!==!0&&e.jsx(Fe,{spaceGateway:s,onDeleteSpaceGateway:u})]})]})}const Tt=R(g)`
  display: flex;
`;$e.propTypes={spaceGateway:E.shape({name:E.string.isRequired,url:E.string.isRequired,protected:E.bool}).isRequired,selected:E.bool,onDeleteSpaceGateway:E.func,onSelectGateway:K.func};function Le({onAddGateway:s=()=>{},...a}){const{t,locale:l}=U(),[p,u]=f.useState(""),[d,i]=f.useState(!1),[x,n]=f.useState(!1),[o,m]=f.useState(""),r=async()=>{try{i(!0);const h=await bt(p,{withSearchParams:!1});if(!await St(h))throw new Error(t("storage.spaces.gateway.add.invalidUrl"));const{data:C}=await fe.get(v(new URL(h).origin,"/__blocklet__.js?type=json")),y={name:C.appName,url:h,protected:!1};await s(y),I.success(t("storage.spaces.addedWithName",{name:y.name})),n(!1)}catch(h){m(`${t("storage.spaces.gateway.add.failed",l)}: ${Q(h)}`)}finally{i(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"middle",color:"primary",variant:"outlined",onClick:()=>n(!0),...a,children:t("storage.spaces.gateway.add.title")}),e.jsxs(Ve,{title:t("storage.spaces.gateway.add.title"),fullWidth:!0,maxWidth:"md",open:x,onClose:()=>n(!1),PaperProps:{style:{minHeight:"auto"}},actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{onClick:h=>{h.stopPropagation(),n(!1)},color:"inherit",children:t("common.cancel")}),e.jsxs(B,{onClick:h=>{h.stopPropagation(),r()},color:"primary","data-cy":"install-blocklet-next-step",disabled:d||!p,variant:"contained",autoFocus:!0,children:[d&&e.jsx(ge,{size:16}),t("common.confirm")]})]}),children:[e.jsx("div",{style:{paddingTop:12,overflowY:"hidden"},children:e.jsx(qe,{component:"div",children:e.jsx($,{component:"div",children:e.jsx(Ye,{label:t("storage.spaces.gateway.add.label"),autoComplete:"off",variant:"outlined",name:"url",fullWidth:!0,value:p,onChange:h=>{m(null),u(h.target.value)},disabled:d,onKeyPress:async h=>{h.key==="Enter"&&(h.preventDefault(),await r())},autoFocus:!0})})})}),!!o&&e.jsx(xe,{severity:"error",style:{width:"100%"},children:o})]})]})}Le.propTypes={onAddGateway:E.func};function Ie({onConnect:s=()=>{},...a}){const{spaceGateways:t,selectedSpaceGateway:l,handleSelectSpaceGateway:p,addSpaceGateway:u,deleteSpaceGateway:d}=Pt(),{t:i}=U(),x=r=>{p(r)},n=async r=>{await u(r)},o=()=>{s(l)},m=async r=>{await d(r)};return e.jsxs(g,{...a,children:[e.jsx(Ke,{children:t.map(r=>{const h=r?.url===l.url;return e.jsx(Oe,{selected:h,children:e.jsx(Qe,{button:!0,selected:h,"data-cy":"get-space-endpoint-for-restore",children:e.jsx(Xe,{children:e.jsx($e,{spaceGateway:r,onDeleteSpaceGateway:m,selected:h,onSelectGateway:()=>x(r)})})},r.url)})})}),e.jsxs(g,{sx:{display:"flex",marginTop:"16px",justifyContent:"center",alignItems:"center"},children:[e.jsx(Le,{onAddGateway:n}),e.jsx(B,{sx:{marginLeft:"16px"},size:"middle",variant:"contained",onClick:o,children:i("storage.spaces.connect.now")})]})]})}Ie.propTypes={onConnect:K.func};const Et=R(g)`
  width: 100%;
  height: 100%;
  overflow-y: auto;
`;function Bt(){const{info:s}=N(),{t:a,locale:t}=f.useContext(Je),l=f.useMemo(()=>s?M(s):"",[s]),p=u=>{const d=new URL(v(u.url,"restore")),i=v(l,"blocklets/restore/verify-ownership");d.searchParams.set("redirectUrl",i),d.searchParams.set("locale",t),window.location.href=Z(d.toString(),{allowDomains:null})};return e.jsx(Ae,{children:e.jsxs(Et,{children:[e.jsx(W,{title:a("blocklet.restoreFromSpaces.connect.title"),subTitle:a("blocklet.restoreFromSpaces.connect.subTitle"),onClickBack:()=>window.history.back()}),e.jsx(g,{sx:{display:"flex",justifyContent:"center"},children:e.jsx(Ie,{sx:{marginTop:"64px",marginBottom:"32px",width:"100%",maxWidth:"720px"},onConnect:p})})]})})}const Dt=R(g)`
  width: 100%;
  height: 100%;
  overflow-y: auto;
`,Y="verify-app-ownership-spaces";function Ut(){const{session:s}=se(),[a]=Ze(),{t,locale:l}=U(),{api:p,info:u}=N(),{api:d}=se(),{meta:i}=re(),x=ye(),n=f.useMemo(()=>u?M(u):"",[u]),[o,m]=ne({loading:!1,isRestoring:!1,isComplete:!1,isOverwrite:!1,shouldReconnect:!1,exists:!1,accessUrl:"",isConnectOpen:!1,isConfirmOpen:!1,connectData:{action:"",checkFn:()=>{},extraParams:{}},connectMessages:{}}),r=a.get("launchType"),h=a.get("nftId"),C=a.get("chainHost"),y=a.get("from"),w=a.get("blocklet_meta_url"),c=a.get("launcherSessionId")||"",T=a.get("launcherUrl")||"",{appDid:j,appPid:O}=i,G=et.getServerAuthMethod(u,r,c,s.user),H=async(k,A)=>{const q=Array.isArray(k)?k.find(b=>!!b.sessionToken):k;q?.sessionToken&&(st(A(q.sessionToken)),await s.refresh()),m({isConnectOpen:!1}),setTimeout(()=>{const b=new URLSearchParams({appDid:j});[{name:"launchType",value:r},{name:"nftId",value:h},{name:"from",value:y},{name:"blocklet_meta_url",value:w},{name:"chainHost",value:C}].forEach(({name:D,value:F})=>{F&&b.set(D,F)}),x(`/blocklets/restore/restore-blocklet?${b.toString()}`)},0)},z=async(k=!1)=>{if(!k){if(o.shouldReconnect){window.location.href=Z(v(n,"blocklets/restore/connect-space"));return}if(s.user)try{m({loading:!0});const b=await p.getBlocklet({input:{did:O,attachRuntimeInfo:!0}});if(b.blocklet){const D=await ke(b.blocklet);if(D){const F=new URL(D);b.blocklet.status!=="running"&&F.searchParams.set("__start__","1"),m({shouldReconnect:!0,exists:!0,accessUrl:F.href,loading:!1})}return}}finally{m({loading:!1})}}if(G==="nft"){const b=new URL(window.location.href);b.pathname=v(window?.env?.apiPrefix??"/",`/api/did/${Y}/token`),b.searchParams.set("appDid",j),b.searchParams.set("endpoint",i.spaceEndpoint),b.searchParams.set("referrer",window.location.href),b.searchParams.set("nftId",h),b.searchParams.set("appPid",i.did);const D={autoConnect:!1,launchType:r,nftId:h};C&&(b.searchParams.set("chainHost",C),D.chainHost=C),k&&b.searchParams.set("overwrite","1");const{data:F}=await d.get(b.href);if(F.error){I.error(F.error);return}D.nw=F.url,m({isConnectOpen:!0,connectData:{action:"verify-restore-by-nft",extraParams:D},connectMessages:{title:t("blocklet.restoreFromSpaces.nftAuthDialog.title"),scan:t("blocklet.restoreFromSpaces.nftAuthDialog.scan"),confirm:t("blocklet.restoreFromSpaces.nftAuthDialog.confirm"),success:t("blocklet.restoreFromSpaces.nftAuthDialog.success")}});return}if(G==="launcher"){const{launcherSession:b,error:D}=await p.getLauncherSession({input:{launcherUrl:T,launcherSessionId:c}});b?m({isConnectOpen:!0,connectData:{action:Y,extraParams:{appDid:j,appPid:i.did,endpoint:i.spaceEndpoint,referrer:window.location.href,restoreFrom:"spaces",overwrite:k?"1":void 0,launcherUrl:T,launcherSessionId:c,chainHost:C}},connectMessages:{title:t("blocklet.restoreBlocklet.verify.title"),scan:t("blocklet.restoreBlocklet.verify.scan"),confirm:t("blocklet.restoreBlocklet.verify.confirm"),success:t("blocklet.restoreBlocklet.verify.success")}}):I.error(`Launch session invalid: ${D}`);return}if(G==="session"){m({isConnectOpen:!0,connectData:{action:Y,extraParams:{appDid:j,appPid:i.did,endpoint:i.spaceEndpoint,referrer:window.location.href,overwrite:k?"1":void 0,restoreFrom:"spaces"}},connectMessages:{title:t("blocklet.restoreBlocklet.verify.title"),scan:t("blocklet.restoreBlocklet.verify.scan"),confirm:t("blocklet.restoreBlocklet.verify.confirm"),success:t("blocklet.restoreBlocklet.verify.success")}});return}const A=new URL(window.location.href);A.pathname=v(window?.env?.apiPrefix??"/",`/api/did/${Y}/token`),A.searchParams.set("appDid",j),A.searchParams.set("appPid",i.did),A.searchParams.set("endpoint",i.spaceEndpoint),A.searchParams.set("referrer",window.location.href),A.searchParams.set("restoreFrom","spaces");const{data:q}=await d.get(A.href);s.login(H,{nw:q.url,openMode:"popup"})},ee=()=>{m({isConnectOpen:!1})},V=()=>{m({isConfirmOpen:!0})},S=()=>{m({isConfirmOpen:!1,isOverwrite:!0}),z(!0)},_=()=>{m({isConfirmOpen:!1})};return f.useEffect(()=>{z()},[]),e.jsxs(Dt,{children:[e.jsx(W,{title:t("blocklet.restoreBlocklet.verify.title"),subTitle:t("blocklet.restoreBlocklet.verify.subTitle"),onClickBack:()=>window.history.back()}),e.jsxs(g,{sx:{textAlign:"center",mt:6},children:[e.jsx(ft,{blocklet:{meta:i},blockletMetaUrl:w}),e.jsxs(g,{sx:{mt:2,mb:2},children:[e.jsx($,{variant:"body2",children:i.title}),e.jsx(ae,{did:j})]}),o.exists&&o.accessUrl&&e.jsxs(e.Fragment,{children:[e.jsx($,{component:"p",variant:"body1",gutterBottom:!0,sx:{color:"orange"},children:t("blocklet.restoreBlocklet.verify.exists")}),e.jsxs($,{component:"div",sx:{marginTop:"32px"},children:[o.accessUrl&&e.jsx(B,{variant:"contained",component:X,href:o.accessUrl,sx:{width:"160px",height:"100%"},children:t("blocklet.restoreBlocklet.verify.open")}),e.jsx(B,{variant:"contained",color:"error",onClick:V,sx:{width:"160px",height:"100%",marginLeft:"32px"},children:t("blocklet.restoreBlocklet.verify.overwrite")})]})]}),!o.exists&&e.jsx(B,{variant:"contained",loading:o.loading,disabled:o.isConnectOpen||o.loading,onClick:z,sx:{width:"180px",height:"100%"},children:t(`blocklet.restoreBlocklet.verify.${o.shouldReconnect?"reconnect":"verify"}`)})]}),o.connectData.isConnectOpen&&e.jsx(ie,{appDid:j,visible:!1}),e.jsx(we,{popup:!0,locale:l,open:o.isConnectOpen,forceConnected:!1,saveConnect:!1,action:o.connectData.action,checkFn:d.get,checkTimeout:5*60*1e3,webWalletUrl:J(u),onSuccess:H,extraParams:o.connectData.extraParams,messages:o.connectMessages,onClose:ee}),o.isConfirmOpen&&e.jsx(tt,{color:"error",title:t("blocklet.restoreBlocklet.overwrite.title"),description:t("blocklet.restoreBlocklet.overwrite.description"),confirm:t("common.confirm"),onCancel:_,onConfirm:S})]})}const pe=R(ht)`
  && .result-footer {
    height: 120px;
    > div {
      flex-wrap: wrap;
    }
  }
`,Ot=nt("@abtnode/webapp:restore-blocklet:step-install"),_t=R(g)`
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow-y: auto;
`,At=R(g)`
  line-height: 1.4em;
  .error-desc {
    margin-top: 8px;
    word-wrap: break-word;
    color: ${s=>s.theme.palette.grey[500]};
  }
`,te={[P.RESTORE_PROGRESS_STATUS.waiting]:0,[P.RESTORE_PROGRESS_STATUS.start]:1,[P.RESTORE_PROGRESS_STATUS.importData]:2,[P.RESTORE_PROGRESS_STATUS.downloading]:3,[P.RESTORE_PROGRESS_STATUS.importDataSuccess]:4,[P.RESTORE_PROGRESS_STATUS.installing]:5,[P.RESTORE_PROGRESS_STATUS.completed]:10},Ft="https://community.arcblock.io/",$t="launcher@arcblock.io";function Lt({appDid:s}){const[a,t]=f.useState(P.RESTORE_PROGRESS_STATUS.waiting),l=at();return l.connect(),f.useEffect(()=>(l.on(P.BlockletEvents.restoreProgress,p=>{s===p?.appDid&&t(p)}),()=>{l.off(P.BlockletEvents.restoreProgress)}),[s,l]),a}function It(){const s=new URL(window.location.href),a=s.searchParams.get("appDid"),t=s.searchParams.get("launchType"),l=s.searchParams.get("nftId"),p=s.searchParams.get("fromLauncher"),u=s.searchParams.get("from"),d=s.searchParams.get("chainHost"),i=Lt({appDid:a}),[x,n]=f.useState(0),o=f.useRef(null),{meta:m}=re(),{t:r}=U(),{api:h,info:C}=N(),[y,w]=ne({nextAccessUrl:"",installError:null}),c=xt(a),{status:T,eventName:j}=c,O=()=>{n(12),o.current&&(clearTimeout(o.current),o.current=null),o.current=setTimeout(()=>{h.getBlocklet({input:{did:a,attachRuntimeInfo:!0}}).then(S=>{S.blocklet&&z(S.blocklet)})},500)},G=()=>{if(c?.runtimeBlocklet?.settings?.initialized){n(11);return}O()},H=[r("blocklet.restoreFromSpaces.progress.waiting"),r("blocklet.restoreFromSpaces.progress.restoring"),r("blocklet.restoreFromSpaces.progress.importData"),r("blocklet.restoreFromSpaces.progress.downloading",{progress:`${i?.data?.completed??100}/${i?.data?.total??100}`}),r("blocklet.restoreFromSpaces.progress.importSuccess"),r("launchBlocklet.waiting.downloading"),r("launchBlocklet.waiting.verifying"),r("launchBlocklet.waiting.downloading"),r("launchBlocklet.waiting.extracting"),r(T==="upgrading"?"common.upgrading":"launchBlocklet.waiting.installing"),r("launchBlocklet.waiting.installed"),r("launchBlocklet.waiting.starting"),r("launchBlocklet.waiting.done")];f.useEffect(()=>{if(i.status===P.RESTORE_PROGRESS_STATUS.error){const S={message:i.message,name:"restoreFailed",action:"retryRestore"};le(S,y.installError)||I.error(Q(S)),w({installError:S});return}n(te[i.status]||0)},[i.status]),f.useEffect(()=>{if(t==="serverless"&&j===P.BlockletEvents.nftConsumed){G();return}if(i.status===P.RESTORE_PROGRESS_STATUS.waiting){n(te[i.status]||0);return}if(i.status!==P.RESTORE_PROGRESS_STATUS.completed&&i.status!==P.RESTORE_PROGRESS_STATUS.error&&T!=="running"){n(te[i.status]||0);return}switch(T){case"waiting":n(6);break;case"downloading":n(7);break;case"installing":case"upgrading":n(8);break;case"installed":if(t==="serverless"&&!ot(c))break;G();break;case"starting":n(11);break;case"running":n(12),O();break;case"stopped":O();break;case"corrupted":case"error":{c?.stopPolling();const S={message:c?.error?.message,name:c?.eventName,action:"retryRestore"},_=(k={})=>{!le(S,y.installError)&&c?.error?.message&&I.error(Q(c.error)),w({installError:S,...k})};h.getBlocklet({input:{did:a,attachRuntimeInfo:!0}}).then(({blocklet:k})=>{k?.settings?.initialized&&(S.action="retryStart"),_()}).catch(()=>{_()})}break}},[T,j,c]);const z=async S=>{const _=await ke(S);if(it(_))return;const k=new URL(_);k.searchParams.set("serverUrl",M(C)),S.status!=="running"&&k.searchParams.set("__start__","1"),p&&k.searchParams.set("fromLauncher",p),u&&k.searchParams.set("from",u),t&&k.searchParams.set("launchType",t),l&&k.searchParams.set("nftId",l),d&&k.searchParams.set("chainHost",d),c?.stopPolling(),w({nextAccessUrl:k.href,status:S.status,resultMessage:lt.isBlockletRunning(S)?{variant:"success",title:r("blocklet.restoreFromSpaces.restore.completeTitle"),subTitle:"",footer:r("common.open")}:{variant:"info",title:r("blocklet.restoreFromSpaces.restore.installedTitle"),subTitle:r("blocklet.restoreFromSpaces.restore.installedSubTitle"),footer:r("common.configuration")}})},ee=async()=>{w({installError:null,nextAccessUrl:""}),await h.startBlocklet({input:{did:a}}),c?.startPolling()};if(y.installError){const S={retryRestore:e.jsx(B,{variant:"contained",className:"bottom-button","data-cy":"retry-install",component:rt,to:`/blocklets/restore/verify-ownership${window.location.search}`,children:r("common.retry")}),retryStart:e.jsx(B,{variant:"contained",className:"bottom-button","data-cy":"retry-start",onClick:()=>ee(),children:r("common.retry")})},_=y.installError.name?y.installError.name.replace("blocklet.",""):"installFailed";return e.jsx(pe,{variant:"error",title:m?.title,subTitle:e.jsxs(At,{children:[e.jsx("div",{children:r(`launchBlocklet.error.${_}`)}),y.installError.message&&e.jsx("div",{className:"error-desc",children:r("common.errorMessage")+y.installError.message})]}),footer:e.jsxs(me,{children:[S[y.installError.action],t==="serverless"&&e.jsx("div",{style:{marginTop:"24px"},dangerouslySetInnerHTML:{__html:r("blocklet.restoreFromSpaces.restore.support",{communityLink:Ft,supportEmail:$t})}})]})})}const V=!!y.nextAccessUrl;return Ot("render",{status:T,eventName:j,launchType:t,runtimeBlockletState:c,state:y}),e.jsxs(_t,{children:[!V&&e.jsxs(e.Fragment,{children:[e.jsx(W,{title:r("blocklet.restoreBlocklet.restore.title"),subTitle:r("blocklet.restoreFromSpaces.restore.subTitle")}),e.jsxs(gt,{children:[e.jsx(ut,{increaseSpeed:.3,messageLoop:!1,message:e.jsx(yt,{steps:H,stepIndex:x,autoGrowth:x===10?1e3:4e3})}),[5,7,8].includes(x)&&e.jsx(ie,{appDid:a})]})]}),V&&e.jsx(pe,{variant:y.resultMessage.variant,title:y.resultMessage.title,subTitle:y.resultMessage.subTitle,footer:e.jsx(me,{children:e.jsx(B,{variant:"contained",style:{width:"200px"},component:X,href:y.nextAccessUrl,children:y.resultMessage.footer})})})]})}const me=R(g)`
  padding-top: 24px;
`;function Ne(){return e.jsx(It,{})}function Nt(){const s=ct(),a=De(),{t,locale:l}=U(),{info:p}=N(),u=dt(),{meta:d}=re(),i=f.useMemo(()=>p?M(p):"",[p]),x=J(p),n=v(be(),"/blocklets/restore"),o=[{key:"verify-ownership",name:t("blocklet.restoreBlocklet.verify.title"),path:v(n,"verify-ownership")},{key:"restore-blocklet",name:t("blocklet.restoreFromSpaces.restore.title"),path:v(n,"restore-blocklet")}];let m=[];mt(u.get("from"))==="launcher"?m=[{key:"purchase-space",name:t("launchBlocklet.steps.purchaseSpace")},{key:"prepare-space",name:t("launchBlocklet.steps.prepareSpace")},...o]:m=[{key:"connect-space",name:t("blocklet.restoreFromSpaces.connect.title"),path:v(n,"connect-space")},{key:"select-blocklet",name:t("blocklet.restoreFromSpaces.selectBlocklet.title")},...o];const r=e.jsx(zt,{className:`${i?"logo-can-click":""}`,children:e.jsx(X,{href:i||"",target:"_blank",children:e.jsx(Ue,{logo:a})})});return e.jsx(Ee,{steps:m,children:e.jsx(Wt,{blockletMeta:d,locale:l,useOfSkeleton:!1,navLogo:r,navSubTitle:t("blocklet.restoreFromSpaces.navSubTitle"),loading:!1,headerEndAddons:e.jsx(Re,{webWalletUrl:x,SessionContext:Ce}),pcWidth:"80%",style:{height:"100%"},logoUrl:d?.logo,theme:s,children:e.jsxs(Mt,{children:[e.jsx(Se,{styles:Gt}),e.jsxs(ve,{children:[e.jsx(L,{path:"connect-space",element:e.jsx(Bt,{})}),e.jsx(L,{path:"verify-ownership",element:e.jsx(Ut,{})}),e.jsx(L,{path:"restore-blocklet",element:e.jsx(Ne,{})}),e.jsx(L,{path:"*",element:e.jsx(je,{to:"connect-space",replace:!0})})]})]})})})}const Gt=Pe`
  html,
  body,
  #root,
  #root > .wrapper {
    height: 100%;
  }
`,Mt=R.div`
  ${s=>s.theme.breakpoints.up("md")} {
    padding-top: 34px;
  }
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;

  .bottom-button {
    min-width: 200px;
  }
`,zt=R.div`
  margin-top: -1px;
  &.logo-can-click {
    cursor: pointer;
  }
`,Wt=R(Be)`
  .layout-content {
    min-width: 0;
    flex: 1 1 0;
  }
`;function Ge({onSelect:s=()=>{}}){const{api:a}=N(),{t,locale:l}=U(),[p,u]=f.useState(!1),[d,i]=f.useState([]),[x,n]=f.useState(""),[o,m]=f.useState(null),r=ye(),h=async()=>{try{u(!0),m(!1);const{getBlocklets:{blocklets:c},getBlockletsFromBackup:{backups:T}}=await a.doBatchQuery({getBlocklets:{input:{}},getBlockletsFromBackup:{input:{}}});i((T||[]).filter(j=>!(c||[]).some(O=>j.appPid===O.meta?.did)).sort((j,O)=>O.createdAt-j.createdAt).slice(0,200)),u(!1)}catch(c){u(!1),m(c.message)}};f.useEffect(()=>{h()},[]);const C=()=>{const c=d.find(j=>j.appDid===x);s({did:c.appDid,name:c.appDid,title:c.name});const T=new URL(window.location.href);T.searchParams.set("appDid",c.appDid),T.searchParams.set("appName",c.name),r(`/blocklets/restore/verify-ownership${T.search}`)},y=c=>{n(c.appDid)};let w=null;return o?w=e.jsx(xe,{severity:"error",style:{width:"100%",marginTop:8},children:o}):p?w=e.jsx(ge,{size:16}):d.length?w=e.jsx(Vt,{children:d.map(c=>e.jsxs(qt,{className:`middle-font-size space ${x===c.appDid?"selected":""}`,onClick:()=>y(c),children:[e.jsxs("div",{className:"left",children:[e.jsx("div",{className:"header",children:e.jsx(g,{sx:{width:40,height:40},children:e.jsx(Te,{did:c.appDid,size:40})})}),e.jsxs("div",{className:"body",children:[e.jsx($,{className:"text",sx:{color:"text.secondary"},children:c.name}),e.jsx($,{className:"text middle-font-size",sx:{color:"text.secondary"},children:e.jsx(ae,{responsive:!1,compact:!0,inline:!0,copyable:!1,size:12,did:c.appDid})})]}),e.jsxs(g,{className:"footer small-font-size",sx:{color:"text.secondary"},children:[t("blocklet.restoreFromServer.backupIn")," ",pt(c.createdAt,l)]})]}),e.jsx("div",{className:"right",children:e.jsx("div",{className:"more",children:e.jsx(oe,{onClick:()=>{},className:"more-btn",size:"large","aria-label":"more functions",children:e.jsx(vt,{color:"disabled"})})})}),e.jsx("div",{className:"selected-container",children:e.jsx(ue,{className:"selected-icon"})})]},c.appDid))}):w=e.jsx(jt,{children:t("common.empty")}),e.jsxs(Ht,{style:{width:"100%"},children:[e.jsx(W,{title:t("blocklet.restoreFromServer.selectTitle"),subTitle:t("blocklet.restoreFromServer.description")}),e.jsx(g,{className:"main-body",sx:{mt:4,mx:3},children:w}),e.jsx(g,{className:"main-footer",sx:{display:"flex",justifyContent:"center"},children:e.jsx(B,{sx:{width:"180px",height:"100%"},onClick:c=>{c.stopPropagation(),C()},color:"primary","data-cy":"install-blocklet-next-step",variant:"contained",disabled:p||o||!x,children:t("common.restore")})})]})}Ge.propTypes={onSelect:E.func};const Ht=R(g)`
  .main-body {
    height: 50vh;
    ${s=>s.theme.breakpoints.down("md")} {
      height: 80vh;
    }

    overflow: auto;
  }
  .main-footer {
    padding-top: 24px;
    padding-bottom: 24px;
    ${s=>s.theme.breakpoints.down("md")} {
      position: fixed;
      bottom: 16px;
      width: 100%;
      padding-bottom: 0;
    }
  }
`,Vt=R(g)`
  display: block;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  max-width: 1000px;
  margin: 0 auto;

  .space {
    display: flex;
    margin: 8px auto;

    .selected-container {
      position: absolute;
      right: 0px;
      bottom: 0px;
      display: flex;
      -webkit-box-pack: end;
      justify-content: flex-end;
      align-items: flex-end;
      width: 30px;
      height: 30px;
      border-radius: 0px 0px 7px;
      color: rgb(255, 255, 255);
      overflow: hidden;
      transition: all 0.3s ease 0s;

      &::after {
        position: absolute;
        z-index: 0;
        left: 30px;
        top: 30px;
        display: block;
        width: 0px;
        height: 0px;
        border-width: 15px;
        border-style: solid;
        /* border-color: transparent rgb(29, 193, 199) rgb(29, 193, 199) transparent; */
        border-color: transparent ${s=>s.theme.palette.primary.main}
          ${s=>s.theme.palette.primary.main} transparent;
        transition: all 0.1s ease 0s;
        content: '';
      }

      .selected-icon {
        visibility: hidden;
        width: 60%;
        height: 60%;
        position: relative;
        z-index: 2;
        margin: 0px 1px 1px 0px;
        font-size: 16px;
        transition: all 0.2s ease 0s;
      }
    }
  }

  .space.selected {
    background-color: ${({theme:s})=>ce(s.palette.primary.light,.12)};
    border-color: ${({theme:s})=>ce(s.palette.primary.light,.12)};

    .selected-container {
      &::after {
        left: 0px;
        top: 0px;
      }

      .selected-icon {
        visibility: visible;
      }
    }
  }
`,qt=R(g)`
  display: flex;
  position: relative;
  width: 100%;
  padding: 10px;
  border: 1 solid;
  border-color: ${({theme:s})=>s.palette.divider};
  cursor: pointer;

  .left {
    display: flex;
    align-items: flex-start;
    width: 100%;
    margin: 0px 20px 0px 0px;

    .header {
      padding: 5px 16px 0 0;
    }

    .body {
      display: flex;
      flex-direction: column;
      width: 100%;
    }

    .footer {
      display: flex;
      align-items: center;
      flex-shrink: 0;
      height: 100%;
    }
  }

  .right {
    display: flex;
  }

  ${s=>s.theme.breakpoints.down("md")} {
    .left {
      display: flex;
      flex-direction: column;
      margin-right: 20px;

      .header {
        display: none;
      }

      .footer {
        margin-top: 6px;
        margin-left: 0px;
        padding: 2px 0px;
        height: auto;
      }
    }

    .right {
      width: auto;
    }

    .text {
      display: -webkit-box;
      overflow: hidden;
      -webkit-box-orient: vertical;
    }
  }

  // 公共属性
  .middle-font-size {
    font-size: 14px;
  }

  .small-font-size {
    font-size: 12px;
  }
`,Yt=R(g)`
  width: 100%;
  height: 100%;
  overflow-y: auto;
`,he="verify-app-ownership-disk";function Kt(){const s=new URL(window.location.href),a=s.searchParams.get("appDid"),t=s.searchParams.get("appName"),{t:l,locale:p}=U(),{api:u,info:d}=N(),{session:i,api:x}=se(),n=f.useMemo(()=>d?M(d):"",[d]),[o,m]=ne({isRestoring:!1,isComplete:!1,connectData:{isConnectOpen:!1,action:"",checkFn:()=>{},extraParams:{}}}),r=async()=>{if((await u.getBlocklet({input:{did:a}})).blocklet){I.error(`Blocklet ${t}(${a}) already exists`),m({shouldReconnect:!0});return}m({connectData:{isConnectOpen:!0,action:he,extraParams:{appDid:a,restoreFrom:"disk"}}})},h=()=>{m({connectData:{isConnectOpen:!1}}),setTimeout(()=>{const w=new URL(v(n,`blocklets/restore/restore-blocklet${window.location.search}`));window.location.href=Z(w.href)},0)},C=async()=>{if(!i.user){const w=new URL(window.location.href);w.pathname=v(window?.env?.apiPrefix??"/",`/api/did/${he}/token`),w.searchParams.set("appDid",a),w.searchParams.set("restoreFrom","disk");const{data:c}=await x.get(w.href);i.login(h,{nw:c.url,openMode:"popup"});return}await r()},y=()=>{m({connectData:{isConnectOpen:!1}})};return f.useEffect(()=>{C()},[]),e.jsxs(Yt,{children:[e.jsx(W,{title:l("blocklet.restoreBlocklet.verify.title"),subTitle:l("blocklet.restoreBlocklet.verify.subTitle")}),e.jsxs(g,{sx:{textAlign:"center",mt:6},children:[e.jsx(Te,{did:a,size:128}),e.jsxs(g,{sx:{mt:2,mb:2},children:[e.jsx($,{variant:"body2",children:t}),e.jsx(ae,{did:a})]}),e.jsx(B,{variant:"contained",disabled:o.connectData.isConnectOpen,onClick:C,sx:{width:"180px",height:"100%"},children:l(`blocklet.restoreBlocklet.verify.${o.shouldReconnect?"reconnect":"verify"}`)})]}),o.connectData.isConnectOpen&&e.jsx(ie,{appDid:a,visible:!1}),e.jsx(we,{popup:!0,locale:p,open:o.connectData.isConnectOpen,forceConnected:!1,saveConnect:!1,action:o.connectData.action,checkFn:x.get,checkTimeout:5*60*1e3,webWalletUrl:J(d),onSuccess:h,extraParams:o.connectData.extraParams,messages:{title:l("blocklet.restoreBlocklet.verify.title"),scan:l("blocklet.restoreBlocklet.verify.scan"),confirm:l("blocklet.restoreBlocklet.verify.confirm"),success:l("blocklet.restoreBlocklet.verify.success")},onClose:y})]})}function Qt(){const s=De(),{t:a,locale:t}=U(),{info:l}=N(),{meta:p,setMeta:u}=f.useState({}),d=f.useMemo(()=>l?M(l):"",[l]),i=J(l),x=v(be(),"/blocklets/restore"),n=[{key:"select",name:a("blocklet.restoreFromServer.selectTitle"),path:v(x,"select")},{key:"verify-ownership",name:a("blocklet.restoreBlocklet.verify.title"),path:v(x,"verify-ownership")},{key:"restore-blocklet",name:a("blocklet.restoreBlocklet.restore.title"),path:v(x,"restore-blocklet")}],o=e.jsx(Zt,{className:`${d?"logo-can-click":""}`,children:e.jsx(X,{href:d||"",target:"_blank",children:e.jsx(Ue,{logo:s})})});return e.jsx(Ee,{steps:n,children:e.jsx(Be,{blockletMeta:{...p,registryUrl:""},locale:t,useOfSkeleton:!1,navLogo:o,headerEndAddons:e.jsx(Re,{webWalletUrl:i,SessionContext:Ce}),pcWidth:"80%",style:{height:"100%"},logoUrl:p?.logo,children:e.jsxs(Jt,{children:[e.jsx(Se,{styles:Xt}),e.jsxs(ve,{children:[e.jsx(L,{path:"select",element:e.jsx(Ge,{onSelect:u})}),e.jsx(L,{path:"verify-ownership",element:e.jsx(Kt,{})}),e.jsx(L,{path:"restore-blocklet",element:e.jsx(Ne,{})}),e.jsx(L,{path:"*",element:e.jsx(je,{to:`select${window.location.search}`,replace:!0})})]})]})})})}const Xt=Pe`
  html,
  body,
  #root,
  #root > .wrapper {
    height: 100%;
  }
`,Jt=R.div`
  ${s=>s.theme.breakpoints.up("md")} {
    padding-top: 34px;
  }
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;

  .bottom-button {
    min-width: 200px;
  }
`,Zt=R.div`
  margin-top: -1px;
  &.logo-can-click {
    cursor: pointer;
  }
`;function fs(){const{search:s}=window.location;return s.includes("restoreFrom=server")?e.jsx(Qt,{}):e.jsx(Nt,{})}export{fs as default};
