<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
    <title>Script.Movie - Professional Screenplay Writing Platform</title>
    <meta name="description" content="Create professional screenplays and stories with our advanced writing platform. Collaborate, organize, and bring your creative vision to life." />
    <meta name="keywords" content="screenplay, screenwriting, story writing, creative writing, script writing, movie script, film writing" />
    <meta name="author" content="Script.Movie" />
    <meta name="robots" content="index, follow" />
    <link rel="canonical" href="https://script.movie" />
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website" />
    <meta property="og:url" content="https://script.movie" />
    <meta property="og:title" content="Script.Movie - Professional Screenplay Writing Platform" />
    <meta property="og:description" content="Create professional screenplays and stories with our advanced writing platform. Collaborate, organize, and bring your creative vision to life." />
    <meta property="og:site_name" content="Script.Movie" />
    
    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image" />
    <meta property="twitter:url" content="https://script.movie" />
    <meta property="twitter:title" content="Script.Movie - Professional Screenplay Writing Platform" />
    <meta property="twitter:description" content="Create professional screenplays and stories with our advanced writing platform. Collaborate, organize, and bring your creative vision to life." />
    
    <!-- Favicon -->
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <link rel="alternate icon" href="/favicon.ico" />
    
    <!-- Theme -->
    <meta name="theme-color" content="#000000" />
    <meta name="color-scheme" content="dark light" />
    

    <!-- Using system fonts for instant loading -->
    

    <!-- Critical CSS with reduced specificity for faster parsing -->
    <style>
      /* Font face definitions with swap */
      @font-face {
        font-family: 'Denton Test';
        font-display: swap;
        src: local('Georgia'), local('Times New Roman');
      }
      
      /* Optimized hero styles for immediate LCP */
      .hero-title {
        font-family: 'Playfair Display', serif;
        font-size: clamp(2rem, 5vw, 4rem);
        font-weight: 700;
        margin-bottom: 1.5rem;
        line-height: 1.1;
        color: #fff;
        font-display: swap;
      }
      .hero-text {
        font-size: clamp(1rem, 2vw, 1.25rem);
        margin-bottom: 2rem;
        color: rgba(255, 255, 255, 0.9);
        max-width: 36rem;
        margin-left: auto;
        margin-right: auto;
        line-height: 1.6;
      }
      .hero-button {
        display: inline-flex;
        align-items: center;
        gap: 0.75rem;
        padding: 1.25rem 2rem;
        background: #bfefff;
        color: #000;
        border-radius: 0.375rem;
        font-weight: 600;
        font-size: 1.125rem;
        text-decoration: none;
        transition: background-color 0.2s ease;
        border: none;
        cursor: pointer;
      }
      .hero-button:hover {
        background: rgba(191, 239, 255, 0.9);
      }
      .hero-section {
        min-height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        padding: 2.5rem 1rem;
        position: relative;
      }
      
      /* Loading states */
      .loading-placeholder {
        background: #111;
        animation: pulse 2s infinite;
      }
      @keyframes pulse {
        0%, 100% { opacity: 0.4; }
        50% { opacity: 0.6; }
      }
      
      /* Adventure page critical styles - light theme only */
      .adventure-page {
        min-height: 100vh;
        background: linear-gradient(135deg, #f8fafc 0%, #ffffff 50%, #f1f5f9 100%);
        color: #1e293b;
        font-family: 'Inter', system-ui, sans-serif;
        transition: none;
      }
      
      /* Critical Adventure page utilities */
      .adventure-hero-title {
        font-family: 'Denton Test', 'Georgia', serif;
        font-size: clamp(1.875rem, 4vw, 3rem);
        font-weight: 700;
        line-height: 1.1;
        letter-spacing: -0.02em;
        text-align: center;
        margin-bottom: 1.5rem;
        color: #1e293b;
      }
      
      .adventure-cta-btn {
        display: inline-flex;
        align-items: center;
        gap: 0.75rem;
        padding: 1rem 2rem;
        background: #7c3aed;
        color: white;
        border-radius: 0.5rem;
        font-weight: 600;
        font-size: 1.125rem;
        text-decoration: none;
        transition: background-color 0.3s ease, transform 0.2s ease;
        border: none;
        cursor: pointer;
        min-height: 3rem;
      }
      
      .adventure-video-container {
        aspect-ratio: 16/9;
        width: 100%;
        min-height: 300px;
        background: #000;
        border-radius: 12px;
        overflow: hidden;
        position: relative;
      }
    </style>
    <script type="module" crossorigin src="/assets/index-CcQAS2Nv.js"></script>
    <link rel="stylesheet" crossorigin href="/assets/index-DTt4xWjS.css">
    <script type="module">"use strict";(()=>{var P="0.2.7";var T={HIGHLIGHT_COLOR:"#0079F2",HIGHLIGHT_BG:"#0079F210",ALLOWED_DOMAIN:".replit.dev"},Q=`
  [contenteditable] {
    outline: none !important;
  }

  [contenteditable]:focus {
    outline: none !important;
  }
`,Z=`
  .beacon-highlighter {
    content: '';
    position: absolute;
    z-index: ${Number.MAX_SAFE_INTEGER-3};
    box-sizing: border-box;
    pointer-events: none;
    outline: 2px dashed ${T.HIGHLIGHT_COLOR} !important;
    outline-offset: 0 !important;
    margin: 0 !important;
    padding: 0 !important;
    transform: none !important;
    background: ${T.HIGHLIGHT_BG} !important;
    opacity: 0;
  }
  
  .beacon-hover-highlighter {
    position: fixed;
    z-index: ${Number.MAX_SAFE_INTEGER};
  }
  
  .beacon-selected-highlighter {
    position: fixed;
    pointer-events: none;
    outline: 2px solid ${T.HIGHLIGHT_COLOR} !important;
    outline-offset: 3px !important;
    background: none !important;
  }
  
  .beacon-label {
    position: absolute;
    background-color: ${T.HIGHLIGHT_COLOR};
    color: #FFFFFF;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 14px;
    font-family: monospace;
    line-height: 1;
    white-space: nowrap;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    transform: translateY(-100%);
    margin-top: -4px;
    left: 0;
    z-index: ${Number.MAX_SAFE_INTEGER-2};
    pointer-events: none;
    opacity: 0;
  }
  
  .beacon-hover-label {
    position: fixed;
    z-index: ${Number.MAX_SAFE_INTEGER};
  }
  
  .beacon-selected-label {
    position: fixed;
    pointer-events: none;
  }
  
  .beacon-sibling-highlighter {
    position: fixed;
    pointer-events: none;
    outline: 2px dashed ${T.HIGHLIGHT_COLOR} !important;
    outline-offset: 0 !important;
    margin: 0 !important;
    padding: 0 !important;
    transform: none !important;
    background: ${T.HIGHLIGHT_BG} !important;
  }
`;function Ne(e,i){return e[13]=1,e[14]=i>>8,e[15]=i&255,e[16]=i>>8,e[17]=i&255,e}var oe=112,le=72,ae=89,ce=115,W;function Ie(){let e=new Int32Array(256);for(let i=0;i<256;i++){let t=i;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[i]=t}return e}function De(e){let i=-1;W||(W=Ie());for(let t=0;t<e.length;t++)i=W[(i^e[t])&255]^i>>>8;return i^-1}function Me(e){let i=e.length-1;for(let t=i;t>=4;t--)if(e[t-4]===9&&e[t-3]===oe&&e[t-2]===le&&e[t-1]===ae&&e[t]===ce)return t-3;return 0}function Re(e,i,t=!1){let n=new Uint8Array(13);i*=39.3701,n[0]=oe,n[1]=le,n[2]=ae,n[3]=ce,n[4]=i>>>24,n[5]=i>>>16,n[6]=i>>>8,n[7]=i&255,n[8]=n[4],n[9]=n[5],n[10]=n[6],n[11]=n[7],n[12]=1;let o=De(n),r=new Uint8Array(4);if(r[0]=o>>>24,r[1]=o>>>16,r[2]=o>>>8,r[3]=o&255,t){let l=Me(e);return e.set(n,l),e.set(r,l+13),e}else{let l=new Uint8Array(4);l[0]=0,l[1]=0,l[2]=0,l[3]=9;let s=new Uint8Array(54);return s.set(e,0),s.set(l,33),s.set(n,37),s.set(r,50),s}}var he="[modern-screenshot]",C=typeof window<"u",_e=C&&"Worker"in window,Oe=C&&"atob"in window,jt=C&&"btoa"in window,V=C?window.navigator?.userAgent:"",de=V.includes("Chrome"),k=V.includes("AppleWebKit")&&!de,j=V.includes("Firefox"),Pe=e=>e&&"__CONTEXT__"in e,ke=e=>e.constructor.name==="CSSFontFaceRule",Fe=e=>e.constructor.name==="CSSImportRule",v=e=>e.nodeType===1,D=e=>typeof e.className=="object",ge=e=>e.tagName==="image",Ue=e=>e.tagName==="use",x=e=>v(e)&&typeof e.style<"u"&&!D(e),$e=e=>e.nodeType===8,Be=e=>e.nodeType===3,L=e=>e.tagName==="IMG",F=e=>e.tagName==="VIDEO",We=e=>e.tagName==="CANVAS",Ge=e=>e.tagName==="TEXTAREA",Ve=e=>e.tagName==="INPUT",je=e=>e.tagName==="STYLE",ze=e=>e.tagName==="SCRIPT",qe=e=>e.tagName==="SELECT",Xe=e=>e.tagName==="SLOT",Ye=e=>e.tagName==="IFRAME",Ke=(...e)=>console.warn(he,...e);function Je(e){let i=e?.createElement?.("canvas");return i&&(i.height=i.width=1),!!i&&"toDataURL"in i&&!!i.toDataURL("image/webp").includes("image/webp")}var G=e=>e.startsWith("data:");function ue(e,i){if(e.match(/^[a-z]+:\/\//i))return e;if(C&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!C)return e;let t=U().implementation.createHTMLDocument(),n=t.createElement("base"),o=t.createElement("a");return t.head.appendChild(n),t.body.appendChild(o),i&&(n.href=i),o.href=e,o.href}function U(e){return(e&&v(e)?e?.ownerDocument:e)??window.document}var $="http://www.w3.org/2000/svg";function Qe(e,i,t){let n=U(t).createElementNS($,"svg");return n.setAttributeNS(null,"width",e.toString()),n.setAttributeNS(null,"height",i.toString()),n.setAttributeNS(null,"viewBox",`0 0 ${e} ${i}`),n}function Ze(e,i){let t=new XMLSerializer().serializeToString(e);return i&&(t=t.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"")),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`}async function et(e,i="image/png",t=1){try{return await new Promise((n,o)=>{e.toBlob(r=>{r?n(r):o(new Error("Blob is null"))},i,t)})}catch(n){if(Oe)return tt(e.toDataURL(i,t));throw n}}function tt(e){let[i,t]=e.split(","),n=i.match(/data:(.+);/)?.[1]??void 0,o=window.atob(t),r=o.length,l=new Uint8Array(r);for(let s=0;s<r;s+=1)l[s]=o.charCodeAt(s);return new Blob([l],{type:n})}function me(e,i){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>t(o.result),o.onerror=()=>n(o.error),o.onabort=()=>n(new Error(`Failed read blob to ${i}`)),i==="dataUrl"?o.readAsDataURL(e):i==="arrayBuffer"&&o.readAsArrayBuffer(e)})}var it=e=>me(e,"dataUrl"),nt=e=>me(e,"arrayBuffer");function H(e,i){let t=U(i).createElement("img");return t.decoding="sync",t.loading="eager",t.src=e,t}function N(e,i){return new Promise(t=>{let{timeout:n,ownerDocument:o,onError:r,onWarn:l}=i??{},s=typeof e=="string"?H(e,U(o)):e,c=null,h=null;function a(){t(s),c&&clearTimeout(c),h?.()}if(n&&(c=setTimeout(a,n)),F(s)){let d=s.currentSrc||s.src;if(!d)return s.poster?N(s.poster,i).then(t):a();if(s.readyState>=2)return a();let g=a,m=u=>{l?.("Failed video load",d,u),r?.(u),a()};h=()=>{s.removeEventListener("loadeddata",g),s.removeEventListener("error",m)},s.addEventListener("loadeddata",g,{once:!0}),s.addEventListener("error",m,{once:!0})}else{let d=ge(s)?s.href.baseVal:s.currentSrc||s.src;if(!d)return a();let g=async()=>{if(L(s)&&"decode"in s)try{await s.decode()}catch(u){l?.("Failed to decode image, trying to render anyway",s.dataset.originalSrc||d,u)}a()},m=u=>{l?.("Failed image load",s.dataset.originalSrc||d,u),a()};if(L(s)&&s.complete)return g();h=()=>{s.removeEventListener("load",g),s.removeEventListener("error",m)},s.addEventListener("load",g,{once:!0}),s.addEventListener("error",m,{once:!0})}})}async function rt(e,i){x(e)&&(L(e)||F(e)?await N(e,i):await Promise.all(["img","video"].flatMap(t=>Array.from(e.querySelectorAll(t)).map(n=>N(n,i)))))}var fe=function(){let i=0,t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)}();function pe(e){return e?.split(",").map(i=>i.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}var ee=0;function st(e){let i=`${he}[#${ee}]`;return ee++,{time:t=>e&&console.time(`${i} ${t}`),timeEnd:t=>e&&console.timeEnd(`${i} ${t}`),warn:(...t)=>e&&Ke(...t)}}function ot(e){return{cache:e?"no-cache":"force-cache"}}async function z(e,i){return Pe(e)?e:lt(e,{...i,autoDestruct:!0})}async function lt(e,i){let{scale:t=1,workerUrl:n,workerNumber:o=1}=i||{},r=!!i?.debug,l=i?.features??!0,s=e.ownerDocument??(C?window.document:void 0),c=e.ownerDocument?.defaultView??(C?window:void 0),h=new Map,a={width:0,height:0,quality:1,type:"image/png",scale:t,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:3e4,progress:null,debug:r,fetch:{requestInit:ot(i?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...i?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber:o,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...i,__CONTEXT__:!0,log:st(r),node:e,ownerDocument:s,ownerWindow:c,dpi:t===1?null:96*t,svgStyleElement:be(s),svgDefsElement:s?.createElementNS($,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:_e&&n&&o?o:0})].map(()=>{try{let m=new Worker(n);return m.onmessage=async u=>{let{url:f,result:p}=u.data;p?h.get(f)?.resolve?.(p):h.get(f)?.reject?.(new Error(`Error receiving message from worker: ${f}`))},m.onmessageerror=u=>{let{url:f}=u.data;h.get(f)?.reject?.(new Error(`Error receiving message from worker: ${f}`))},m}catch(m){return a.log.warn("Failed to new Worker",m),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[Je(s)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests:h,drawImageCount:0,tasks:[],features:l,isEnable:m=>m==="restoreScrollPosition"?typeof l=="boolean"?!1:l[m]??!1:typeof l=="boolean"?l:l[m]??!0};a.log.time("wait until load"),await rt(e,{timeout:a.timeout,onWarn:a.log.warn}),a.log.timeEnd("wait until load");let{width:d,height:g}=at(e,a);return a.width=d,a.height=g,a}function be(e){if(!e)return;let i=e.createElement("style"),t=i.ownerDocument.createTextNode(`
.______background-clip--text {
  background-clip: text;
  -webkit-background-clip: text;
}
`);return i.appendChild(t),i}function at(e,i){let{width:t,height:n}=i;if(v(e)&&(!t||!n)){let o=e.getBoundingClientRect();t=t||o.width||Number(e.getAttribute("width"))||0,n=n||o.height||Number(e.getAttribute("height"))||0}return{width:t,height:n}}async function ct(e,i){let{log:t,timeout:n,drawImageCount:o,drawImageInterval:r}=i;t.time("image to canvas");let l=await N(e,{timeout:n,onWarn:i.log.warn}),{canvas:s,context2d:c}=ht(e.ownerDocument,i),h=()=>{try{c?.drawImage(l,0,0,s.width,s.height)}catch(a){i.log.warn("Failed to drawImage",a)}};if(h(),i.isEnable("fixSvgXmlDecode"))for(let a=0;a<o;a++)await new Promise(d=>{setTimeout(()=>{h(),d()},a+r)});return i.drawImageCount=0,t.timeEnd("image to canvas"),s}function ht(e,i){let{width:t,height:n,scale:o,backgroundColor:r,maximumCanvasSize:l}=i,s=e.createElement("canvas");s.width=Math.floor(t*o),s.height=Math.floor(n*o),s.style.width=`${t}px`,s.style.height=`${n}px`,l&&(s.width>l||s.height>l)&&(s.width>l&&s.height>l?s.width>s.height?(s.height*=l/s.width,s.width=l):(s.width*=l/s.height,s.height=l):s.width>l?(s.height*=l/s.width,s.width=l):(s.width*=l/s.height,s.height=l));let c=s.getContext("2d");return c&&r&&(c.fillStyle=r,c.fillRect(0,0,s.width,s.height)),{canvas:s,context2d:c}}function Ee(e,i){if(e.ownerDocument)try{let r=e.toDataURL();if(r!=="data:,")return H(r,e.ownerDocument)}catch(r){i.log.warn("Failed to clone canvas",r)}let t=e.cloneNode(!1),n=e.getContext("2d"),o=t.getContext("2d");try{return n&&o&&o.putImageData(n.getImageData(0,0,e.width,e.height),0,0),t}catch(r){i.log.warn("Failed to clone canvas",r)}return t}function dt(e,i){try{if(e?.contentDocument?.body)return q(e.contentDocument.body,i)}catch(t){i.log.warn("Failed to clone iframe",t)}return e.cloneNode(!1)}function gt(e){let i=e.cloneNode(!1);return e.currentSrc&&e.currentSrc!==e.src&&(i.src=e.currentSrc,i.srcset=""),i.loading==="lazy"&&(i.loading="eager"),i}async function ut(e,i){if(e.ownerDocument&&!e.currentSrc&&e.poster)return H(e.poster,e.ownerDocument);let t=e.cloneNode(!1);t.crossOrigin="anonymous",e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc);let n=t.ownerDocument;if(n){let o=!0;if(await N(t,{onError:()=>o=!1,onWarn:i.log.warn}),!o)return e.poster?H(e.poster,e.ownerDocument):t;t.currentTime=e.currentTime,await new Promise(l=>{t.addEventListener("seeked",l,{once:!0})});let r=n.createElement("canvas");r.width=e.offsetWidth,r.height=e.offsetHeight;try{let l=r.getContext("2d");l&&l.drawImage(t,0,0,r.width,r.height)}catch(l){return i.log.warn("Failed to clone video",l),e.poster?H(e.poster,e.ownerDocument):t}return Ee(r,i)}return t}function mt(e,i){return We(e)?Ee(e,i):Ye(e)?dt(e,i):L(e)?gt(e):F(e)?ut(e,i):e.cloneNode(!1)}function ft(e){let i=e.sandbox;if(!i){let{ownerDocument:t}=e;try{t&&(i=t.createElement("iframe"),i.id=`__SANDBOX__-${fe()}`,i.width="0",i.height="0",i.style.visibility="hidden",i.style.position="fixed",t.body.appendChild(i),i.contentWindow?.document.write('<!DOCTYPE html><meta charset="UTF-8"><title></title><body>'),e.sandbox=i)}catch(n){e.log.warn("Failed to getSandBox",n)}}return i}var pt=["width","height","-webkit-text-fill-color"],bt=["stroke","fill"];function we(e,i,t){let{defaultComputedStyles:n}=t,o=e.nodeName.toLowerCase(),r=D(e)&&o!=="svg",l=r?bt.map(f=>[f,e.getAttribute(f)]).filter(([,f])=>f!==null):[],s=[r&&"svg",o,l.map((f,p)=>`${f}=${p}`).join(","),i].filter(Boolean).join(":");if(n.has(s))return n.get(s);let h=ft(t)?.contentWindow;if(!h)return new Map;let a=h?.document,d,g;r?(d=a.createElementNS($,"svg"),g=d.ownerDocument.createElementNS(d.namespaceURI,o),l.forEach(([f,p])=>{g.setAttributeNS(null,f,p)}),d.appendChild(g)):d=g=a.createElement(o),g.textContent=" ",a.body.appendChild(d);let m=h.getComputedStyle(g,i),u=new Map;for(let f=m.length,p=0;p<f;p++){let b=m.item(p);pt.includes(b)||u.set(b,m.getPropertyValue(b))}return a.body.removeChild(d),n.set(s,u),u}function ye(e,i,t){let n=new Map,o=[],r=new Map;if(t)for(let s of t)l(s);else for(let s=e.length,c=0;c<s;c++){let h=e.item(c);l(h)}for(let s=o.length,c=0;c<s;c++)r.get(o[c])?.forEach((h,a)=>n.set(a,h));function l(s){let c=e.getPropertyValue(s),h=e.getPropertyPriority(s),a=s.lastIndexOf("-"),d=a>-1?s.substring(0,a):void 0;if(d){let g=r.get(d);g||(g=new Map,r.set(d,g)),g.set(s,[c,h])}i.get(s)===c&&!h||(d?o.push(d):n.set(s,[c,h]))}return n}function Et(e,i,t,n){let{ownerWindow:o,includeStyleProperties:r,currentParentNodeStyle:l}=n,s=i.style,c=o.getComputedStyle(e),h=we(e,null,n);l?.forEach((d,g)=>{h.delete(g)});let a=ye(c,h,r);a.delete("transition-property"),a.delete("all"),a.delete("d"),a.delete("content"),t&&(a.delete("margin-top"),a.delete("margin-right"),a.delete("margin-bottom"),a.delete("margin-left"),a.delete("margin-block-start"),a.delete("margin-block-end"),a.delete("margin-inline-start"),a.delete("margin-inline-end"),a.set("box-sizing",["border-box",""])),a.get("background-clip")?.[0]==="text"&&i.classList.add("______background-clip--text"),de&&(a.has("font-kerning")||a.set("font-kerning",["normal",""]),(a.get("overflow-x")?.[0]==="hidden"||a.get("overflow-y")?.[0]==="hidden")&&a.get("text-overflow")?.[0]==="ellipsis"&&e.scrollWidth===e.clientWidth&&a.set("text-overflow",["clip",""]));for(let d=s.length,g=0;g<d;g++)s.removeProperty(s.item(g));return a.forEach(([d,g],m)=>{s.setProperty(m,d,g)}),a}function wt(e,i){(Ge(e)||Ve(e)||qe(e))&&i.setAttribute("value",e.value)}var yt=[":before",":after"],vt=[":-webkit-scrollbar",":-webkit-scrollbar-button",":-webkit-scrollbar-thumb",":-webkit-scrollbar-track",":-webkit-scrollbar-track-piece",":-webkit-scrollbar-corner",":-webkit-resizer"];function St(e,i,t,n,o){let{ownerWindow:r,svgStyleElement:l,svgStyles:s,currentNodeStyle:c}=n;if(!l||!r)return;function h(a){let d=r.getComputedStyle(e,a),g=d.getPropertyValue("content");if(!g||g==="none")return;o?.(g),g=g.replace(/(')|(")|(counter\(.+\))/g,"");let m=[fe()],u=we(e,a,n);c?.forEach((E,y)=>{u.delete(y)});let f=ye(d,u,n.includeStyleProperties);f.delete("content"),f.delete("-webkit-locale"),f.get("background-clip")?.[0]==="text"&&i.classList.add("______background-clip--text");let p=[`content: '${g}';`];if(f.forEach(([E,y],A)=>{p.push(`${A}: ${E}${y?" !important":""};`)}),p.length===1)return;try{i.className=[i.className,...m].join(" ")}catch(E){n.log.warn("Failed to copyPseudoClass",E);return}let b=p.join(`
  `),w=s.get(b);w||(w=[],s.set(b,w)),w.push(`.${m[0]}:${a}`)}yt.forEach(h),t&&vt.forEach(h)}var te=new Set(["symbol"]);async function ie(e,i,t,n,o){if(v(t)&&(je(t)||ze(t))||n.filter&&!n.filter(t))return;te.has(i.nodeName)||te.has(t.nodeName)?n.currentParentNodeStyle=void 0:n.currentParentNodeStyle=n.currentNodeStyle;let r=await q(t,n,!1,o);n.isEnable("restoreScrollPosition")&&At(e,r),i.appendChild(r)}async function ne(e,i,t,n){let o=(v(e)?e.shadowRoot?.firstChild:void 0)??e.firstChild;for(let r=o;r;r=r.nextSibling)if(!$e(r))if(v(r)&&Xe(r)&&typeof r.assignedNodes=="function"){let l=r.assignedNodes();for(let s=0;s<l.length;s++)await ie(e,i,l[s],t,n)}else await ie(e,i,r,t,n)}function At(e,i){if(!x(e)||!x(i))return;let{scrollTop:t,scrollLeft:n}=e;if(!t&&!n)return;let{transform:o}=i.style,r=new DOMMatrix(o),{a:l,b:s,c,d:h}=r;r.a=1,r.b=0,r.c=0,r.d=1,r.translateSelf(-n,-t),r.a=l,r.b=s,r.c=c,r.d=h,i.style.transform=r.toString()}function Tt(e,i){let{backgroundColor:t,width:n,height:o,style:r}=i,l=e.style;if(t&&l.setProperty("background-color",t,"important"),n&&l.setProperty("width",`${n}px`,"important"),o&&l.setProperty("height",`${o}px`,"important"),r)for(let s in r)l[s]=r[s]}var Ct=/^[\w-:]+$/;async function q(e,i,t=!1,n){let{ownerDocument:o,ownerWindow:r,fontFamilies:l}=i;if(o&&Be(e))return n&&/\S/.test(e.data)&&n(e.data),o.createTextNode(e.data);if(o&&r&&v(e)&&(x(e)||D(e))){let c=await mt(e,i);if(i.isEnable("removeAbnormalAttributes")){let u=c.getAttributeNames();for(let f=u.length,p=0;p<f;p++){let b=u[p];Ct.test(b)||c.removeAttribute(b)}}let h=i.currentNodeStyle=Et(e,c,t,i);t&&Tt(c,i);let a=!1;if(i.isEnable("copyScrollbar")){let u=[h.get("overflow-x")?.[0],h.get("overflow-y")?.[0]];a=u.includes("scroll")||(u.includes("auto")||u.includes("overlay"))&&(e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth)}let d=h.get("text-transform")?.[0],g=pe(h.get("font-family")?.[0]),m=g?u=>{d==="uppercase"?u=u.toUpperCase():d==="lowercase"?u=u.toLowerCase():d==="capitalize"&&(u=u[0].toUpperCase()+u.substring(1)),g.forEach(f=>{let p=l.get(f);p||l.set(f,p=new Set),u.split("").forEach(b=>p.add(b))})}:void 0;return St(e,c,a,i,m),wt(e,c),F(e)||await ne(e,c,i,m),c}let s=e.cloneNode(!1);return await ne(e,s,i),s}function Ht(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(i){e.log.warn("Failed to destroyContext",i)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[]}function Lt(e){let{url:i,timeout:t,responseType:n,...o}=e,r=new AbortController,l=t?setTimeout(()=>r.abort(),t):void 0;return fetch(i,{signal:r.signal,...o}).then(s=>{if(!s.ok)throw new Error("Failed fetch, not 2xx response",{cause:s});switch(n){case"arrayBuffer":return s.arrayBuffer();case"dataUrl":return s.blob().then(it);case"text":default:return s.text()}}).finally(()=>clearTimeout(l))}function I(e,i){let{url:t,requestType:n="text",responseType:o="text",imageDom:r}=i,l=t,{timeout:s,acceptOfImage:c,requests:h,fetchFn:a,fetch:{requestInit:d,bypassingCache:g,placeholderImage:m},font:u,workers:f,fontFamilies:p}=e;n==="image"&&(k||j)&&e.drawImageCount++;let b=h.get(t);if(!b){g&&g instanceof RegExp&&g.test(l)&&(l+=(/\?/.test(l)?"&":"?")+new Date().getTime());let w=n.startsWith("font")&&u&&u.minify,E=new Set;w&&n.split(";")[1].split(",").forEach(O=>{p.has(O)&&p.get(O).forEach(J=>E.add(J))});let y=w&&E.size,A={url:l,timeout:s,responseType:y?"arrayBuffer":o,headers:n==="image"?{accept:c}:void 0,...d};b={type:n,resolve:void 0,reject:void 0,response:null},b.response=(async()=>{if(a&&n==="image"){let S=await a(t);if(S)return S}return!k&&t.startsWith("http")&&f.length?new Promise((S,O)=>{f[h.size&f.length-1].postMessage({rawUrl:t,...A}),b.resolve=S,b.reject=O}):Lt(A)})().catch(S=>{if(h.delete(t),n==="image"&&m)return e.log.warn("Failed to fetch image base64, trying to use placeholder image",l),typeof m=="string"?m:m(r);throw S}),h.set(t,b)}return b.response}async function ve(e,i,t,n){if(!Se(e))return e;for(let[o,r]of xt(e,i))try{let l=await I(t,{url:r,requestType:n?"image":"text",responseType:"dataUrl"});e=e.replace(Nt(o),`$1${l}$3`)}catch(l){t.log.warn("Failed to fetch css data url",o,l)}return e}function Se(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}var Ae=/url\((['"]?)([^'"]+?)\1\)/g;function xt(e,i){let t=[];return e.replace(Ae,(n,o,r)=>(t.push([r,ue(r,i)]),n)),t.filter(([n])=>!G(n))}function Nt(e){let i=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${i})(['"]?\\))`,"g")}var It=["background-image","border-image-source","-webkit-border-image","-webkit-mask-image","list-style-image"];function Dt(e,i){return It.map(t=>{let n=e.getPropertyValue(t);return!n||n==="none"?null:((k||j)&&i.drawImageCount++,ve(n,null,i,!0).then(o=>{!o||n===o||e.setProperty(t,o,e.getPropertyPriority(t))}))}).filter(Boolean)}function Mt(e,i){if(L(e)){let t=e.currentSrc||e.src;if(!G(t))return[I(i,{url:t,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(n=>{n&&(e.srcset="",e.dataset.originalSrc=t,e.src=n||"")})];(k||j)&&i.drawImageCount++}else if(D(e)&&!G(e.href.baseVal)){let t=e.href.baseVal;return[I(i,{url:t,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(n=>{n&&(e.dataset.originalSrc=t,e.href.baseVal=n||"")})]}return[]}function Rt(e,i){let{ownerDocument:t,svgDefsElement:n}=i,o=e.getAttribute("href")??e.getAttribute("xlink:href");if(!o)return[];let[r,l]=o.split("#");if(l){let s=`#${l}`,c=t?.querySelector(`svg ${s}`);if(r&&e.setAttribute("href",s),n?.querySelector(s))return[];if(c)return n?.appendChild(c.cloneNode(!0)),[];if(r)return[I(i,{url:r,responseType:"text"}).then(h=>{n?.insertAdjacentHTML("beforeend",h)})]}return[]}function Te(e,i){let{tasks:t}=i;v(e)&&((L(e)||ge(e))&&t.push(...Mt(e,i)),Ue(e)&&t.push(...Rt(e,i))),x(e)&&t.push(...Dt(e.style,i)),e.childNodes.forEach(n=>{Te(n,i)})}async function _t(e,i){let{ownerDocument:t,svgStyleElement:n,fontFamilies:o,fontCssTexts:r,tasks:l,font:s}=i;if(!(!t||!n||!o.size))if(s&&s.cssText){let c=se(s.cssText,i);n.appendChild(t.createTextNode(`${c}
`))}else{let c=Array.from(t.styleSheets).filter(a=>{try{return"cssRules"in a&&!!a.cssRules.length}catch(d){return i.log.warn(`Error while reading CSS rules from ${a.href}`,d),!1}});await Promise.all(c.flatMap(a=>Array.from(a.cssRules).map(async(d,g)=>{if(Fe(d)){let m=g+1,u=d.href,f="";try{f=await I(i,{url:u,requestType:"text",responseType:"text"})}catch(b){i.log.warn(`Error fetch remote css import from ${u}`,b)}let p=f.replace(Ae,(b,w,E)=>b.replace(E,ue(E,u)));for(let b of Pt(p))try{a.insertRule(b,b.startsWith("@import")?m+=1:a.cssRules.length)}catch(w){i.log.warn("Error inserting rule from remote css import",{rule:b,error:w})}}}))),c.flatMap(a=>Array.from(a.cssRules)).filter(a=>ke(a)&&Se(a.style.getPropertyValue("src"))&&pe(a.style.getPropertyValue("font-family"))?.some(d=>o.has(d))).forEach(a=>{let d=a,g=r.get(d.cssText);g?n.appendChild(t.createTextNode(`${g}
`)):l.push(ve(d.cssText,d.parentStyleSheet?d.parentStyleSheet.href:null,i).then(m=>{m=se(m,i),r.set(d.cssText,m),n.appendChild(t.createTextNode(`${m}
`))}))})}}var Ot=/(\/\*[\s\S]*?\*\/)/g,re=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;function Pt(e){if(e==null)return[];let i=[],t=e.replace(Ot,"");for(;;){let r=re.exec(t);if(!r)break;i.push(r[0])}t=t.replace(re,"");let n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let r=n.exec(t);if(r)o.lastIndex=n.lastIndex;else if(r=o.exec(t),r)n.lastIndex=o.lastIndex;else break;i.push(r[0])}return i}var kt=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Ft=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function se(e,i){let{font:t}=i,n=t?t?.preferredFormat:void 0;return n?e.replace(Ft,o=>{for(;;){let[r,,l]=kt.exec(o)||[];if(!l)return"";if(l===n)return`src: ${r};`}}):e}async function Ut(e,i){let t=await z(e,i);if(v(t.node)&&D(t.node))return t.node;let{ownerDocument:n,log:o,tasks:r,svgStyleElement:l,svgDefsElement:s,svgStyles:c,font:h,progress:a,autoDestruct:d,onCloneNode:g,onEmbedNode:m,onCreateForeignObjectSvg:u}=t;o.time("clone node");let f=await q(t.node,t,!0);if(l&&n){let y="";c.forEach((A,S)=>{y+=`${A.join(`,
`)} {
  ${S}
}
`}),l.appendChild(n.createTextNode(y))}o.timeEnd("clone node"),await g?.(f),h!==!1&&v(f)&&(o.time("embed web font"),await _t(f,t),o.timeEnd("embed web font")),o.time("embed node"),Te(f,t);let p=r.length,b=0,w=async()=>{for(;;){let y=r.pop();if(!y)break;try{await y}catch(A){t.log.warn("Failed to run task",A)}a?.(++b,p)}};a?.(b,p),await Promise.all([...Array.from({length:4})].map(w)),o.timeEnd("embed node"),await m?.(f);let E=$t(f,t);return s&&E.insertBefore(s,E.children[0]),l&&E.insertBefore(l,E.children[0]),d&&Ht(t),await u?.(E),E}function $t(e,i){let{width:t,height:n}=i,o=Qe(t,n,e.ownerDocument),r=o.ownerDocument.createElementNS(o.namespaceURI,"foreignObject");return r.setAttributeNS(null,"x","0%"),r.setAttributeNS(null,"y","0%"),r.setAttributeNS(null,"width","100%"),r.setAttributeNS(null,"height","100%"),r.append(e),o.appendChild(r),o}async function Bt(e,i){let t=await z(e,i),n=await Ut(t),o=Ze(n,t.isEnable("removeControlCharacter"));t.autoDestruct||(t.svgStyleElement=be(t.ownerDocument),t.svgDefsElement=t.ownerDocument?.createElementNS($,"defs"),t.svgStyles.clear());let r=H(o,n.ownerDocument);return await ct(r,t)}async function Ce(e,i){let t=await z(e,i),{log:n,type:o,quality:r,dpi:l}=t,s=await Bt(t);n.time("canvas to blob");let c=await et(s,o,r);if(["image/png","image/jpeg"].includes(o)&&l){let h=await nt(c.slice(0,33)),a=new Uint8Array(h);return o==="image/png"?a=Re(a,l):o==="image/jpeg"&&(a=Ne(a,l)),n.timeEnd("canvas to blob"),new Blob([a,c.slice(33)],{type:o})}return n.timeEnd("canvas to blob"),c}var M={METADATA:"data-replit-metadata",COMPONENT_NAME:"data-component-name"};function He(e){if(e.startsWith("http://localhost:"))return!0;try{return new URL(e).hostname.endsWith(T.ALLOWED_DOMAIN)}catch{return!1}}function Y(e){if(!e)return null;let i=document.elementFromPoint(e.clientX,e.clientY);return i instanceof HTMLElement?i:null}function Jt(e,i=300){if(!e)return"";let t=String(e);return t.length<=i?t:t.slice(0,i)+"..."}function X(e){if(e)return{tagName:e.tagName.toLowerCase(),className:e.className.toString?e.className.toString():String(e.className),textContent:e.textContent??"",id:e.id}}function B(e){return e.getAttribute(M.COMPONENT_NAME)??e.tagName.toLowerCase()}function K(e){let i=window.getComputedStyle(e),t=e.parentElement,n=e.nextElementSibling,o=t?.parentElement??null,r={backgroundColor:i.backgroundColor,color:i.color,display:i.display,position:i.position,width:i.width,height:i.height,fontSize:i.fontSize,fontFamily:i.fontFamily,fontWeight:i.fontWeight,margin:i.margin,padding:i.padding,textAlign:i.textAlign};return{elementPath:e.getAttribute(M.METADATA)??"",elementName:B(e),textContent:e.textContent??"",originalTextContent:e.getAttribute("data-original-text")?decodeURIComponent(e.getAttribute("data-original-text")??""):void 0,srcAttribute:e.getAttribute("src")??"",hasChildElements:e.childElementCount>0,id:e.id,className:e.className.toString?e.className.toString():String(e.className),computedStyles:r,textAlign:i.textAlign,relatedElements:{parent:X(t),nextSibling:X(n),grandParent:X(o)}}}async function Le(e){try{let t=window.getComputedStyle(e).backgroundColor;return Wt(t)&&(t=window.getComputedStyle(document.documentElement).backgroundColor),await Ce(e,{type:"image/png",backgroundColor:t,fetch:{requestInit:{mode:"no-cors"}}})}catch(i){console.error("[replit-cartographer] Failed to take screenshot:",i);return}}function Wt(e){return e==="transparent"||e==="rgba(0, 0, 0, 0)"||e.endsWith(", 0)")||e.endsWith(",0)")}function R(e){let i=e.getAttribute(M.METADATA);if(!i)return[];let t=`[${M.METADATA}="${i}"]`;return Array.from(document.querySelectorAll(t)).filter(o=>o instanceof HTMLElement).filter(o=>o!==e)}var _=class{selectedElement=null;selectedSiblingElements=[];isActive=!1;lastHighlightedElement=null;enableEditing=!1;shadowHost=null;shadowRoot=null;hoverHighlighter=null;hoverLabel=null;selectedHighlighter=null;selectedLabel=null;hoverSiblingHighlighters=[];selectedSiblingHighlighters=[];mutationObserver=null;constructor(){this.setupMessageListener(),this.notifyScriptLoaded()}initializeHighlighter(){this.shadowHost=document.createElement("div"),this.shadowHost.style.all="initial",this.shadowRoot=this.shadowHost.attachShadow({mode:"open"}),document.body.appendChild(this.shadowHost);let i=document.createElement("style");i.textContent=Z,this.shadowRoot.appendChild(i);let t=document.createElement("style");t.textContent=Q,document.head.appendChild(t),this.hoverHighlighter=document.createElement("div"),this.hoverLabel=document.createElement("div"),this.hoverHighlighter.className="beacon-highlighter beacon-hover-highlighter",this.hoverLabel.className="beacon-label beacon-hover-label",this.selectedHighlighter=document.createElement("div"),this.selectedLabel=document.createElement("div"),this.selectedHighlighter.className="beacon-highlighter beacon-selected-highlighter",this.selectedLabel.className="beacon-label beacon-selected-label",this.shadowRoot.appendChild(this.selectedHighlighter),this.shadowRoot.appendChild(this.selectedLabel),this.shadowRoot.appendChild(this.hoverHighlighter),this.shadowRoot.appendChild(this.hoverLabel)}setupMessageListener(){window.addEventListener("message",this.handleMessage.bind(this))}notifyScriptLoaded(){this.postMessageToParent({type:"SELECTOR_SCRIPT_LOADED",timestamp:Date.now(),version:P})}postMessageToParent(i){window.parent&&window.parent.postMessage(i,"*")}handleMouseMove=i=>{if(this.isActive&&this.hoverHighlighter){let t=Y(i);if(!t||t===this.hoverHighlighter||t===this.selectedHighlighter||t===this.shadowHost||this.selectedSiblingHighlighters.includes(t)||this.hoverSiblingHighlighters.includes(t)){this.hideHighlight(this.hoverHighlighter,this.hoverLabel),this.lastHighlightedElement=null,this.clearHoverSiblingHighlighters();return}if(t===this.selectedElement){this.hideHighlight(this.hoverHighlighter,this.hoverLabel),this.lastHighlightedElement=null,this.clearHoverSiblingHighlighters();return}this.lastHighlightedElement&&this.lastHighlightedElement!==t&&this.lastHighlightedElement!==this.selectedElement&&this.lastHighlightedElement.removeAttribute("contenteditable"),this.lastHighlightedElement=t,this.updateHighlighterPosition(t,this.hoverHighlighter,this.hoverLabel)}};handleMouseLeave=()=>{this.isActive&&(this.hoverHighlighter&&(this.hoverHighlighter.style.opacity="0"),this.hoverLabel&&(this.hoverLabel.style.opacity="0"),this.hoverSiblingHighlighters.length>0&&this.clearHoverSiblingHighlighters(),this.lastHighlightedElement&&this.lastHighlightedElement!==this.selectedElement&&this.lastHighlightedElement.removeAttribute("contenteditable"))};calculateLabelPosition(i,t){return t<28?{top:`${t+window.scrollY}px`,left:`${i.left+window.scrollX}px`,transform:"none",marginTop:"2px"}:{top:`${t+window.scrollY}px`,left:`${i.left+window.scrollX}px`,transform:"translateY(-100%)",marginTop:"-4px"}}updateHighlighterPosition(i,t,n){if(!t||!n)return;let o=R(i);this.enableEditing&&o.length<=1&&i===this.selectedElement&&i.childElementCount===0&&i.tagName.toLowerCase()!=="img"&&i.setAttribute("contenteditable","plaintext-only");let r=i.getBoundingClientRect(),l=window.innerHeight,s=Math.max(0,r.top),c=Math.min(l,r.bottom),h=Math.max(0,c-s);Object.assign(t.style,{opacity:h>0?"1":"0",top:`${s}px`,left:`${r.left}px`,width:`${r.width}px`,height:`${h}px`}),n.textContent=B(i);let a=this.calculateLabelPosition(r,s);Object.assign(n.style,{...a,opacity:h>0?"1":"0"}),t===this.selectedHighlighter?this.highlightSelectedSiblings(i):this.highlightHoverSiblings(i)}hideHighlight(i,t){i&&(i.style.opacity="0"),t&&(t.style.opacity="0");let n=i===this.hoverHighlighter,o=i===this.selectedHighlighter;n&&this.clearHoverSiblingHighlighters(),o&&this.clearSelectedSiblingHighlighters()}handleClick=async i=>{if(!this.isActive)return;i.preventDefault(),i.stopPropagation();let t=Y(i);if((!t||t===this.hoverHighlighter||t===this.selectedHighlighter||t===this.shadowHost)&&(t=this.lastHighlightedElement),!t||t===this.selectedElement)return;this.unselectCurrentElement(),this.clearSelectedSiblingHighlighters(),this.selectedElement=t;let n=R(t),o=n.length>0;o&&this.highlightSelectedSiblings(t),t.hasAttribute("data-original-text")||t.setAttribute("data-original-text",encodeURIComponent(t.textContent??"")),!t.hasAttribute("data-original-style")&&t.hasAttribute("style")&&t.setAttribute("data-original-style",encodeURIComponent(t.getAttribute("style")??"")),!t.hasAttribute("data-original-src")&&t.hasAttribute("src")&&t.setAttribute("data-original-src",encodeURIComponent(t.getAttribute("src")??"")),!o&&this.enableEditing&&t.childElementCount===0&&t.tagName.toLowerCase()!=="img"&&(this.selectedElement.setAttribute("contenteditable","plaintext-only"),this.selectedElement.focus()),this.selectedHighlighter&&this.selectedLabel&&(this.selectedHighlighter.style.outlineStyle="solid",this.selectedHighlighter.style.opacity="1",this.selectedHighlighter.style.pointerEvents="none",this.selectedLabel.style.opacity="1",this.selectedLabel.textContent=B(t)),this.hoverHighlighter&&(this.hoverHighlighter.style.opacity="0",this.hoverHighlighter.style.pointerEvents="none"),this.hoverLabel&&(this.hoverLabel.style.opacity="0"),this.clearHoverSiblingHighlighters(),this.updateHighlighterPosition(t,this.selectedHighlighter,this.selectedLabel);let r=K(t),l;try{l=await Le(t)}catch(s){console.error("[replit-cartographer] Error capturing element screenshot:",s)}this.observeSelectedElement(),this.postMessageToParent({type:"ELEMENT_SELECTED",payload:{...r,screenshotBlob:l??void 0,siblingCount:o?n.length:0},timestamp:Date.now()})};restoreElements(){document.querySelectorAll('[data-replit-dirty="true"]').forEach(t=>{if(t.hasAttribute("data-original-text")&&t.textContent!==decodeURIComponent(t.getAttribute("data-original-text")||"")){let n=decodeURIComponent(t.getAttribute("data-original-text")||"");t.textContent=n,t.removeAttribute("data-original-text")}if(t.hasAttribute("data-original-style")){let n=decodeURIComponent(t.getAttribute("data-original-style")||"");t.setAttribute("style",n),t.removeAttribute("data-original-style")}else t.removeAttribute("style");if(t.hasAttribute("data-original-src")&&t.getAttribute("src")!==decodeURIComponent(t.getAttribute("data-original-src")||"")){let n=decodeURIComponent(t.getAttribute("data-original-src")||"");t.setAttribute("src",n),t.removeAttribute("data-original-src")}t.removeAttribute("data-replit-dirty")})}unselectCurrentElement(){if(this.restoreElements(),this.selectedElement){if(this.selectedElement.removeAttribute("contenteditable"),this.selectedElement.hasAttribute("data-original-style")){let i=decodeURIComponent(this.selectedElement.getAttribute("data-original-style")||"");this.selectedElement.setAttribute("style",i),this.selectedElement.removeAttribute("data-original-style")}if(this.selectedElement.hasAttribute("data-original-src")&&this.selectedElement.getAttribute("src")!==decodeURIComponent(this.selectedElement.getAttribute("data-original-src")||"")){let i=decodeURIComponent(this.selectedElement.getAttribute("data-original-src")||"");this.selectedElement.setAttribute("src",i),this.selectedElement.removeAttribute("data-original-src")}this.selectedElement=null}this.clearSelectedSiblingHighlighters(),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}handleMessage=i=>{if(!He(i.origin))return;let t=i.data;if(!(!t||typeof t!="object"))switch(t.type){case"TOGGLE_REPLIT_VISUAL_EDITOR":{this.handleVisualEditorToggle(t);break}case"CLEAR_SELECTION":{this.unselectCurrentElement(),this.hideHighlight(this.selectedHighlighter,this.selectedLabel);break}case"UPDATE_SELECTED_ELEMENT":{if(!this.selectedElement)return;let{attributes:n}=t;[this.selectedElement,...this.selectedSiblingElements].forEach(r=>{n.style!==void 0&&(r.setAttribute("style",n.style),r.setAttribute("data-replit-dirty","true")),n.textContent!==void 0&&(r.textContent=n.textContent,r.setAttribute("data-replit-dirty","true")),n.className!==void 0&&(r.className=n.className,r.setAttribute("data-replit-dirty","true")),n.src!==void 0&&(r.setAttribute("src",n.src),r.setAttribute("data-replit-dirty","true"))}),this.updateHighlighterPosition(this.selectedElement,this.selectedHighlighter,this.selectedLabel),this.selectedSiblingElements.length>0&&(this.clearHighlighters(this.selectedSiblingHighlighters),this.selectedSiblingHighlighters=[],this.selectedSiblingHighlighters=this.highlightElements(this.selectedSiblingElements));break}case"CLEAR_ELEMENT_DIRTY":{this.selectedElement&&this.selectedElement.removeAttribute("data-replit-dirty");break}}};handleVisualEditorToggle(i){if(i.type!=="TOGGLE_REPLIT_VISUAL_EDITOR")return;let t=!!i.enabled;this.enableEditing=!!i.enableEditing,t?this.postMessageToParent({type:"REPLIT_VISUAL_EDITOR_ENABLED",timestamp:Date.now()}):this.postMessageToParent({type:"REPLIT_VISUAL_EDITOR_DISABLED",timestamp:Date.now()}),this.isActive!==t&&(this.isActive=t,this.toggleEventListeners(t))}observeSelectedElement(){this.selectedElement&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(i=>{if(i.some(n=>n.type==="characterData")&&this.selectedElement){this.selectedElement.setAttribute("data-replit-dirty","true");let n=K(this.selectedElement);this.postMessageToParent({type:"ELEMENT_TEXT_CHANGED",payload:n,timestamp:Date.now()}),this.updateHighlighterPosition(this.selectedElement,this.selectedHighlighter,this.selectedLabel)}}),this.mutationObserver.observe(this.selectedElement,{characterData:!0,childList:!1,attributes:!1,subtree:!0}))}recalculateSelectedElement=()=>{this.isActive&&(this.selectedElement&&this.updateHighlighterPosition(this.selectedElement,this.selectedHighlighter,this.selectedLabel),this.lastHighlightedElement&&this.updateHighlighterPosition(this.lastHighlightedElement,this.hoverHighlighter,this.hoverLabel),this.selectedSiblingElements.length>0&&(this.clearHighlighters(this.selectedSiblingHighlighters),this.selectedSiblingHighlighters=[],this.selectedSiblingHighlighters=this.highlightElements(this.selectedSiblingElements)))};handleKeyDown=i=>{this.isActive&&(i.key==="Escape"||i.key==="Esc")&&this.handleVisualEditorToggle({type:"TOGGLE_REPLIT_VISUAL_EDITOR",enabled:!1,timestamp:Date.now()})};toggleEventListeners(i){i?(this.initializeHighlighter(),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseleave",this.handleMouseLeave),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown),window.addEventListener("resize",this.recalculateSelectedElement),window.addEventListener("scroll",this.recalculateSelectedElement,!0)):(document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("mouseleave",this.handleMouseLeave),document.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("resize",this.recalculateSelectedElement),window.removeEventListener("scroll",this.recalculateSelectedElement,!0),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.selectedElement&&(this.selectedElement.removeAttribute("contenteditable"),this.selectedElement.removeAttribute("data-original-text"),document.querySelectorAll('[contenteditable="plaintext-only"]').forEach(t=>{t.removeAttribute("contenteditable")})),this.clearSelectedSiblingHighlighters(),this.clearHoverSiblingHighlighters(),this.hoverHighlighter?.remove(),this.hoverLabel?.remove(),this.selectedHighlighter?.remove(),this.selectedLabel?.remove(),this.shadowHost?.remove(),this.hoverHighlighter=null,this.hoverLabel=null,this.selectedHighlighter=null,this.selectedLabel=null,this.shadowHost=null,this.shadowRoot=null,this.selectedElement=null)}clearHighlighters(i){return i.forEach(t=>{t.remove()}),[]}clearHoverSiblingHighlighters(){this.hoverSiblingHighlighters=this.clearHighlighters(this.hoverSiblingHighlighters)}clearSelectedSiblingHighlighters(){this.selectedSiblingElements.forEach(i=>{i.removeAttribute("contenteditable")}),this.selectedSiblingElements=[],this.selectedSiblingHighlighters=this.clearHighlighters(this.selectedSiblingHighlighters)}highlightElements(i){if(!this.shadowRoot||i.length===0)return[];let t=[];return i.forEach(n=>{let o=document.createElement("div");o.className="beacon-highlighter beacon-sibling-highlighter",this.shadowRoot?.appendChild(o),t.push(o);let r=n.getBoundingClientRect(),l=window.innerHeight,s=Math.max(0,r.top),c=Math.min(l,r.bottom),h=Math.max(0,c-s);Object.assign(o.style,{opacity:h>0?"1":"0",top:`${s}px`,left:`${r.left}px`,width:`${r.width}px`,height:`${h}px`})}),t}highlightHoverSiblings(i){this.clearHoverSiblingHighlighters();let t=R(i);this.hoverSiblingHighlighters=this.highlightElements(t)}highlightSelectedSiblings(i){this.clearSelectedSiblingHighlighters(),this.selectedSiblingElements=R(i),this.selectedSiblingHighlighters=this.highlightElements(this.selectedSiblingElements)}};if(typeof window<"u")try{window.REPLIT_BEACON_VERSION||(window.REPLIT_BEACON_VERSION=P,new _)}catch(e){console.error("[replit-beacon] Failed to initialize:",e)}})();
</script>
  </head>
  <body>
    <!-- Step 1: Instant Frame - Shows immediately while React loads -->
    <div id="instant-frame" style="
      position: fixed;
      inset: 0;
      z-index: 9999;
      background-color: #ffffff;
      opacity: 1;
      transition: opacity 300ms ease-out;
      will-change: opacity;
      pointer-events: none;
    "></div>

    <!-- Step 2: React App loads invisibly under the instant frame -->
    <div id="root" style="opacity: 0; transition: opacity 300ms ease-in; will-change: opacity;"></div>
    
    <!-- Step 3: Progressive removal script -->
    <script>
      // Progressive Visual Bootstrapping System
      (function() {
        var instantFrame = document.getElementById('instant-frame');
        var reactRoot = document.getElementById('root');
        var isReactReady = false;
        var isPageLoaded = false;
        var isTransitioning = false;
        
        // Apply landing page background only for root path
        var isLandingPage = window.location.pathname === '/' || window.location.pathname === '';
        if (isLandingPage && instantFrame) {
          instantFrame.style.backgroundImage = "url('/LandingPageAdventure.webp')";
          instantFrame.style.backgroundSize = "cover";
          instantFrame.style.backgroundPosition = "center top";
          instantFrame.style.backgroundRepeat = "no-repeat";
        }
        
        // Enhanced React readiness detection
        function checkReactReady() {
          // Check for React ready event
          if (document.documentElement.hasAttribute('data-react-ready')) {
            isReactReady = true;
            tryRemoveInstantFrame();
            return;
          }
          
          // Fallback: Check for DOM children
          var rootChild = reactRoot && reactRoot.firstChild;
          if (rootChild && rootChild.tagName && rootChild.tagName.toLowerCase() !== 'script') {
            isReactReady = true;
            tryRemoveInstantFrame();
          }
        }
        
        // Smooth transition from instant frame to React app
        function tryRemoveInstantFrame() {
          if (isReactReady && isPageLoaded && !isTransitioning) {
            isTransitioning = true;
            
            // Show React app first
            if (reactRoot) {
              reactRoot.style.opacity = '1';
            }
            
            // Then fade out instant frame smoothly
            setTimeout(function() {
              if (instantFrame) {
                instantFrame.style.opacity = '0';
                
                // Remove after transition
                setTimeout(function() {
                  if (instantFrame && instantFrame.parentNode) {
                    instantFrame.parentNode.removeChild(instantFrame);
                    console.log('✅ Progressive Visual Bootstrapping: Instant frame removed');
                  }
                }, 300);
              }
            }, 150);
          }
        }
        
        // Listen for page load
        function onPageLoad() {
          isPageLoaded = true;
          tryRemoveInstantFrame();
        }
        
        // Listen for React app ready event
        document.addEventListener('react-app-ready', function(event) {
          console.log('✅ React app ready:', event.detail);
          isReactReady = true;
          tryRemoveInstantFrame();
        });
        
        // Check React readiness periodically (fallback)
        var checkInterval = setInterval(function() {
          if (isReactReady) {
            clearInterval(checkInterval);
            return;
          }
          checkReactReady();
        }, 100);
        
        // Faster emergency fallback: Remove after maximum timeout (reduced from 8s to 2s)
        setTimeout(function() {
          if (instantFrame && !isTransitioning) {
            console.log('⚠️ Progressive Visual Bootstrapping: Emergency fallback triggered');
            isPageLoaded = true;
            isReactReady = true;
            tryRemoveInstantFrame();
          }
          clearInterval(checkInterval);
        }, 2000);
        
        // Additional aggressive fallback specifically for content loading
        setTimeout(function() {
          if (instantFrame) {
            console.log('🚀 Progressive Visual Bootstrapping: Aggressive content loading fallback');
            if (instantFrame.parentNode) {
              instantFrame.style.opacity = '0';
              setTimeout(function() {
                if (instantFrame.parentNode) {
                  instantFrame.parentNode.removeChild(instantFrame);
                  console.log('✅ Progressive Visual Bootstrapping: Instant frame force removed');
                }
              }, 100);
            }
          }
        }, 1500);
        
        // Listen for various load events
        if (document.readyState === 'complete') {
          onPageLoad();
        } else {
          window.addEventListener('load', onPageLoad);
          document.addEventListener('DOMContentLoaded', onPageLoad);
        }
        
        // Performance tracking
        if (window.performance && window.performance.mark) {
          window.performance.mark('instant-frame-start');
        }
      })();
    </script>
    
    <script>
      // Fix for Vite HMR WebSocket connection
      if (window.location.hostname === 'localhost' || window.location.hostname.includes('replit.dev')) {
        window.__vite_port__ = window.location.port || '5000';
      }
      
      // Adventure page specific optimizations
      (function() {
        // Preload critical Adventure page resources when user navigates to /adventure
        if (window.location.pathname === '/adventure') {
          // Preload adventure-specific images
          const adventureImages = [
            '/lovable-uploads/38221cf2-7157-4fa4-9284-9676804b29bc.png'
          ];
          
          adventureImages.forEach(src => {
            const link = document.createElement('link');
            link.rel = 'preload';
            link.href = src;
            link.as = 'image';
            document.head.appendChild(link);
          });
        }
        
        // Optimize for back/forward cache
        window.addEventListener('pageshow', function(event) {
          if (event.persisted) {
            document.body.classList.add('bf-cache-restored');
          }
        });
        
        window.addEventListener('pagehide', function() {
          // Clean up any intervals or connections that might prevent BF cache
        });
        
        // Performance optimizations for Adventure page
        if (window.location.pathname === '/adventure') {
          // Defer non-critical resources
          setTimeout(() => {
            // Load non-critical Adventure assets
            const nonCriticalAssets = [];
            nonCriticalAssets.forEach(src => {
              const link = document.createElement('link');
              link.rel = 'prefetch';
              link.href = src;
              document.head.appendChild(link);
            });
          }, 2000);
        }
      })();
    </script>
    <!-- Development banner only in development mode -->
    <script>
      if (window.location.hostname === 'localhost' || window.location.hostname.includes('replit.dev')) {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://replit.com/public/js/replit-dev-banner.js';
        script.async = true;
        script.onerror = function() {
          console.warn('Replit banner script failed to load - this is normal in production');
        };
        document.head.appendChild(script);
      }
    </script>
  </body>
</html>