import{sourceChannel as De,app as t,clearPrivateView as w,reopen as f,settleSaveElsewhere as J,pauseAccessCheck as Q,captureEmailChangeToken as Oe,settingsFromHistory as Ue,refreshSession as y,pruneSharedDrafts as Me,startPhone as Ne,pageTitle as X,readerPath as Z,knownPath as ee,installOpener as Ge,installRouter as Ye,disposeViews as He,countHour as Be,countNewAccountRead as Fe,installAskWaiting as Ke,returnAskDue as je,goalAskDue as $e,forgetAhead as _e,rememberedUser as k,knownSession as ze,start as U,yieldToBrowser as Je,openSettings as P,settingsReady as x,run as te,reviewStore as Qe,readAhead as Xe,readyHeadStart as ne,shellSettings as ae,sourceStore as re,showAccountRail as I,appShell as E,sessionModuleHint as M,settingsClosed as Ze,pagesFor as et}from"./app-chunk-email-change-token-DRXPGcrm.mjs";import{theme as C,heardPulse as tt,ensurePageStyles as nt}from"./app-chunk-account-pulse-D4LShi5j.mjs";import{notice as v,parsedPage as ie,button as N,hydrateLibraryShell as oe,link as se}from"./app-chunk-account-return-5Iv5Wqbu.mjs";import{voice as at}from"./app-chunk-source-text-BYmy6w5z.mjs";import{keepOffline as G}from"./app-chunk-offline-register-DCiCR7Sr.mjs";import{prepareReader as rt}from"./reader-boot.mjs";import{feature as ce}from"./app-chunk-extension-identity-BWxnG5ap.mjs";import{el as R,statusLine as le}from"./app-chunk-ui-dom-BGh5f48c.mjs";import"./app-chunk-extension-bridge-jM7iER6l.mjs";import"./app-chunk-key-map-CA0JcvGF.mjs";import"./app-chunk-brand-CZCZSYdJ.mjs";async function it(...e){const n=t.generation,a=t.sourceRevision;if(await t.sessionChecked,n!==t.generation||a!==t.sourceRevision)throw Error("The source changed. Inspect it again.");const o=t.session?.user?.id??null,s=t.session?.access?.binding??null,i=await import("./app-chunk-expression-save-Oinz-fqU.mjs");if(n!==t.generation||a!==t.sourceRevision)throw Error("The source changed. Inspect it again.");if(o!==(t.session?.user?.id??null)||s!==(t.session?.access?.binding??null))throw Error("Your account changed. Check the destination and retry this save.");return i.beginSave(...e)}const ot=e=>()=>e().catch(n=>{if(!navigator.onLine||!(n instanceof TypeError))throw n;let a=0;try{a=Number(sessionStorage.getItem("mtw-stale-code"))||0,sessionStorage.setItem("mtw-stale-code",String(Date.now()))}catch{throw n}if(Date.now()-a<6e4)throw n;return location.reload(),new Promise(()=>{})}),l=Object.fromEntries(Object.entries({auth:()=>import("./app-chunk-account-source-CW0r9BQ-.mjs").then(function(e){return e.a}),reader:()=>import("./app-chunk-immersion-progress-CUmuh9iX.mjs").then(function(e){return e.r}),retained:()=>import("./app-chunk-retained-passage-D4_PBoS-.mjs").then(function(e){return e.r}),offline:()=>import("./app-chunk-offline-page-C1aa-NWI.mjs"),library:()=>import("./app-chunk-library-Wp72d2xI.mjs"),review:()=>import("./app-chunk-review-rest-CX-6zjKh.mjs").then(function(e){return e.r}),reviewEntry:()=>import("./app-chunk-grove-song-CEtXWEbk.mjs").then(function(e){return e.r}),home:()=>import("./app-chunk-knowledge-card-CHlSvgUL.mjs").then(function(e){return e.h}),homeGuest:()=>import("./app-chunk-home-so-far-D6rirPAv.mjs").then(function(e){return e.h}),share:()=>import("./app-chunk-google-doc-CFk8egGv.mjs").then(function(e){return e.p}),account:()=>import("./app-chunk-account-email-CChFfZHz.mjs").then(function(e){return e.a}),help:()=>import("./app-chunk-feedback-C2pK53xR.mjs").then(function(e){return e.h}),keys:()=>import("./app-chunk-keys-opening-BAryJRU1.mjs").then(function(e){return e.k}),backpack:()=>import("./app-chunk-backpack-opening-D2X-nIQU.mjs").then(function(e){return e.b}),immersion:()=>import("./app-chunk-immersion-import-oDQuI7B1.mjs").then(function(e){return e.i}),guest:()=>import("./app-chunk-guest-BKY-sUoG.mjs")}).map(([e,n])=>[e,ot(n)])),st=(e,n)=>{const[a]=et(e,n);return a?!M()&&["backpack","immersion"].includes(a)?l.guest():a==="home"&&!M()?l.homeGuest():l[a]():null},V=(e,n)=>{const a=E(e);return Z(n)?a.classList.add("reader"):e&&n==="/backpack"&&a.classList.add("backpack-list"),a},ct=e=>{const n=e.split("/")[1];for(const a of document.querySelectorAll("#app .global-nav [data-destination]"))a.dataset.destination===n?a.setAttribute("aria-current","page"):a.removeAttribute("aria-current")};async function lt(){if(b)return;me=location.pathname,at.stop(),He(),t.reviewSettings=null;const e=++t.generation;t.viewMark={generation:e,value:tt()},t.request?.abort();let n=location.pathname;const a=new URLSearchParams(location.search),o=n==="/immersion/read"?!a.get("id"):n==="/immersion/share"&&!["share","title","text","url"].some(r=>a.get(r));(n==="/offline"||n==="/offline/read"||o)&&(history.replaceState(null,"","/immersion"),n="/immersion");const s=n==="/home"?"home":n==="/review"?"review":n==="/read"?"read":n.startsWith("/backpack")?"backpack":n.startsWith("/immersion")?"immersion":n.startsWith("/library/read/")?"reading":n.startsWith("/library")?"library":"";if(s&&(ce("open:"+s),Be(s)),s==="immersion")try{localStorage.setItem("mtw-immersion-opened","1")}catch{}(s==="reading"||n==="/immersion/read")&&Fe(),(Ke()||je()||$e())&&!n.startsWith("/auth")&&setTimeout(()=>{e===t.generation&&import("./app-chunk-account-install-DBce1wcE.mjs").then(({installMoment:r})=>r()).catch(()=>{})},1500),rt(n),_e();const i=n==="/review"?ft():null;if(await nt(n),e!==t.generation)return;if(t.reviewLoading=n==="/review",n!="/immersion/read"&&n!="/offline/read"&&(t.immersionCurrentId=null),n.startsWith("/library")){const r=!document.querySelector(".library-page")&&await import("./app-chunk-library-offline-Buz785qx.mjs").then(({keptPage:h})=>h(n)).catch(()=>null);return e!==t.generation?void 0:r&&mt(ie(r))?de(e):!navigator.onLine||!document.querySelector(".library-page")?(await l.offline()).offlinePage(e,n):de(e)}n!=="/"&&(document.title=X(n));const c=/^\/backpack\/([^/]+)\/inspect$/.exec(n)?.[1];if(c&&(t.readerDraft=null,t.intent=null,t.main=V(null,n)),n==="/review")return gt(e,i);if(n==="/"&&!navigator.onLine)return history.replaceState(history.state,"","/home"),(await l.offline()).offlinePage(e,"/home");if(n==="/"&&!t.readerDraft?.account)return wt();if(!ee(n))return document.querySelector("#main[data-guest-first-page]")||navigator.onLine!==!1&&!document.querySelector("#main[data-boot-ready]")?vt(e):yt(e);n==="/read"&&document.querySelector("#app.boot-shell form[data-reader-paste]")&&(t.main=V(k(),n));const u=n.startsWith("/auth")?null:ze();if(!u&&!t.main?.isConnected&&!n.startsWith("/auth")&&!document.querySelector("#app.boot-shell")){const r=document.querySelector("#app > #main");r?(r.inert=!0,ct(n),setTimeout(()=>{e===t.generation&&r.isConnected&&(t.main=V(k(),n))},300)):t.main=V(k(),n)}const m=st(n,a);m?.catch(()=>{});let d=u;if(u)y().then(r=>{r&&(r.user?.id!==u.user?.id||r.access?.binding!==u.access?.binding)&&f()},r=>{e===t.generation&&Te(n,r,e).catch(h=>v(h.message))});else{try{d=await y()}catch(r){e===t.generation&&await Te(n,r,e);return}if(!d)return;if(e!==t.generation)return U()}if((d.user||n==="/read")&&G(),t.readerDraft?.account&&t.readerDraft.account!==t.session.user?.id&&(t.readerDraft=null),t.main=V(t.session.user,n),t.main.dataset.account=t.session.user?.id??"",v(""),await Je(),e!==t.generation)return;const g=()=>t.main?.isConnected&&t.generation===e&&t.session?.access?.binding===d.access.binding;if(n.startsWith("/auth")){const{authPage:r}=await m;e===t.generation&&await r()}else if(n==="/home"){const{homePage:r,startView:h}=await(t.session.user?l.home():l.homeGuest());if(e!==t.generation)return;t.session.user?t.homeView=r({main:t.main,access:{...t.session.access},active:g}):h(t.main)}else if(n==="/help"){const{helpPage:r}=await m;e===t.generation&&(t.helpView=r(t.main,{session:d,active:()=>e===t.generation&&t.main?.isConnected&&t.session?.access?.account===d.access?.account&&t.session?.access?.binding===d.access?.binding}))}else if(n==="/keys"){const{keysPage:r}=await m;if(e!==t.generation)return;t.keysView=r(t.main,{theme:C,openSettings:P}),x(),new URL(location.href).searchParams.get("settings")==="1"&&(history.replaceState(null,"","/keys"),P())}else if(n==="/account"){const{accountPage:r}=await m;e===t.generation&&r()}else if(n==="/immersion/share")await(await m).phoneShare({main:t.main,session:d,active:()=>e===t.generation&&t.session?.access?.binding===d.access?.binding});else if(n==="/immersion"){if(t.session.user){const{immersionPage:h}=await l.immersion();if(!g())return;const p=await h({main:t.main,access:{...t.session.access},active:g});g()&&(t.immersionView=p)}else{const{immersionGuest:h}=await l.guest();if(e!==t.generation)return;h(t.main)}const r=()=>{import("./app-chunk-immersion-progress-CUmuh9iX.mjs").then(function(h){return h.r}).catch(()=>{})};if(e!==t.generation)return;if(t.session.user)globalThis.requestIdleCallback?requestIdleCallback(r,{timeout:2e3}):setTimeout(r,500);else{const h=t.main,p=new AbortController,q=W=>{e!==t.generation?p.abort():W.target.closest?.('a[href^="/read"]')&&(p.abort(),r())};for(const W of["pointerover","pointerdown","focusin"])h.addEventListener(W,q,{signal:p.signal,passive:!0})}}else if(n==="/immersion/read")await(await m).openImmersionSource(e);else if(c)await(await m).openRetainedPassage(e,c);else if(n.startsWith("/backpack"))try{if(t.session.user){const{backpack:r}=await l.backpack();e===t.generation&&await r()}else{const{backpackGuest:r}=await l.guest();e===t.generation&&r(t.main,t.session.providers)}}catch(r){e===t.generation&&t.main.replaceChildren(R("h1","Backpack unavailable"),R("p",r.message),N("Try again",te(U)))}else{const{reader:r}=await m;e===t.generation&&await r()}}const ue=e=>document.body.classList.toggle("library-visitor",e);async function de(e){t.session&&!t.session.waiting&&ue(!t.session.user);const n=document.body.classList.contains("library-visitor")?null:t.session?.user??k();if(t.session={user:null,access:null,providers:{},waiting:!0},C.bind(null,!0),t.sourceRevision++,t.main=oe(n,ae)??document.querySelector("#main"),!t.main)return;t.main.dataset.account="",pt(t.main),v("");const a=t.main,{enhanceLibrary:o}=await l.library();if(e!==t.generation)return;t.readingView=await o({main:t.main,getSession:()=>t.session,refreshSession:y,saveLookup:it,newInspection:()=>{t.intent=null},theme:C,openSettings:P,active:()=>t.main===a&&a.isConnected&&t.generation===e});try{const i=sessionStorage.getItem("mtw-kept-word");sessionStorage.removeItem("mtw-kept-word");const c=i?.startsWith("{")?JSON.parse(i):i&&{text:i};c?.text&&e===t.generation&&setTimeout(v(`Kept ${c.text}. It\u2019s in your Backpack.`,c.review?{label:"Review it now",run:()=>{ce("first_save_review"),location.assign("/review")}}:null),8e3)}catch{}x();const s=(async()=>{for(let i=0;i<3;i++){const c=await y();if(c||t.generation!==e)return c}return null})().catch(async i=>{const c=i?.status?null:await re("metadata").catch(()=>null);if(!c?.access||c.blocked||t.main!==a||t.generation!==e)throw i;return t.session={user:{id:c.access.account},access:c.access,providers:{}}});t.sessionChecked=s.catch(()=>null),s.then(i=>{!i||t.main!==a||t.generation!==e||(a.dataset.account=i.user?.id??"",ue(!i.user),t.readingView?.bind?.(i.access),i.user&&(import("./app-chunk-expression-save-Oinz-fqU.mjs").catch(()=>{}),G()),t.readingView?.refreshProgress?.().catch(()=>{}),I(i.user))}).catch(()=>{})}const D=e=>ee(e)&&e!=="/"&&!/^\/(auth|offline)(\/|$)/.test(e);let T=0;function ut(){const e=location.pathname,n=(e.startsWith("/library/read/")?document.querySelector(".library-reading h1"):e==="/immersion/read"?document.querySelector(".reader-head h1"):null)?.textContent.trim();return n?{reviewFrom:{title:[...n].slice(0,80).join(""),href:e+location.search}}:null}let b=null,S=null,me=location.pathname,he=!1,pe=!1;const O=e=>Z(e)||e==="/"||e==="/review"||e==="/offline/read"||e==="/immersion/share"||e.startsWith("/library/read/")||/^\/auth(\/|$)/.test(e);let A=!0;for(const e of["pointerdown","keydown","wheel","touchstart"])addEventListener(e,()=>{A=!1},{capture:!0,once:!0,passive:!0});setTimeout(()=>{A=!1},15e3);const dt=()=>!!(S&&!S.loaded&&!O(new URL(S.url).pathname)),fe=()=>(document.visibilityState==="hidden"||A||dt()||!O(me)&&!O(location.pathname)&&!t.readingView?.settings)&&!t.privateSource&&!t.intent&&!document.querySelector("dialog[open]")&&!document.activeElement?.matches('input,textarea,[contenteditable="true"]');function Y(){b&&(b.close(),b=null,document.body.inert=pe);const e=S;S=null,e?.own===T&&!e.loaded&&j(e.url,{push:e.push,state:e.state,applyUpdate:!1})}navigator.serviceWorker?.addEventListener("message",e=>{if(e.data?.type!=="prepare-update"||!e.ports[0])return;const n=e.ports[0],a=!b&&e.source?.state==="installed"&&fe();a&&(b=n,pe=document.body.inert,document.body.inert=!0,n.onmessage=({data:o})=>{o?.cancel&&b===n&&Y()}),n.postMessage({safe:a}),a||n.close()}),navigator.serviceWorker?.addEventListener("controllerchange",()=>{if(!b||he)return;he=!0;const e=S;e?.own===T&&e.push&&history.pushState(e.state,"",e.url),location.reload()});let ge=performance.now();function we(){!navigator.serviceWorker?.controller||!navigator.onLine||performance.now()-ge<3e5||(ge=performance.now(),navigator.serviceWorker.getRegistration().then(e=>e?.update()).catch(()=>{}))}async function ye(e,n,a,o,s=!1){if(!navigator.serviceWorker?.controller||!s&&O(new URL(n).pathname)||s&&!A)return!1;let i;try{i=(await navigator.serviceWorker.getRegistration())?.waiting}catch{return!1}if(!i||e!==T)return!1;const c=S={own:e,url:n,push:a,state:o,loaded:s};if(!fe())return S=null,!1;const u=new MessageChannel,m=g=>{clearTimeout(d),u.port1.close(),!g&&!b&&S===c&&Y()},d=setTimeout(()=>{u.port1.close(),!b&&S===c&&Y()},2e3);u.port1.onmessage=({data:g})=>m(g?.activated===!0);try{i.postMessage({type:"activate-update"},[u.port2])}catch{m(!1)}return!0}function ve(e){!e||document.querySelector("body > .library-site-header")||(document.querySelector("#app")?.before(document.importNode(e,!0)),document.querySelector('link[href="/landing.css"]')||document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:"/landing.css",media:"(min-width: 900px)"})))}function mt(e){const n=e?.querySelector("#main.library-page"),a=document.querySelector("#main");return!n||!a?!1:(document.title=e.title,a.replaceWith(document.importNode(n,!0)),ve(e.querySelector(".library-site-header")),!0)}const L=new Map,H=(e,n="auto")=>fetch(e,{headers:{Accept:"text/html"},priority:n}).then(async a=>a.ok&&new URL(a.url).pathname.startsWith("/library")?ie(await a.text()):null),be=(e,n)=>performance.now()-n.at<(new URL(e).pathname.startsWith("/library/read/")?3e5:1e4);function B(e,n,a="auto"){if(!navigator.onLine||navigator.connection?.saveData)return;let o=L.get(e);(!o||!be(e,o))&&(L.delete(e),L.size>=6&&L.delete(L.keys().next().value),o={at:performance.now(),page:H(e,a)},o.page.catch(()=>L.get(e)===o&&L.delete(e)),L.set(e,o)),n&&!o.answers&&(o.answers=o.page.then(s=>{const i=s?.head.querySelector('link[rel="preload"][as="fetch"][href^="/language/library/"]')?.getAttribute("href"),c=s&&JSON.parse(s.querySelector("#main .library-source-data")?.textContent??"null")?.readingFont?.path;c&&fetch(c,{priority:a}).then(d=>d.arrayBuffer()).catch(()=>{});const u=s?.querySelector("#main img.library-reading-cover")?.parentElement;if(u?.matches("picture")&&(o.cover=document.importNode(u,!0)),!i||typeof DecompressionStream!="function")return null;const m=fetch(i,{priority:a}).then(d=>{if(!d.ok)throw Error("No built answers.");return new Response(d.body.pipeThrough(new DecompressionStream("gzip"))).text()});return m.catch(()=>{}),{path:i,text:m}}).catch(()=>null))}function ht(e){const n=L.get(e);return L.delete(e),n&&be(e,n)?n:null}function Se(e){if(typeof e?.href!="string"||e.target&&e.target!=="_self"||e.hasAttribute("download")||!D(location.pathname))return null;const n=new URL(e.href);return n.origin===location.origin&&D(n.pathname)&&!(n.pathname===location.pathname&&n.search===location.search)?n:null}const F=e=>{const n=Se(e?.closest?.("a[href]"));return n?.pathname.startsWith("/library")?n.href:null},K=typeof IntersectionObserver=="function"?new IntersectionObserver(e=>{for(const n of e)if(n.isIntersecting){K.unobserve(n.target);const a=F(n.target);a&&B(a,!0,"low")}},{rootMargin:"0px 0px 100% 0px"}):null,pt=e=>{K?.disconnect();for(const n of e.querySelectorAll("a.library-next"))K?.observe(n)};let ke=null,Le=0;document.addEventListener("pointerover",e=>{const n=e.pointerType==="mouse"?F(e.target):null;n!==ke&&(ke=n,clearTimeout(Le),n&&(Le=setTimeout(()=>B(n,!0),80)))},{passive:!0}),document.addEventListener("focusin",e=>{const n=e.target;if(n.matches?.(":focus-visible"))for(let a=n.parentElement;a&&a!==document.body;a=a.parentElement){const o=getComputedStyle(a);if(a.scrollWidth<=a.clientWidth||!/auto|scroll/.test(o.overflowX))continue;const s=a.getBoundingClientRect(),i=n.getBoundingClientRect();if(i.left>=s.left&&i.right<=s.right)return;const c=/x|both/.test(o.scrollSnapType);(c?[...a.children].find(u=>u.contains(n))??n:n).scrollIntoView({block:"nearest",inline:c?"start":"nearest"});return}}),document.addEventListener("pointerdown",e=>{const n=e.button===0?F(e.target):null;n&&B(n,e.pointerType==="mouse")},{passive:!0});async function j(e,{push:n,state:a=null,applyUpdate:o=!0}){const s=new URL(e).pathname,i=++T;if(we(),b){S={own:i,url:e,push:n,state:a};return}if(o&&await ye(i,e,n,a)||i!==T)return;let c=null,u=null,m=X(s),d=[],g=null;if(s.startsWith("/library")){try{const r=ht(e),h=await(r?r.page.catch(()=>H(e)):H(e));g=await r?.answers,c=h?.querySelector("#main.library-page"),u=h?.querySelector(".library-site-header"),m=h?.title,d=[...h?.head.querySelectorAll("[data-seo]")??[]]}catch{}if(i!==T)return;if(!c||!document.querySelector("#main")){location.assign(e);return}}if(n&&history.state?.mtwSettings&&history.replaceState({...history.state,mtwSettings:!1},"",location.href),n&&history.pushState(a,"",e),w({navigation:!0}),t.intent=null,document.title=m,document.head.querySelectorAll("[data-seo]").forEach(r=>r.remove()),d.length)for(const r of d)document.head.append(document.importNode(r,!0));else{const r=document.createElement("meta");r.name="robots",r.content="noindex,follow",r.dataset.seo="",document.head.append(r)}g&&(globalThis.mtwEarlyAnswers=g),c?document.querySelector("#main").replaceWith(document.importNode(c,!0)):t.main?.matches(".library-page")&&(t.main=null),ve(u),n&&scrollTo(0,0),f()}document.addEventListener("click",e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const n=e.target.closest?.("a[href]");if(n?.closest(".global-nav")&&n.href===location.href.split("#")[0]&&scrollY>0){e.preventDefault(),scrollTo({top:0,behavior:matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"});return}const a=Se(n);!a||!qe(a)||(e.preventDefault(),Ee(a,n))});const qe=e=>navigator.onLine||!!navigator.serviceWorker?.controller&&!e.pathname.startsWith("/library"),Ee=(e,n)=>{j(e.href,{push:!0,state:e.pathname==="/review"&&!e.search&&!n?.closest(".library-end")?ut():null})};Ge(e=>{const n=new URL(e,location.href);qe(n)&&n.origin===location.origin&&D(location.pathname)&&D(n.pathname)?Ee(n):location.assign(n.href)});const We=async()=>{const e=await re("metadata").catch(()=>null);return e?.access&&!e.blocked?{id:e.access.account}:null},Re=()=>import("./app-chunk-email-change-token-DRXPGcrm.mjs").then(function(e){return e.g}).then(({prepareReviewOperations:e})=>e?.()).catch(()=>{});function ft(){if(!t.session?.access||document.querySelector("script[data-initial-session]")||navigator.onLine===!1)return null;const e=new URLSearchParams(location.search),n=e.has("item")||e.has("session");n?(l.review().catch(()=>{}),Re()):(l.reviewEntry().catch(()=>{}),Qe("read").then(({record:o})=>{if(o&&(o.phase!=="complete"||o.pending?.length))return Re(),l.review()}).catch(()=>{})),Xe(n?["/api/review/tracks"]:["/api/review/handoff?","/api/home?part=today","/api/home?part=review","/api/review/tracks"],t.session.access);const a=y();return a.catch(()=>{}),{session:a,headStart:location.search?null:ne()}}async function gt(e,n=null){const a=E(t.session?.user??k());t.main=a;let o=n?.session??null;const s=async()=>{const p=o?.then(W=>W??y())??y();o=null;const q=await p.catch(async W=>{if(!W?.status&&!t.session?.user){const z=await We();z&&t.main===a&&I(z)}throw W});if(!q)throw Error("Your account changed. Reopen Review.");return q.user&&G(),t.main===a&&(a.dataset.account=q.access?.account??"",I(q.user),t.reviewLoading=!1,x()),q};let i=null;const c=()=>(i&&performance.now()-i.at<2e3||(i={at:performance.now(),check:s()},i.check.catch(()=>{i=null})),i.check),u=()=>t.main===a&&t.generation===e,m=!!(location.search||t.session?.user||k()||M()),d=m?null:l.guest();d?.catch(()=>{});const g=n?n.headStart:location.search?null:ne();if(c().catch(()=>{}),!m){const p=await c().catch(()=>null);if(!u())return;if(p&&!p.access){const{reviewGuest:q}=await(d??l.guest());if(!u())return;a.querySelector(":scope > .guest")||a.replaceChildren(),q(a,p.providers??t.session.providers);return}}let r;const h=async()=>(await(r??=l.review())).reviewPage({main:a,refresh:c,bindPreparedTheme:p=>C.bind(p),openSettings:P,exposeSettings:p=>{t.main===a&&(t.reviewSettings=p)},active:u});try{const p=new URLSearchParams(location.search);p.has("item")||p.has("session")?await h():await(await l.reviewEntry()).reviewEntry({main:a,refresh:c,active:u,openPrepared:h,beforeRoute:Ze,headStart:g})}finally{t.main===a&&(t.reviewLoading=!1,x())}}async function wt(){t.session={user:null,providers:{}},C.bind(null,!0),t.main=E(null),t.main.dataset.account="",v("");const e=t.main;await(await l.reader()).reader(),y().then(n=>{if(!(!n||t.main!==e)){if(n.user&&!t.intent&&!t.readerDraft?.account){location.replace("/home");return}n.localSignedOut&&!document.querySelector("#status")?.textContent&&v("Signed out locally. Reconnect and finish sign-out to end the server session."),t.main.dataset.account=n.user?.id??"",I(n.user)}}).catch(n=>{n?.status||t.main!==e||!k()||e.querySelector("textarea")?.value||(history.replaceState(history.state,"","/home"),f())})}function yt(e){const n=E(t.session?.user??k());t.main=n,v("");const a=navigator.onLine!==!1;n.append(R("h1",a?"Can\u2019t reach Mandarin The Wild":"You\u2019re offline"),le(a?"Check your connection and try again.":"This page opens when you\u2019re back online."),...a?[N("Try again",()=>location.reload())]:[],se("Open Home","/home")),addEventListener("online",()=>{e===t.generation&&location.reload()},{once:!0})}async function vt(e){const n=t.session?.user??k(),a=document.querySelector('#main[data-guest-first-page="not-found"]'),o=a?oe(n,ae):E(n);t.main=o,a&&document.querySelector("#app").classList.remove("boot-shell","boot-auth"),v("");const{notFoundGuest:s}=await import("./app-chunk-guest-BKY-sUoG.mjs");e!==t.generation||t.main!==o||(s(o),y().then(i=>{i&&t.main===o&&e===t.generation&&(o.dataset.account=i.user?.id??"",I(i.user))}).catch(()=>{}))}async function Te(e,n,a){if(e==="/immersion/share"){const{refuseOfflineShare:s}=await l.share();a===t.generation&&(t.main=E(null),n.status?t.main.append(R("h1","Immersion"),R("p",n.message),N("Try again",te(U))):(s(t.main),await(await l.offline()).offlinePage(a,"/immersion"),a===t.generation&&v("You\u2019re offline. Share it again when you\u2019re back online.")));return}if(e.startsWith("/auth")){if(a===t.generation){t.main=E(null),t.main.querySelector(":scope > [data-auth-first]")?.remove();const s=R("section","","card auth-card");s.append(R("h1","Sign in"),le("You\u2019re offline. Sign-in opens here again when you\u2019re back online."),se("Open Home","/home")),t.main.append(s)}return}const o=k()??await We();if(e==="/keys"){const{keysPage:s}=await l.keys();a===t.generation&&(t.main=E(o),t.keysView=s(t.main,{theme:C,openSettings:P}),x());return}if(e==="/help"){const{helpPage:s}=await l.help();a===t.generation&&(t.main=E(o),t.helpView=s(t.main,{session:null,offline:!!o,active:()=>a===t.generation&&t.main?.isConnected}));return}if(!e.startsWith("/backpack")&&!["/read","/home","/account","/immersion","/immersion/read"].includes(e))throw n;await(await l.offline()).offlinePage(a,e)}let Ce=0;const Pe=()=>{clearTimeout(Ce),Ce=setTimeout(()=>{const e=document.querySelector(".delete-dialog[open]"),n=t.generation;if(e){e.addEventListener("close",()=>{t.generation===n&&Pe()},{once:!0});return}w(),f()},250)};De.onmessage=async e=>{if(e.data.type==="immersion-updated"&&e.data.account===t.session?.user?.id){if(document.querySelector(".immersion-dialog[open]"))return;(t.immersionCurrentId===e.data.id||location.pathname==="/immersion")&&(w(),await f());return}if(e.data.type==="immersion-deleted"&&e.data.account===t.session?.user?.id){t.homeView?.sourceDeleted(e.data.id),(e.data.id===t.immersionCurrentId||location.pathname==="/immersion"&&!document.querySelector(".immersion-dialog[open]"))&&(w(),await f());return}if(e.data.type==="deleted"&&e.data.account===t.session?.user?.id){Pe();return}if(e.data.type==="offline-copy"){t.privateSource&&(!e.data.id||e.data.id===t.privateSource.record.source.id)?(w(),await f()):!navigator.onLine&&["/immersion","/home"].includes(location.pathname)&&(w(),await f());return}e.data.type==="account"&&(w(),t.session=null,C.bind(null,!0),location.pathname.startsWith("/library")||t.main?.replaceChildren(R("p","Your account changed. Reopening this view\u2026")),await f()),e.data.type==="canceled"&&e.data.operation===t.intent&&(t.intent=null,J(e.data.operation,{state:"dismissed"})),e.data.type==="saved"&&e.data.operation===t.intent&&(location.pathname==="/"||location.pathname==="/read"||location.pathname.startsWith("/library/read/"))&&J(e.data.operation,{state:"saved",id:e.data.id,known:e.data.known})};const xe=".collection-dialog[open],.delete-dialog[open],.download-dialog[open],.email-change-dialog[open],.passkey-dialog[open],.account-provider-dialog[open],.feedback-dialog[open],.import-dialog[open],.settings-dialog[open],.sessions-dialog[open]";let $=null;const Ie=()=>{const e=document.querySelector("dialog[open]");if(e&&!e.matches(xe)&&!(location.pathname==="/immersion"&&e.matches(".immersion-dialog"))){$!==e&&e.addEventListener("close",()=>{$=null,navigator.onLine!==!1&&Ie()},{once:!0}),$=e;return}if(location.pathname.startsWith("/library")&&!document.querySelector(".library-page")){location.reload();return}if(t.readingView){l.offline().then(n=>n.recheckOpenReader()).catch(n=>v(n.message));return}if(document.querySelector(xe)||t.main?.querySelector(".memory-aid textarea")||location.pathname==="/immersion"&&document.querySelector(".immersion-dialog[open]")){const n=t.generation;y().then(a=>{a&&(!a.access||n!==t.generation)&&(w(),f())}).catch(a=>v(a.message));return}w(),f()};window.addEventListener("online",Ie);const Ve=()=>{l.offline().catch(()=>{})};globalThis.requestIdleCallback?requestIdleCallback(Ve,{timeout:1500}):setTimeout(Ve,500),window.addEventListener("offline",()=>{Q(),!document.querySelector("dialog[open]")&&["/home","/immersion","/backpack","/account","/library"].includes(location.pathname)&&(w(),f())}),window.addEventListener("hashchange",()=>{Oe()&&f()}),window.addEventListener("popstate",e=>{T++,!Ue(e)&&(t.immersionView?.follow()||j(location.href,{push:!1}))}),window.addEventListener("pageshow",e=>{e.persisted&&f()}),document.addEventListener("visibilitychange",()=>{if(document.visibilityState!=="visible"){Q();return}if(we(),t.privateSource||location.pathname.startsWith("/offline")){w(),f();return}if(!document.querySelector("[data-account]")){f();return}if(t.learningView){t.learningView.refresh();return}y().then(e=>{e&&document.querySelector("[data-account]")?.dataset.account!==void 0&&document.querySelector("[data-account]").dataset.account!==(e.user?.id??"")&&f()}).catch(()=>{})}),window.addEventListener("focus",()=>{t.learningView?.refresh()}),Me(),Ne(),Ye(lt),f();const Ae=()=>setTimeout(async()=>{const e=()=>{ye(T,location.href,!1,history.state,!0)};e();const n=(await navigator.serviceWorker?.getRegistration().catch(()=>null))?.installing;n?.addEventListener("statechange",()=>{n.state==="installed"&&A&&e()})},3e3);document.readyState==="complete"?Ae():addEventListener("load",Ae,{once:!0});const _=()=>{import("./app-chunk-save-outbox-store-CkhoP4mW.mjs").then(e=>e.resumeQueuedSaves()).catch(()=>{})};window.addEventListener("online",_),window.addEventListener("pageshow",_),_();
