1var e=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,s=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,r=(t,i,s)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[i]=s,o=(e,t)=>{for(var i in t||(t={}))n.call(t,i)&&r(e,i,t[i]);if(s)for(var i of s(t))a.call(t,i)&&r(e,i,t[i]);return e},l=(e,s)=>t(e,i(s)),c=(e,t,i)=>new Promise((s,n)=>{var a=e=>{try{o(i.next(e))}catch(t){n(t)}},r=e=>{try{o(i.throw(e))}catch(t){n(t)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(a,r);o((i=i.apply(e,t)).next())});import{A as u,D as h,o as d,C as m,_ as p,i as g,u as f}from"./index-CoMAdSaI.js";import{r as y,j as b,g as w}from"./react-vendor-73cbJX8F.js";import{m as k}from"./SocraticTutor-D1PWsSJQ.js";var v={};const x=new class{constructor(){this.cache=new Map,this.cacheTimeout=18e5,this.musicCategories={classical:["orchestra","symphony","classical music","concert hall","conductor","violin","cello","piano","flute","clarinet","trumpet","trombone","french horn","timpani","harp","oboe","bassoon","percussion","string quartet","chamber music"],jazz:["jazz music","jazz band","saxophone","trumpet","piano","double bass","drums","jazz club","jazz musician","improvisation","swing","bebop","cool jazz","fusion","smooth jazz","jazz festival","jazz ensemble"],rock:["rock music","electric guitar","bass guitar","drums","rock band","concert","stage","microphone","amplifier","rock concert","music festival","band performance","electric bass","keyboard","synthesizer","rock star","beatles","beatle","lennon","mccartney","harrison","starr","ringo","paul","john","george","album","single","record","recording","studio","producer","arrangement","lyrics"],folk:["folk music","acoustic guitar","banjo","mandolin","fiddle","harmonica","accordion","traditional music","cultural music","ethnic music","world music","indigenous music","heritage music","roots music"],electronic:["electronic music","synthesizer","drum machine","dj equipment","music production","studio equipment","digital audio","electronic instruments","music technology","computer music","electronic dance music"],historical:["medieval music","renaissance music","baroque music","classical period","romantic music","early music","ancient music","historical instruments","period instruments","music manuscript","music history"],cultural:["african music","asian music","latin music","middle eastern music","indian music","chinese music","japanese music","celtic music","slavic music","arabic music","flamenco","tango","samba","reggae"]},this.musicFallbacks={general:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Violin_VL100.jpg/800px-Violin_VL100.jpg",title:"Musical Instruments",pageURL:"https://commons.wikimedia.org/wiki/File:Violin_VL100.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Grand_piano.jpg/800px-Grand_piano.jpg",title:"Music Studio",pageURL:"https://commons.wikimedia.org/wiki/File:Grand_piano.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],classical:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Orchestra.jpg/800px-Orchestra.jpg",title:"Classical Orchestra",pageURL:"https://commons.wikimedia.org/wiki/File:Orchestra.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],jazz:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Saxophone.jpg/800px-Saxophone.jpg",title:"Jazz Performance",pageURL:"https://commons.wikimedia.org/wiki/File:Saxophone.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}]}}normalizeImageResult(e){if(!e||!e.url||"string"!=typeof e.url)return e;const t=u||"https://www.thediscourse.ai",i=o({},e),s=["upload.wikimedia.org","pixabay.com","wikipedia.org"].some(e=>i.url.includes(e)),n=i.url.includes("/api/image/fast")||i.url.includes("/api/image/proxy");return s&&!n?i.url=`${t}/api/image/fast?url=${encodeURIComponent(i.url)}`:i.url.startsWith("/api/")?i.url=`${t}${i.url}`:0===i.url.indexOf("https://api.thediscourse.ai/api/image/")&&(i.url=i.url.replace("https://api.thediscourse.ai",t)),i.pageURL&&"string"==typeof i.pageURL&&0===i.pageURL.indexOf("https://api.thediscourse.ai/api/image/")&&(i.pageURL=i.pageURL.replace("https://api.thediscourse.ai",t)),i}detectMusicCategory(e,t=""){const i=`${e} ${t}`.toLowerCase();for(const[n,a]of Object.entries(this.musicCategories))for(const e of a)if(i.includes(e.toLowerCase()))return n;const s=["music","musical","melody","rhythm","harmony","composition","performance","concert","song","tune","note","scale","chord","tempo","beat","pitch","sound","audio"];for(const n of s)if(i.includes(n))return"general";return null}generateMusicSearchQueries(e,t="",i=null){const s=[],n=`${e} ${t}`.toLowerCase();if(e&&s.push(e),i&&this.musicCategories[i]){const t=this.musicCategories[i];for(const i of t)if(n.includes(i.toLowerCase())||e.toLowerCase().includes(i.toLowerCase())){s.push(i);break}}if(!i){const e=["music","musical","instrument","performance"];for(const t of e)if(n.includes(t)){s.push(t);break}}const a=["piano","guitar","violin","drums","trumpet","saxophone","flute","clarinet","cello","bass","harp","oboe","bassoon","trombone","french horn","timpani"];for(const o of a)if(n.includes(o)){s.push(o);break}const r=["classical","jazz","rock","pop","folk","electronic","medieval","renaissance","baroque","romantic","modern","contemporary","traditional","experimental"];for(const o of r)if(n.includes(o)){s.push(o);break}return s.slice(0,5)}searchMusicImages(e,t,i){return c(this,arguments,function*(e,t,i,s=[],n=[]){const a=this.getCacheKey(e,t,i),r=this.getFromCache(a);if(r)return r;try{const r=this.detectMusicCategory(e);this.generateMusicSearchQueries(e,"",r);try{const o=yield h("/api/image-search/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonTitle:e.substring(0,100),content:`Music lesson about ${e}. ${r?`Category: ${r}`:""}`,usedImageTitles:s,usedImageUrls:n,courseId:t,lessonId:i,disableModeration:!0,musicContext:!0,musicCategory:r})});if(o&&o.url){const e=this.normalizeImageResult(o);return this.setCache(a,e),e}}catch(o){}return yield this.searchMusicFallback(e,r,s,n)}catch(l){return this.getMusicFallback(category)}})}searchMusicFallback(e,t,i,s){return c(this,null,function*(){try{const n=this.generateMusicSearchQueries(e,"",t);for(const e of n){const t=yield this.searchPixabayMusic(e,i,s);if(t)return this.normalizeImageResult(t)}return this.getMusicFallback(t)}catch(n){return this.getMusicFallback(t)}})}searchPixabayMusic(e,t,i){return c(this,null,function*(){try{const t=v.PIXABAY_API_KEY;if(!t)return null;const i=`music ${e}`,s=yield fetch(`https://pixabay.com/api/?key=${t}&q=${encodeURIComponent(i)}&image_type=photo&orientation=horizontal&safesearch=true&per_page=20&min_width=800&min_height=600`,{signal:AbortSignal.timeout(1e4)});
1if(!s.ok)throw new Error(`Pixabay API error: ${s.status}`);const n=yield s.json();if(n.hits&&n.hits.length>0){const t=n.hits.filter(e=>{var t;const i=(e.tags||"").toLowerCase(),s=(null==(t=(e.tags||"").split(",")[0])?void 0:t.toLowerCase())||"";return["music","musical","instrument","concert","performance","band","orchestra","singer","song"].some(e=>i.includes(e)||s.includes(e))});if(t.length>0){const i=t[0];return{url:i.webformatURL,title:i.tags||e,pageURL:i.pageURL,attribution:"Pixabay",uploader:i.user,description:i.tags||e}}}return null}catch(t){return null}})}getMusicFallback(e="general"){const t=this.musicFallbacks[e]||this.musicFallbacks.general,i=Math.floor(Math.random()*t.length);return this.normalizeImageResult(t[i])}forceImageReplacement(e,t,i){return c(this,arguments,function*(e,t,i,s=[],n=[]){const a=this.getCacheKey(e,t,i);return this.cache.delete(a),yield this.searchMusicImages(e,t,i,s,n)})}getCacheKey(e,t,i){return`music_image_${t}_${i}_${e.replace(/[^a-zA-Z0-9]/g,"_").substring(0,50)}`}getFromCache(e){const t=this.cache.get(e);return t&&Date.now()-t.timestamp<this.cacheTimeout?t.data:(t&&this.cache.delete(e),null)}setCache(e,t){if(this.cache.set(e,{data:t,timestamp:Date.now()}),this.cache.size>100){const e=this.cache.keys().next().value;this.cache.delete(e)}}clearCache(){this.cache.clear()}getCacheStats(){return{size:this.cache.size,maxSize:100,timeout:this.cacheTimeout}}};var S={};const C={cache:new Map,cacheTimeout:18e5,fallbackImages:{history:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Pantheon_Rome.jpg/800px-Pantheon_Rome.jpg",title:"Ancient Historical Architecture",pageURL:"https://commons.wikimedia.org/wiki/File:Pantheon_Rome.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Acropolis_of_Athens_01361.JPG/800px-Acropolis_of_Athens_01361.JPG",title:"Classical Architecture",pageURL:"https://commons.wikimedia.org/wiki/File:Acropolis_of_Athens_01361.JPG",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Codex_Manesse_Heinrich_von_Veldeke.jpg/800px-Codex_Manesse_Heinrich_von_Veldeke.jpg",title:"Ancient Manuscripts",pageURL:"https://commons.wikimedia.org/wiki/File:Codex_Manesse_Heinrich_von_Veldeke.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],ancient:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Colosseum_in_Rome%2C_Italy_-_April_2007.jpg/800px-Colosseum_in_Rome%2C_Italy_-_April_2007.jpg",title:"Ancient Civilization",pageURL:"https://commons.wikimedia.org/wiki/File:Colosseum_in_Rome%2C_Italy_-_April_2007.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Roman_Forum_View.jpg/800px-Roman_Forum_View.jpg",title:"Historical Monument",pageURL:"https://commons.wikimedia.org/wiki/File:Roman_Forum_View.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],egypt:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Kheops-Pyramid.jpg/800px-Kheops-Pyramid.jpg",title:"Ancient Egypt",pageURL:"https://commons.wikimedia.org/wiki/File:Kheops-Pyramid.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Sphinx_of_Giza.jpg/800px-Sphinx_of_Giza.jpg",title:"Egyptian Architecture",pageURL:"https://commons.wikimedia.org/wiki/File:Sphinx_of_Giza.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],science:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Laboratory_glassware.jpg/800px-Laboratory_glassware.jpg",title:"Scientific Discovery",pageURL:"https://commons.wikimedia.org/wiki/File:Laboratory_glassware.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Microscope_optics.jpg/800px-Microscope_optics.jpg",title:"Scientific Equipment",pageURL:"https://commons.wikimedia.org/wiki/File:Microscope_optics.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],education:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Library_books.jpg/800px-Library_books.jpg",title:"Learning and Education",pageURL:"https://commons.wikimedia.org/wiki/File:Library_books.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Old_books.jpg/800px-Old_books.jpg",title:"Knowledge and Wisdom",pageURL:"https://commons.wikimedia.org/wiki/File:Old_books.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],technology:[{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Desktop_computer_clipart_-_Angle_view.svg/800px-Desktop_computer_clipart_-_Angle_view.svg.png",title:"Modern Computing",pageURL:"https://commons.wikimedia.org/wiki/File:Desktop_computer_clipart_-_Angle_view.svg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Modern_Laptop_Computer.jpg/800px-Modern_Laptop_Computer.jpg",title:"Laptop Technology",pageURL:"https://commons.wikimedia.org/wiki/File:Modern_Laptop_Computer.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/iPhone_13_Pro_Max.png/440px-iPhone_13_Pro_Max.png",title:"Smartphone Technology",pageURL:"https://commons.wikimedia.org/wiki/File:iPhone_13_Pro_Max.png",attribution:"Wikimedia Commons",uploader:"Wikimedia"}],default:[{url:"https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png",title:"Educational Content",pageURL:"https://commons.wikimedia.org/wiki/File:Profile_avatar_placeholder_large.png",attribution:"Wikimedia Commons",uploader:"Wikimedia"},{url:"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Library_books.jpg/800px-Library_books.jpg",title:"Learning and Education",pageURL:"https://commons.wikimedia.org/wiki/File:Library_books.jpg",attribution:"Wikimedia Commons",uploader:"Wikimedia"}]},getCacheKey(e,t,i){const s=this.extractLessonContext(e);return`${t}_${i}_${(null==e?void 0:e.substring(0,50))||"default"}_${s}`},extractLessonContext(e){if(!e)return"default";const t=e.toLowerCase();let i="";if(t.includes("early")&&t.includes("dynastic"))i="early_dynastic";else if(t.includes("unification"))i="unification";else if(t.includes("period"))i="period";else if(t.includes("empire"))i="empire";else if(t.includes("dynasty"))i="dynasty";else if(t.includes("kingdom"))i="kingdom";else if(t.includes("civilization"))i="civilization";else if(t.includes("ancient"))i="ancient";else if(t.includes("historical"))i="historical";else{i=t.split(/\s+/).filter(e=>e.length>3).slice(0,2).join("_")}return i||"default"},getFromCache(e){const t=this.cache.get(e);return t&&Date.now()-t.timestamp<this.cacheTimeout?t.data:(t&&this.cache.delete(e),null)},setCache(e,t){this.cache.set(e,{data:t,timestamp:Date.now()})},normalizeImageResult(e){if(!e||!e.url||"string"!=typeof e.url)return e;const t=u||"https://www.thediscourse.ai",i=o({},e),s=["upload.wikimedia.org","pixabay.com","wikipedia.org"].some(e=>i.url.includes(e)),n=i.url.includes("/api/image/fast")||i.url.includes("/api/image/proxy");return s&&!n?i.url=`${t}/api/image/fast?url=${encodeURIComponent(i.url)}`:i.url.startsWith("/images/")&&!i.url.startsWith("/images/onboarding/")?i.url=`${t}/api${i.url}`:i.url.startsWith("/api/")?i.url=`${t}${i.url}`:0===i.url.indexOf("https://api.thediscourse.ai/api/image/")&&(i.url=i.url.replace("https://api.thediscourse.ai",t)),i.pageURL&&"string"==typeof i.pageURL&&0===i.pageURL.indexOf("https://api.thediscourse.ai/api/image/")&&(i.pageURL=i.pageURL.replace("https://api.thediscourse.ai",t)),i},search(e,t,i){return c(this,arguments,function*(e,t,i,s=[],n=[],a="",r=null,o=""){if(!e||!t||!i)return this.getFallbackImage(e);const l=this.detectMusicContent(e);
1if(l)return yield x.searchMusicImages(e,t,i,s,n);const c=yield this.getCourseContext(t,r);if(c&&this.detectMusicContent(c.title||c.subject||""))return yield x.searchMusicImages(e,t,i,s,n);this.detectHistoricalContent(e);const u=this.getCacheKey(e,t,i),d=this.getFromCache(u);if(d)return d;try{const l=yield this.searchWikimedia(e,a,o);if(l){const e=this.normalizeImageResult(l);return this.setCache(u,e),e}const c=yield this.searchPixabay(e,a,o);if(c){const e=this.normalizeImageResult(c);return this.setCache(u,e),e}try{const l=yield h("/api/image-search/search",{method:"POST",body:JSON.stringify({lessonTitle:e.substring(0,100),courseSubject:a,content:o||"",usedImageTitles:s,usedImageUrls:n,courseId:t,lessonId:i,sessionId:r||void 0,disableModeration:!0})});if(l&&l.url){const e=this.normalizeImageResult(l);if(this.isValidUrl(e.url)||e.url)return this.setCache(u,e),e}}catch(m){}const d=this.getFallbackImage(e),p=this.normalizeImageResult(d);return this.setCache(u,p),p}catch(m){try{const t=yield this.searchWikimedia(e,a,o);if(t){const e=this.normalizeImageResult(t);return this.setCache(u,e),e}}catch(p){}try{const t=yield this.searchPixabay(e,a,o);if(t){const e=this.normalizeImageResult(t);return this.setCache(u,e),e}}catch(g){}const t=this.getFallbackImage(e,a),i=this.normalizeImageResult(t);return this.setCache(u,i),i}})},searchWikimedia(e,t="",i=""){return c(this,null,function*(){var s;try{const n=this.optimizeSearchQuery(e,t,i),a=yield fetch(`https://commons.wikimedia.org/w/api.php?action=query&format=json&origin=*&generator=search&gsrnamespace=6&gsrsearch=${encodeURIComponent(n)}&gsrlimit=10&prop=imageinfo|info&iiprop=url|size|mime|user|extmetadata&iiurlwidth=1600&iiurlheight=1000&inprop=url`,{signal:AbortSignal.timeout(8e3)});if(!a.ok)throw new Error(`Wikimedia API error: ${a.status}`);const r=yield a.json(),o=Object.values((null==(s=null==r?void 0:r.query)?void 0:s.pages)||{});if(!o.length)return null;const l=["logo","icon","symbol","diagram","coat_of_arms","map_icon","disambiguation","title page","frontispiece","title-page","titlepage","dictionary of","encyclopaedia","encyclopedia","national biography","table of contents","index of","printed page","text page","book page","dictionnaire","lexicon","almanac","compendium","tome"],c=o.map(e=>{var t;const i=null==(t=null==e?void 0:e.imageinfo)?void 0:t[0];if(!(i&&i.url&&i.mime&&i.mime.startsWith("image/")))return null;const s=(e.title||"").replace(/^File:/i,"").replace(/_/g," "),a=s.toLowerCase(),r=l.some(e=>a.includes(e)),o=(n.toLowerCase().includes("viking")||n.toLowerCase().includes("norse"))&&["rugby","football","nfl","nhl","nba","jersey","stadium","pitch","mascot","sports","team","player","league","championship","minnesota","widnes"].some(e=>a.includes(e));if(r||o)return null;const c=Number(i.width||0),u=Number(i.height||0);return{score:(c>0&&u>0?c*u:0)+(/image\/(jpeg|jpg|png|webp)/i.test(i.mime)?1e9:0),image:{url:i.thumburl||i.url,title:s||n,pageURL:`https://commons.wikimedia.org/wiki/${encodeURIComponent((e.title||"").replace(/\s+/g,"_"))}`,attribution:"Wikimedia Commons",uploader:i.user||"Wikimedia Contributor",description:s||n}}}).filter(Boolean).sort((e,t)=>t.score-e.score);return c.length?c[0].image:null}catch(n){return null}})},searchWikimediaMultiple(e,t="",i="",s=12){return c(this,null,function*(){var n;try{const a=this.optimizeSearchQuery(e,t,i),r=yield fetch(`https://commons.wikimedia.org/w/api.php?action=query&format=json&origin=*&generator=search&gsrnamespace=6&gsrsearch=${encodeURIComponent(a)}&gsrlimit=${Math.min(30,2*s)}&prop=imageinfo|info&iiprop=url|size|mime|user|extmetadata&iiurlwidth=1600&iiurlheight=1000&inprop=url`,{signal:AbortSignal.timeout(8e3)});if(!r.ok)throw new Error(`Wikimedia API error: ${r.status}`);const o=yield r.json(),l=Object.values((null==(n=null==o?void 0:o.query)?void 0:n.pages)||{});return l.map(e=>{var t;const i=null==(t=null==e?void 0:e.imageinfo)?void 0:t[0];if(!(i&&i.url&&i.mime&&i.mime.startsWith("image/")))return null;const s=(e.title||"").replace(/^File:/i,"").replace(/_/g," "),n=Number(i.width||0),r=Number(i.height||0);return{score:(n>0&&r>0?n*r:0)+(/image\/(jpeg|jpg|png|webp)/i.test(i.mime)?1e9:0),image:{url:i.thumburl||i.url,title:s||a,pageURL:`https://commons.wikimedia.org/wiki/${encodeURIComponent((e.title||"").replace(/\s+/g,"_"))}`,attribution:"Wikimedia Commons",uploader:i.user||"Wikimedia Contributor",description:s||a}}}
1).filter(Boolean).sort((e,t)=>t.score-e.score).slice(0,s).map(e=>e.image)}catch(a){return[]}})},searchMultiple(e,t="",i="",s=12){return c(this,null,function*(){const n=[],a=new Set,r=e=>{const t=this.normalizeImageResult(e);(null==t?void 0:t.url)&&!a.has(t.url)&&(a.add(t.url),n.push(t))};try{const n=yield h("/api/image-search/search-multiple",{method:"POST",body:JSON.stringify({query:e,courseSubject:t,content:i,limit:s})}),a=Array.isArray(null==n?void 0:n.images)?n.images:[];for(const e of a)r(e)}catch(o){}if(n.length<s)try{const n=yield this.searchWikimediaMultiple(e,t,i,s);for(const e of n)r(e)}catch(o){}return n.slice(0,s)})},searchWithContext(e,t,i,s,n,a,r,o){return c(this,null,function*(){return yield this.search(e,a,r,s,n,t,null,i)})},searchPixabay(e,t="",i=""){return c(this,null,function*(){try{const s=S.PIXABAY_API_KEY;if(!s)return null;const n=this.optimizeSearchQuery(e,t,i),a=yield fetch(`https://pixabay.com/api/?key=${s}&q=${encodeURIComponent(n)}&image_type=photo&orientation=horizontal&safesearch=true&per_page=10&min_width=800&min_height=600`,{signal:AbortSignal.timeout(8e3)});if(!a.ok)throw new Error(`Pixabay API error: ${a.status}`);const r=yield a.json();if(r.hits&&r.hits.length>0){const e=n.toLowerCase().includes("viking")||n.toLowerCase().includes("norse"),t=["rugby","football","nfl","nhl","nba","jersey","stadium","pitch","mascot","sports team","sports player","player","league","championship","minnesota","widnes","reels to revenue","seeen","dcbl"],i=e?r.hits.filter(e=>{const i=`${e.tags||""} ${e.user||""}`.toLowerCase();return!t.some(e=>i.includes(e))}):r.hits;if(!i.length&&r.hits.length>0)return null;const s=i.length?i:r.hits;let a=s[0];for(const n of s.slice(0,5))if(n.imageWidth>=1200&&n.imageHeight>=800){a=n;break}return{url:a.webformatURL,title:a.tags||n,pageURL:a.pageURL,attribution:"Pixabay",uploader:a.user,description:a.tags||n}}return null}catch(s){return null}})},extractContentKeywords(e,t=4){if(!e||"string"!=typeof e)return[];const i=new Set(["the","a","an","and","or","of","in","on","to","for","by","with","at","from","as","is","are","was","were","be","being","been","this","that","these","those","it","its","into","about","over","under","between","through","during","before","after","up","down","out","off","than","which","who","what","when","where","how","can","could","would","should","will","have","has","had","do","does","did","not","but","also","such","they","their","them","we","our","you","your","he","she","his","her","its","one","two","three","first","second","third","many","more","most","some","any","all","each","both","few","very","just","however","therefore"]),s={},n=e.replace(/<[^>]+>/g," ").replace(/&[a-z]+;/gi," ").toLowerCase().replace(/[^\w\s'-]/g," ").split(/\s+/);for(const a of n){const e=a.replace(/^[-']+|[-']+$/g,"");e.length>3&&!i.has(e)&&/^[a-z]/.test(e)&&(s[e]=(s[e]||0)+1)}return Object.entries(s).sort((e,t)=>t[1]-e[1]).slice(0,t).map(([e])=>e)},optimizeSearchQuery(e,t="",i=""){if(!e)return"education";const s=["the","a","an","and","or","of","in","on","to","for","by","with","at","from","as","is","are","was","were","be","being","been","this","that","these","those","it","its","into","about","over","under","between","through","during","before","after","above","below","up","down","out","off","than"];let n=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2&&!s.includes(e)).slice(0,4).join(" ");if(i){const e=this.extractContentKeywords(i,4);if(e.length){const t=n.split(/\s+/).filter(Boolean);n=[...new Set([...t,...e])].slice(0,5).join(" ")}}if(n.includes("egypt")||n.includes("ancient")||n.includes("dynastic")||n.includes("pharaoh")?n+=" ancient egypt civilization":n.includes("rome")||n.includes("roman")?n+=" roman empire":n.includes("greek")||n.includes("greece")?n+=" greek civilization":n.includes("history")||n.includes("historical")?n+=" historical ancient":n.includes("early")||n.includes("period")?n+=" ancient historical":n.includes("fall")||n.includes("decline")?n+=" empire collapse":n.includes("rise")||n.includes("growth")?n+=" empire expansion":n.includes("city")||n.includes("urban")?n+=" ancient city":n.includes("culture")||n.includes("society")?n+=" ancient culture":n.includes("art")||n.includes("architecture")?n+=" ancient art":n.includes("unification")?n+=" unified kingdom ancient":n.includes("dynasty")?n+=" royal dynasty ancient":n.includes("empire")?n+=" imperial power ancient":n.includes("kingdom")?n+=" ancient kingdom civilization":n.includes("apple")||n.includes("iphone")||n.includes("ipad")||n.includes("macintosh")||n.includes("macbook")?n+=" computer smartphone electronics apple-inc hardware":!n.includes("amazon")||n.includes("forest")||n.includes("river")?
1n.includes("java")||n.includes("python")||n.includes("ruby")||n.includes("script")?n+=" programming language software code":!n.includes("windows")||n.includes("house")||n.includes("building")?!n.includes("oracle")||n.includes("ancient")||n.includes("greece")?n.includes("computer")||n.includes("technology")||n.includes("computing")||n.includes("software")||n.includes("internet")?n+=" technology computing digital":n.includes("civil war")||n.includes("war")&&(n.includes("american")||n.includes("slavery")||n.includes("compromise"))?n+=" american civil war historical battlefield":n.includes("slavery")||n.includes("abolition")?n+=" historical slavery abolition american":(n.includes("viking")||n.includes("norse")||t&&(t.toLowerCase().includes("viking")||t.toLowerCase().includes("norse")))&&(n+=" norse viking age history historical culture scandinavia longship"):n+=" company software database technology":n+=" microsoft software operating-system":n+=" company office technology e-commerce",t&&t.trim().length>2){const e=t.toLowerCase();n.includes(e)||(n=`${e} ${n}`),e.includes("egypt")&&(n.includes("kingdom")||n.includes("old")||n.includes("dynasty")||n.includes("rise")||n.includes("society"))&&(n+=" ancient egypt pyramids giza pharaoh nile sphinx hieroglyphs")}return/\b(egypt|rome|roman|greek|greece|dynasty|kingdom|empire|civilization)\b/i.test(n)&&(n.includes("ancient")||n.includes("historical")||(n=`ancient ${n}`)),(!n||n.trim().length<3)&&(n="education learning"),n},getFallbackImage(e,t=""){const i=((null==e?void 0:e.toLowerCase())||"")+" "+((null==t?void 0:t.toLowerCase())||"");let s="default";i.includes("egypt")||i.includes("pharaoh")||i.includes("pyramid")?s="egypt":i.includes("ancient")||i.includes("rome")||i.includes("roman")||i.includes("greek")||i.includes("greece")?s="ancient":i.includes("history")||i.includes("historical")||i.includes("dynasty")||i.includes("empire")?s="history":i.includes("science")||i.includes("research")||i.includes("scientific")?s="science":i.includes("technology")||i.includes("computer")||i.includes("computing")||i.includes("apple")||i.includes("iphone")||i.includes("digital")||i.includes("internet")||i.includes("software")?s="technology":i.includes("education")||i.includes("learning")||i.includes("study")||i.includes("knowledge")?s="education":i.includes("fall")||i.includes("decline")||i.includes("collapse")?s="history":(i.includes("rise")||i.includes("growth")||i.includes("expansion")||i.includes("city")||i.includes("urban")||i.includes("civilization")||i.includes("culture")||i.includes("society")||i.includes("art"))&&(s="ancient");const n=this.fallbackImages[s]||this.fallbackImages.default;return n[Math.floor(Math.random()*n.length)]},clearCache(){this.cache.clear()},getCacheStats(){const e=Date.now();let t=0,i=0;for(const[s,n]of this.cache.entries())e-n.timestamp<this.cacheTimeout?t++:i++;return{total:this.cache.size,valid:t,expired:i}},isValidUrl(e){if(!e||"string"!=typeof e)return!1;try{const t=new URL(e),i=t.pathname.toLowerCase(),s=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".tiff",".tif",".jfif"].some(e=>i.includes(e)),n=["pixabay.com","wikimedia.org","wikipedia.org","cdn"].some(e=>t.hostname.includes(e));if(s||n)return!0;["image","photo","img","picture","pic"].some(e=>i.includes(e));return!0}catch(t){return!!(e.startsWith("/")||e.startsWith("./")||e.startsWith("data:image/"))}},preCacheImage(e){return c(this,null,function*(){if(!e||!e.url)return!1;if(!this.isValidUrl(e.url))return!1;try{const t=yield fetch(e.url,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{Accept:"image/*, image/svg+xml","User-Agent":"SimpleImageService/1.0"}});if(t.ok){(t.headers.get("content-type")||"").includes("svg")||e.url.toLowerCase().includes(".svg");return!0}return!1}catch(t){return!1}})},detectMusicContent(e){const t=e.toLowerCase();return["music","musical","melody","rhythm","harmony","composition","performance","concert","song","tune","note","scale","chord","tempo","beat","pitch","sound","audio","orchestra","band","ensemble","singer","vocal","instrument","piano","guitar","violin","drums","trumpet","saxophone","flute","clarinet","cello","bass","
1jazz","rock","pop","folk","classical","electronic","blues","country","reggae","symphony","sonata","concerto","opera","ballet","musical theater","recital","beatles","beatle","lennon","mccartney","harrison","starr","ringo","paul","john","george","album","single","record","recording","studio","producer","arrangement","lyrics","guitar riff","bass line","drum beat","vocal harmony","backup vocals","lead singer"].some(e=>t.includes(e))},detectHistoricalContent(e){const t=e.toLowerCase();return["history","ancient","rome","greek","egypt","medieval","renaissance","empire","republic","kingdom","dynasty","civilization","war","battle","revolution","pharaoh","emperor","king","queen","temple","ruins","artifact","manuscript"].some(e=>t.includes(e))},getCourseContext(e,t=null){return c(this,null,function*(){try{const i=yield fetch(`${u}/api/public/courses/${e}`,{method:"GET",headers:o({"Content-Type":"application/json"},t?{"X-Session-Id":t}:{}),signal:AbortSignal.timeout(5e3)});return i.ok?yield i.json():null}catch(i){}return null})},forceReplaceMusicImages(e,t,i){return c(this,arguments,function*(e,t,i,s=[],n=[]){const a=this.getCacheKey(e,t,i);return this.cache.delete(a),yield x.forceImageReplacement(e,t,i,s,n)})}},T=Object.freeze(Object.defineProperty({__proto__:null,default:C},Symbol.toStringTag,{value:"Module"}));const P=new class{constructor(){this.cache=new Map,this.metadata=new Map,this.maxSize=1e3,this.maxMemory=52428800,this.currentMemory=0,this.stats={hits:0,misses:0,sets:0,deletes:0,evictions:0,memoryUsage:0},this.startCleanupInterval()}set(e,t,i=3e5){const s=this.calculateSize(t),n=Date.now()+i;return this.ensureCapacity(s),this.cache.set(e,t),this.metadata.set(e,{expiresAt:n,size:s,createdAt:Date.now(),accessCount:0,lastAccessed:Date.now()}),this.currentMemory+=s,this.stats.sets++,this.updateStats(),!0}get(e){const t=this.metadata.get(e);return t?Date.now()>t.expiresAt?(this.delete(e),this.stats.misses++,this.updateStats(),null):(t.accessCount++,t.lastAccessed=Date.now(),this.stats.hits++,this.updateStats(),this.cache.get(e)):(this.stats.misses++,this.updateStats(),null)}delete(e){const t=this.metadata.get(e);return t&&(this.currentMemory-=t.size,this.stats.deletes++),this.cache.delete(e),this.metadata.delete(e),this.updateStats(),!0}has(e){const t=this.metadata.get(e);return!!t&&(!(Date.now()>t.expiresAt)||(this.delete(e),!1))}clear(){this.cache.clear(),this.metadata.clear(),this.currentMemory=0,this.updateStats()}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(2):0;return l(o({},this.stats),{hitRate:`${e}%`,size:this.cache.size,memoryUsage:this.formatBytes(this.currentMemory),maxMemory:this.formatBytes(this.maxMemory),memoryUsagePercent:(this.currentMemory/this.maxMemory*100).toFixed(2)})}keys(e=null){const t=Array.from(this.cache.keys());if(!e)return t;const i=new RegExp(e.replace(/\*/g,".*"));return t.filter(e=>i.test(e))}entries(){const e=[];for(const[t,i]of this.cache.entries()){const s=this.metadata.get(t);s&&Date.now()<=s.expiresAt&&e.push({key:t,value:i,metadata:o({},s)})}return e}mset(e,t=3e5){const i=[];for(const[s,n]of e)i.push(this.set(s,n,t));return i}mget(e){const t=[];for(const i of e)t.push(this.get(i));return t}incr(e,t=1){const i=(this.get(e)||0)+t;return this.set(e,i),i}decr(e,t=1){return this.incr(e,-t)}expire(e,t){const i=this.metadata.get(e);return!!i&&(i.expiresAt=Date.now()+t,!0)}ttl(e){const t=this.metadata.get(e);return t?Date.now()>t.expiresAt?-1:Math.max(0,t.expiresAt-Date.now()):-2}ensureCapacity(e){if(this.currentMemory+e<=this.maxMemory&&this.cache.size<this.maxSize)return;const t=this.getItemsToEvict();for(const i of t)if(this.delete(i),this.stats.evictions++,this.currentMemory+e<=.8*this.maxMemory&&this.cache.size<.8*this.maxSize)break}getItemsToEvict(){const e=Array.from(this.metadata.entries()).map(([e,t])=>o({key:e},t));return e.sort((e,t)=>{const i=Date.now(),s=i>e.expiresAt,n=i>t.expiresAt;if(s&&!n)return-1;if(!s&&n)return 1;return.7*e.accessCount+.3*(i-e.lastAccessed)-(.7*t.accessCount+.3*(i-t.lastAccessed))}),e.map(e=>e.key)}calculateSize(e){if(null==e)return 8;if("string"==typeof e)return 2*e.length;if("number"==typeof e)return 8;if("boolean"==typeof e)return 4;if(e instanceof ArrayBuffer)return e.byteLength;if(e instanceof Blob)return e.size;if("object"==typeof e)try{return 2*JSON.stringify(e).length}catch(t){return 1024}return 8}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["Bytes","KB","MB","GB"][t]}startCleanupInterval(){setInterval(()=>{this.cleanup()},6e4)}cleanup(){const e=Date.now(),t=[];for(const[i,s]of this.metadata.entries())e>s.expiresAt&&t.push(i);for(const i of t)this.delete(i);t.length}updateStats(){this.stats.memoryUsage=this.currentMemory}resetStats(){this.stats={hits:0,misses:0,sets:0,deletes:0,evictions:0,memoryUsage:0}}};const I=new class{constructor(){this.preloadedImages=new Set,this.maxConcurrent=3,this.activePreloads=0,this.cache=P}preloadImage(e,t="low"){return c(this,null,function*(){if(!e)return!1;const t=`preload:${e}`;if(this.cache.get(t))return!0;
1if(this.preloadedImages.has(e))return!0;for(;this.activePreloads>=this.maxConcurrent;)yield new Promise(e=>setTimeout(e,50));this.activePreloads++;try{const i=yield this._preloadSingleImage(e);return i&&(this.preloadedImages.add(e),this.cache.set(t,{success:!0,timestamp:Date.now()},6e5)),i}finally{this.activePreloads--}})}_preloadSingleImage(e){return c(this,null,function*(){return new Promise(t=>{const i=new Image,s=(Date.now(),setTimeout(()=>{t(!1)},8e3));i.onload=()=>{clearTimeout(s);Date.now();t(!0)},i.onerror=()=>{clearTimeout(s),t(!1)},i.src=e})})}isPreloaded(e){return this.preloadedImages.has(e)}clearPreloaded(){this.preloadedImages.clear()}getStats(){const e=this.cache.getStats();return{preloadedCount:this.preloadedImages.size,activePreloads:this.activePreloads,maxConcurrent:this.maxConcurrent,cacheStats:e}}getCacheStats(){return this.cache.getStats()}};const j=new class{constructor(){this.preloadCache=new Map}preloadLessonImage(e,t,i){return c(this,null,function*(){var t,s;if(!(null==e?void 0:e.title)||!i)return null;const n=(null==(t=null==e?void 0:e.image)?void 0:t.imageUrl)||(null==(s=null==e?void 0:e.image)?void 0:s.url);if(n){try{yield I.preloadImage(n,"high")}catch(r){}return null}const a=`${i}_${e.id}_${e.title}`;if(this.preloadCache.has(a))return this.preloadCache.get(a);try{const t=yield C.search(e.title,i,e.id);return t&&t.url&&(yield I.preloadImage(t.url,"high")),this.preloadCache.set(a,t),t}catch(o){return null}})}getPreloadedImage(e,t,i){for(const[s,n]of this.preloadCache.entries())if(s.includes(e)||s.includes(t))return n;return null}clearCache(){this.preloadCache.clear()}};const z=new class{constructor(){this.slowImages=new Map,this.performanceData=new Map,this.renderTimes=new Map,this.slowThreshold=3e3,this.criticalThreshold=5e3,this.maxSlowImages=50,this.observer=null,this.renderObserver=null,this.longTaskThreshold=300,this.monitoringEnabled=!0,this.errorCount=0,this.maxErrors=10,this.initPerformanceObserver()}initPerformanceObserver(){if("PerformanceObserver"in window)try{this.observer=new PerformanceObserver(e=>{for(const t of e.getEntries())"resource"===t.entryType&&"img"===t.initiatorType&&this.trackImageLoad(t)}),this.observer.observe({entryTypes:["resource"]}),this.renderObserver=new PerformanceObserver(e=>{if(this.monitoringEnabled)for(const t of e.getEntries())t.duration>this.longTaskThreshold&&this.trackLongTask(t)}),this.renderObserver.observe({entryTypes:["longtask"]})}catch(e){}}trackImageLoad(e){if(!this.monitoringEnabled)return;const t=e.duration,i=e.name;"requestIdleCallback"in window?requestIdleCallback(()=>{this.processImageLoad(e,t,i)},{timeout:3e3}):setTimeout(()=>{this.processImageLoad(e,t,i)},200)}processImageLoad(e,t,i){if(this.performanceData.set(i,{loadTime:t,timestamp:Date.now(),size:e.transferSize||0}),t>this.slowThreshold&&(this.slowImages.set(i,{loadTime:t,timestamp:Date.now(),size:e.transferSize||0,domain:new URL(i).hostname}),this.criticalThreshold,this.slowImages.size>this.maxSlowImages)){const e=Array.from(this.slowImages.keys())[0];this.slowImages.delete(e)}}trackLongTask(e){const t=e.duration;t>this.longTaskThreshold&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.processLongTask(e,t)},{timeout:5e3}):setTimeout(()=>{this.processLongTask(e,t)},500))}processLongTask(e,t){try{t>500&&this.errorCount++,this.renderTimes.set(e.name||"unknown",{duration:t,timestamp:Date.now()}),this.errorCount>=this.maxErrors&&this.disableMonitoring()}catch(i){this.errorCount++,this.errorCount>=this.maxErrors&&this.disableMonitoring()}}trackRenderTime(e,t){"requestIdleCallback"in window?requestIdleCallback(()=>{this.renderTimes.set(e,{renderTime:t,timestamp:Date.now()})},{timeout:1e3}):setTimeout(()=>{this.renderTimes.set(e,{renderTime:t,timestamp:Date.now()})},0)}trackManualImageLoad(e,t,i=0){t>this.slowThreshold&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.slowImages.set(e,{loadTime:t,timestamp:Date.now(),size:i,domain:new URL(e).hostname,manual:!0})},{timeout:3e3}):setTimeout(()=>{this.slowImages.set(e,{loadTime:t,timestamp:Date.now(),size:i,domain:new URL(e).hostname,manual:!0})},200))}disableMonitoring(){this.monitoringEnabled=!1}enableMonitoring(){this.monitoringEnabled=!0}setLongTaskThreshold(e){this.longTaskThreshold=e}getSlowImages(){return Array.from(this.slowImages.entries()).map(([e,t])=>o({url:e},t))}getPerformanceStats(){const e=Array.from(this.performanceData.values()).map(e=>e.loadTime),t=Array.from(this.renderTimes.values()).map(e=>e.duration||e.renderTime);if(0===e.length)return{totalImages:0,averageLoadTime:0,slowImages:0,critical
1SlowImages:0,averageRenderTime:0,slowRenders:0};const i=e.reduce((e,t)=>e+t,0)/e.length,s=e.filter(e=>e>this.slowThreshold).length,n=e.filter(e=>e>this.criticalThreshold).length,a=t.length>0?t.reduce((e,t)=>e+t,0)/t.length:0,r=t.filter(e=>e>1e3).length;return{totalImages:e.length,averageLoadTime:Math.round(i),slowImages:s,criticalSlowImages:n,slowPercentage:Math.round(s/e.length*100),averageRenderTime:Math.round(a),slowRenders:r,totalRenders:t.length}}getOptimizationSuggestions(){const e=[],t=this.getPerformanceStats();t.slowPercentage>20&&e.push("Consider implementing image CDN or compression"),t.criticalSlowImages>0&&e.push("Critical slow images detected - review image sources and proxy settings"),t.averageRenderTime>500&&e.push("Slow render times detected - consider deferred rendering and requestIdleCallback"),t.slowRenders>0&&e.push("Render-blocking operations detected - break rendering into chunks");const i=this.getSlowImages(),s={};i.forEach(e=>{s[e.domain]=(s[e.domain]||0)+1});const n=Object.entries(s).filter(([e,t])=>t>3).map(([e])=>e);return n.length>0&&e.push(`Slow images from domains: ${n.join(", ")}`),e}generatePerformanceReport(){const e=this.getPerformanceStats(),t=this.getOptimizationSuggestions(),i=this.getSlowImages().slice(0,10);return{timestamp:(new Date).toISOString(),stats:e,suggestions:t,slowImages:i,renderTimes:Array.from(this.renderTimes.entries()).map(([e,t])=>o({component:e},t))}}clearData(){this.slowImages.clear(),this.performanceData.clear(),this.renderTimes.clear()}destroy(){this.observer&&this.observer.disconnect(),this.renderObserver&&this.renderObserver.disconnect()}};var L=Object.defineProperty,_=Object.defineProperties,N=Object.getOwnPropertyDescriptors,R=Object.getOwnPropertySymbols,M=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,A=(e,t,i)=>t in e?L(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,O=(e,t)=>{for(var i in t||(t={}))M.call(t,i)&&A(e,i,t[i]);if(R)for(var i of R(t))$.call(t,i)&&A(e,i,t[i]);return e},U=(e,t)=>_(e,N(t));const W=e=>{var t=e,{src:i,alt:s="",className:n="",style:a={},lazy:r=!0,preload:o=!1,priority:l=!1,placeholder:c=null,timeout:h=1e4}=t,d=((e,t)=>{var i={};for(var s in e)M.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&R)for(var s of R(e))t.indexOf(s)<0&&$.call(e,s)&&(i[s]=e[s]);return i})(t,["src","alt","className","style","lazy","preload","priority","placeholder","timeout"]);const m=y.useMemo(()=>{if(!i)return i;if(i.startsWith("http://")||i.startsWith("https://"))return i;if(i.startsWith("data:"))return i;const e=u||"";if(e&&i.startsWith(e))return i;return`${e}${i.startsWith("/")?i:`/${i}`}`},[i]),[p,g]=y.useState(!1),[f,w]=y.useState(!1),[k,v]=y.useState(!r||o),[x,S]=y.useState(null),[C,T]=y.useState(null),[P,j]=y.useState(!1),[L,_]=y.useState(!1);y.useEffect(()=>{g(!1),w(!1),j(!1),S(null),_(!1)},[m]);const N=y.useRef(null),A=y.useRef(null);y.useRef(null);const W=y.useRef(null),E=k||o,D=y.useMemo(()=>[800],[]),F=y.useCallback((e,t)=>{if(!e||!k)return"";if(!e.includes("/api/image/"))return"";const i=e.replace("/api/image/enhanced","/api/image/fast");return D.map(e=>`${i} ${e}w`).join(", ")},[k,D]),q=y.useCallback(e=>{return t=null,i=null,s=function*(){if(e&&!x&&!p)try{const t=e.replace("/api/image/enhanced","/api/image/fast");S(t)}catch(t){}},new Promise((e,n)=>{var a=e=>{try{o(s.next(e))}catch(t){n(t)}},r=e=>{try{o(s.throw(e))}catch(t){n(t)}},o=t=>t.done?e(t.value):Promise.resolve(t.value).then(a,r);o((s=s.apply(t,i)).next())});var t,i,s},[x,p]);y.useEffect(()=>{if(!r||o)return void v(!0);const e=new IntersectionObserver(([t])=>{t.isIntersecting&&(v(!0),e.disconnect())},{rootMargin:"200px 0px 200px 0px",threshold:.05});return N.current&&e.observe(N.current),()=>{e&&e.disconnect&&e.disconnect()}},[r,o]),y.useEffect(()=>{k&&m&&!x&&!p&&q(m)},[k,m,x,p,q]);const B=y.useCallback(e=>{const t=e.target,i=parseInt(t.dataset.startTime||"0"),s=Date.now()-i;W.current&&(clearTimeout(W.current),W.current=null),g(!0),w(!1),j(!1);"requestIdleCallback"in window?requestIdleCallback(()=>{const e=t.naturalWidth*t.naturalHeight||0;z.trackManualImageLoad(m,s,e)},{timeout:1e3}):setTimeout(()=>
1{const e=t.naturalWidth*t.naturalHeight||0;z.trackManualImageLoad(m,s,e)},0)},[m]);y.useEffect(()=>{E&&A.current&&(A.current.dataset.startTime=Date.now().toString(),z.trackManualImageLoad(m,0,0),A.current.complete&&A.current.naturalWidth>0&&B({target:A.current}))},[E,m,B]);const V=y.useCallback(e=>{if(w(!0),W.current&&(clearTimeout(W.current),W.current=null),"true"!==e.target.dataset.fallbackTried){if(m&&m.includes("/api/image/"))try{const t=m.match(/url=([^&]+)/);if(t){const i=decodeURIComponent(t[1]);return e.target.dataset.fallbackTried="true",_(!0),i.includes("wikimedia.org")?void(e.target.src=i):void(e.target.src=i)}}catch(t){}j(!0)}else j(!0)},[m]);y.useEffect(()=>{if(E&&m&&!p&&!f){const e=500;W.current=setTimeout(()=>{j(!0)},h+e)}return()=>{W.current&&(clearTimeout(W.current),W.current=null)}},[E,m,p,f,h]),y.useEffect(()=>{if(!E||p||!m)return;l&&A.current?I.preloadImage(m,"high"):"requestIdleCallback"in window?requestIdleCallback(()=>{I.preloadImage(m,"low")},{timeout:2e3}):setTimeout(()=>{I.preloadImage(m,"low")},100)},[l,m,E,p]);const H=y.useMemo(()=>E&&m?F(m,"webp"):"",[E,m,F]);return b.jsxs(b.Fragment,{children:[P&&b.jsx("div",U(O({className:`image-fallback ${n}`,style:U(O({},a),{backgroundImage:"url(https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png)",backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",minHeight:"200px"})},d),{children:b.jsx("span",{style:{color:"#6b7280",fontSize:"14px"},children:"Image unavailable"})})),b.jsxs("picture",{ref:N,className:P?"hidden-picture":n,style:P?{display:"none"}:void 0,children:[H&&!L&&b.jsx("source",{type:"image/webp",srcSet:H,sizes:"(max-width: 768px) 100vw, 800px"}),b.jsx("img",O({ref:A,src:m,alt:s,className:"image-component "+(p?"loaded":"loading"),loading:l?"eager":"lazy",fetchPriority:l?"high":"low",style:O(U(O({},a),{opacity:p?1:.7,transition:"opacity 0.3s ease-in-out"}),p?{}:{filter:"blur(1px)"}),onLoad:B,onError:V},d))]})]})};W.propTypes={src:d.string.isRequired,alt:d.string,className:d.string,style:d.object,lazy:d.bool,preload:d.bool,priority:d.bool,placeholder:d.string,timeout:d.number};const E=e=>{const t=String(e||"").trim();return t?/^https:\/\//i.test(t)?t:t.startsWith("/api/")?u?`${u}${t}`:t:"":""};function D({video:e,lessonTitle:t,videoRef:i,onPlay:s}){var n;const[a,r]=y.useState(""),o=y.useMemo(()=>E(null==e?void 0:e.url),[null==e?void 0:e.url]),l=y.useMemo(()=>E(null==e?void 0:e.posterUrl),[null==e?void 0:e.posterUrl]),c=y.useMemo(()=>E(null==e?void 0:e.captionsUrl),[null==e?void 0:e.captionsUrl]);if(!e||"ready"!==e.status||!o)return null;const u=Boolean(a)&&a===o,h=String(e.title||`${t||"Lesson"} visual demonstration`).trim(),d="verified"===(null==(n=e.narration)?void 0:n.status)?String(e.narration.text||"").trim():"";return b.jsxs("figure",{className:"mx-auto mb-8 max-w-4xl overflow-hidden rounded-xl border border-slate-200 bg-slate-950 shadow-sm dark:border-slate-700",children:[u?b.jsx("div",{className:"flex min-h-48 items-center justify-center bg-slate-100 px-6 py-10 text-center text-sm text-slate-600 dark:bg-slate-800 dark:text-slate-300",children:"This visual demonstration could not be played. The written lesson remains available below."}):b.jsxs("video",{ref:i,className:"block aspect-video w-full bg-black object-contain",controls:!0,controlsList:"nodownload noremoteplayback",disablePictureInPicture:!0,disableRemotePlayback:!0,playsInline:!0,preload:"metadata",poster:l||void 0,"aria-label":h,onContextMenu:e=>e.preventDefault(),onError:()=>r(o),onPlay:s,children:[b.jsx("source",{src:o,type:e.mimeType||"video/mp4"}),c?b.jsx("track",{default:!0,kind:"captions",src:c,srcLang:e.captionsLanguage||"en",label:e.captionsLabel||"English"}):null,"Your browser does not support embedded video."]},o),b.jsxs("figcaption",{className:"bg-white px-4 py-3 text-sm text-slate-600 dark:bg-slate-900 dark:text-slate-300",children:[b.jsx("div",{className:"font-medium text-slate-800 dark:text-slate-100",children:h}),b.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs",children:[b.jsx("span",{children:e.disclosure||"AI-generated visual demonstration"}),d?b.jsxs(b.Fragment,{children:[b.jsx("span",{"aria-hidden":"true",children:"â¢"}),b.jsx("span",{children:"Includes lesson-grounded narration â reverse-transcribed and verified before publishing."})]}):null]}),d?b.jsxs("details",{className:"mt-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs dar
1k:border-slate-700 dark:bg-slate-800/70",children:[b.jsx("summary",{className:"cursor-pointer font-semibold text-slate-700 dark:text-slate-200",children:"Narration transcript"}),b.jsx("p",{className:"mt-2 leading-5 text-slate-600 dark:text-slate-300",children:d})]}):null]})]})}D.propTypes={video:d.shape({status:d.string,url:d.string,posterUrl:d.string,captionsUrl:d.string,captionsLanguage:d.string,captionsLabel:d.string,mimeType:d.string,title:d.string,disclosure:d.string,providerAttribution:d.string,providerUrl:d.string,narration:d.shape({status:d.string,text:d.string,language:d.string,voice:d.string,engine:d.string,verification:d.string,wordErrorRate:d.number})}),lessonTitle:d.string,videoRef:d.shape({current:d.any}),onPlay:d.func},D.defaultProps={video:null,lessonTitle:"",videoRef:null,onPlay:void 0};const F={"onb-m1-l1-welcome":{imageUrl:"/images/onboarding/01-welcome-dashboard.gif",imageTitle:"A tour of your Discourse AI dashboard"},"onb-m1-l2-first-course":{imageUrl:"/images/onboarding/02-create-course.gif",imageTitle:"Generating your first course"},"onb-m2-l1-modules-lessons":{imageUrl:"/images/onboarding/03-lesson-navigation.gif",imageTitle:"Navigating modules and lessons"},"onb-m2-l2-tools-account":{imageUrl:"/images/onboarding/04-quiz-flashcards.gif",imageTitle:"Quizzes and flashcards in action"}};function q(e){var t,i,s,n;const a=(null==e?void 0:e.id)?F[e.id]:null;if(a)return a;const r=(null==(t=null==e?void 0:e.image)?void 0:t.imageUrl)||(null==(i=null==e?void 0:e.image)?void 0:i.url)||"";return"string"==typeof r&&r.includes("/images/onboarding/")?{imageUrl:r,imageTitle:(null==(s=null==e?void 0:e.image)?void 0:s.imageTitle)||(null==(n=null==e?void 0:e.image)?void 0:n.title)||""}:null}var B,V,H={},G={};const K=w(function(){if(V)return H;V=1,Object.defineProperty(H,"__esModule",{value:!0}),H.default=void 0;var e=function(){if(B)return G;B=1,Object.defineProperty(G,"__esModule",{value:!0}),G.trim=G.isObject=G.isNil=G.isNan=G.size=G.isString=G.validateLocale=G.splitSentences=void 0,G.splitSentences=function(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").replace(/\.+/g,".|").replace(/\?/g,"?|").replace(/\!/g,"!|").split("|").map(function(e){return i(e)}).filter(Boolean)};var e=/^(?:(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)|(art-lojban|cel-gaulish|n
1o-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang))$|^((?:[a-z]{2,3}(?:(?:-[a-z]{3}){1,3})?)|[a-z]{4}|[a-z]{5,8})(?:-([a-z]{4}))?(?:-([a-z]{2}|\d{3}))?((?:-(?:[\da-z]{5,8}|\d[\da-z]{3}))*)?((?:-[\da-wy-z](?:-[\da-z]{2,8})+)*)?(-x(?:-[\da-z]{1,8})+)?$|^(x(?:-[\da-z]{1,8})+)$/i;G.validateLocale=function(t){return"string"==typeof t&&e.test(t)};var t=function(e){return"string"==typeof e||e instanceof String};G.isString=t,G.size=function(e){return e&&Array.isArray(e)&&e.length?e.length:0},G.isNan=function(e){return"number"==typeof e&&isNaN(e)},G.isNil=function(e){return null==e},G.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)};var i=function(e){return t(e)?e.trim():""};return G.trim=i,G}();function t(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}(e.prototype,t),e}var i=function(){function i(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,i),this.browserSupport="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,this.synthesisVoice=null}return t(i,[{key:"init",value:function(){var t=this,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Promise(function(s,n){t.browserSupport||n("Your browser does not support Speech Synthesis");var a=(0,e.isNil)(i.listeners)?{}:i.listeners,r=!!(0,e.isNil)(i.splitSentences)||i.splitSentences,o=(0,e.isNil)(i.lang)?void 0:i.lang,l=(0,e.isNil)(i.volume)?1:i.volume,c=(0,e.isNil)(i.rate)?1:i.rate,u=(0,e.isNil)(i.pitch)?1:i.pitch,h=(0,e.isNil)(i.voice)?void 0:i.voice;Object.keys(a).forEach(function(e){var t=a[e];"onvoiceschanged"!==e&&(speechSynthesis[e]=function(e){t&&t(e)})}),t._loadVoices().then(function(i){a.onvoiceschanged&&a.onvoiceschanged(i),!(0,e.isNil)(o)&&t.setLanguage(o),!(0,e.isNil)(h)&&t.setVoice(h),!(0,e.isNil)(l)&&t.setVolume(l),!(0,e.isNil)(c)&&t.setRate(c),!(0,e.isNil)(u)&&t.setPitch(u),!(0,e.isNil)(r)&&t.setSplitSentences(r),s({voices:i,lang:t.lang,voice:t.voice,volume:t.volume,rate:t.rate,pitch:t.pitch,splitSentences:t.splitSentences,browserSupport:t.browserSupport})}).catch(function(e){n(e)})})}},{key:"_fetchVoices",value:function(){return new Promise(function(t,i){setTimeout(function(){var s=speechSynthesis.getVoices();return(0,e.size)(s)>0?t(s):i("Could not fetch voices")},100)})}},{key:"_loadVoices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._fetchVoices().catch(function(i){if(0===t)throw i;return e._loadVoices(t-1)})}},{key:"hasBrowserSupport",value:function(){return this.browserSupport}},{key:"setVoice",value:function(t){var i,s=speechSynthesis.getVoices();if((0,e.isString)(t)&&(i=s.find(function(e){return e.name===t})),(0,e.isObject)(t)&&(i=t),!i)throw"Error setting voice. The voice you passed is not valid or the voices have not been loaded yet.";this.synthesisVoice=i}},{key:"setLanguage",value:function(t){if(t=t.replace("_","-"),!(0,e.validateLocale)(t))throw"Error setting language. Please verify your locale is BCP47 format (http://schneegans.de/lv/?tags=es-FR&format=text)";this.lang=t}},{key:"setVolume",value:function(t){if(t=parseFloat(t),!(!(0,e.isNan)(t)&&t>=0&&t<=1))throw"Error setting volume. Please verify your volume value is a number between 0 and 1.";this.volume=t}},{key:"setRate",value:function(t){if(t=parseFloat(t),!(!(0,e.isNan)(t)&&t>=0&&t<=10))throw"Error setting rate. Please verify your volume value is a number between 0 and 10.";this.rate=t}},{key:"setPitch",value:function(t){if(t=parseFloat(t),!(!(0,e.isNan)(t)&&t>=0&&t<=2))throw"Error setting pitch. Please verify your pitch value is a number between 0 and 2.";this.pitch=t}},{key:"setSplitSentences",value:function(e){this.splitSentences=e}},{key:"speak",value:function(t){var i=this;return new Promise(function(s,n){var a=t.text,r=t.listeners,o=void 0===r?{}:r,l=t.queue,c=void 0===l||l,u=(0,e.trim)(a);(0,e.isNil)(u)&&s(),!c&&i.cancel();var h=[],d=i.splitSentences?(0,e.splitSentences)(u):[u];d.forEach(function(t,a){var r=a===(0,e.size)(d)-1,l=new SpeechSynthesisUtterance;i.synthesisVoice&&(l.voice=i.synthesisVoice),i.lang&&(l.lang=i.lang),i.volume&&(l.volume=i.volume),i.rate&&(l.rate=i.rate),i.pitch&&(l.pitch=i.pitch),l.text=t,Object.keys(o).forEac
1h(function(e){var t=o[e];l[e]=function(i){t&&t(i),"onerror"===e&&n({utterances:h,lastUtterance:l,error:i}),"onend"===e&&r&&s({utterances:h,lastUtterance:l})}}),h.push(l),speechSynthesis.speak(l)})})}},{key:"pending",value:function(){return speechSynthesis.pending}},{key:"paused",value:function(){return speechSynthesis.paused}},{key:"speaking",value:function(){return speechSynthesis.speaking}},{key:"pause",value:function(){speechSynthesis.pause()}},{key:"resume",value:function(){speechSynthesis.resume()}},{key:"cancel",value:function(){speechSynthesis.cancel()}}]),i}();return H.default=i,H}());let J=null;if("undefined"!=typeof window&&m)try{const e=m.getPlatform();"android"===e&&p(()=>import("@capacitor-community/text-to-speech"),[]).then(e=>{J=e.TextToSpeech}).catch(e=>{})}catch(Ue){}const Q="voice_unavailable",Y="network",Z="interrupted",X="unknown",ee=e=>{var t,i,s;return!!(e&&e.reason&&(e.reason.utterances||e.reason.lastUtterance||e.reason.error||(null==(t=e.reason.message)?void 0:t.includes("speech"))||(null==(i=e.reason.message)?void 0:i.includes("TTS"))||(null==(s=e.reason.message)?void 0:s.includes("utterance"))))&&(e.preventDefault(),!0)};"undefined"!=typeof window&&(window.addEventListener("unhandledrejection",ee),window.addEventListener("error",e=>{var t,i;return!(!e.error||!(e.error.utterances||e.error.lastUtterance||e.error.error||(null==(t=e.error.message)?void 0:t.includes("speech"))||(null==(i=e.error.message)?void 0:i.includes("TTS"))))&&(e.preventDefault(),!0)}));class te{constructor(e="default"){this.serviceType=e,this.serviceId=`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.speech=new K,this.isInitialized=!1,this.isPlaying=!1,this.isPaused=!1,this.currentText="",this.currentLessonId=null,this.fullText="",this.errorCount=0,this.maxRetries=3,this.initializationAttempts=0,this.maxInitAttempts=3,this.isRetrying=!1,this.lastStartTime=0,this.speakTimeout=null,this.finishedNormally=!1,this.wasManuallyPaused=!1,this.isStopped=!1,this.wasManuallyStopped=!1,this.onCompleteCallback=null,this.pausePosition=0,this.pauseTime=0,this.totalSpokenTime=0,this.speakingStartTime=0,this.browserSupport=this.checkBrowserSupport(),this.isWindowsPackagedRuntime=!1;try{if("undefined"!=typeof window&&window.location&&window.location.protocol){const e=window.location.protocol;this.isWindowsPackagedRuntime="ms-appx-web:"===e||"ms-appx:"===e||"appx:"===e||"app:"===e}}catch(t){this.isWindowsPackagedRuntime=!1}this.useNativeTTS=!1,this.audioContext=null,this.initAudioContext(),this.initSpeech(),this.checkNativeTTS().then(()=>{this.useNativeTTS})}checkNativeTTS(){return c(this,null,function*(){const e=m?m.getPlatform():"web";if(e&&"android"===e.toLowerCase()){if(void 0!==m&&m.Plugins){Object.keys(m.Plugins);if(m.Plugins.NativeTTS&&(J=m.Plugins.NativeTTS),!J&&m.Plugins.TextToSpeech&&(J=m.Plugins.TextToSpeech),!J)try{const e=yield p(()=>import("@capacitor-community/text-to-speech"),[]);J=e.TextToSpeech}catch(Ue){}}if(!J||"function"!=typeof J.speak&&"object"!=typeof J.speak)this.useNativeTTS=!1;else{this.useNativeTTS=!0;try{if(m.Plugins.NativeTTS&&J===m.Plugins.NativeTTS&&"function"==typeof J.getStatus){const e=yield J.getStatus();e&&e.isInitialized&&(this.isInitialized=!0)}}catch(t){}}}else this.useNativeTTS=!1})}checkBrowserSupport(){const e={speechSynthesis:"undefined"!=typeof window&&"speechSynthesis"in window,speechSynthesisUtterance:"undefined"!=typeof window&&"SpeechSynthesisUtterance"in window,voices:!1,isCapacitor:!1,isAndroid:!1,isIOS:!1};if(m){e.isCapacitor=!0;const t=m.getPlatform();e.isAndroid=t&&"android"===t.toLowerCase(),e.isIOS="ios"===t}if(e.speechSynthesis)try{const t=window.speechSynthesis.getVoices();e.voices=t&&t.length>0}catch(t){}return e}initAudioContext(){try{"undefined"!=typeof AudioContext&&(this.audioContext=new AudioContext)}catch(Ue){}}resumeAudioContext(){return c(this,null,function*(){if(this.audioContext&&"suspended"===this.audioContext.state)try{yield this.audioContext.resume()}catch(Ue){}})}initSpeech(){return c(this,null,function*(){if(this.useNativeTTS)this.isInitialized=!0;else if(!(this.initializationAttempts>=this.maxInitAttempts)){this.initializationAttempts++;try{if(!this.browserSupport.speechSynthesis)throw new Error("Speech synthesis not supported in this browser");yield this.speech.init({volume:1,lang:"en-US",rate:.9,pitch:1,voice:"Google UK English Female",splitSentences:!1,listeners:{onvoiceschanged:()=>{},onend:()=>{this.isStopped||(this.isPlaying=!1,this.isPaused=!1,this.finishedNormally=!0),this.stopHeartbeat()},onerror:e=>{this.isPlaying=!1},onpause:()=>{this.isPaused=!0,this.isPlaying=!1},onresume:()=>{this.isStopped||(this.isPaused=!1,this.isPlaying=!0,this.startHeartbeat())},onstart:()=>{this.isStopped||(this.isPlaying=!0,this.isPaused=!1)}}}),this.isInitialized=!0,this.initializationAttempts=0}catch(Ue){if(this.isInitialized=!1,this.initializationAttempts<this.maxInitAttempts)try{yield this.speech.init(),this.isInitialized=!0,this.initializationAttempts=0}catch(e){}}}})}waitForVoices(){return c(this,null,function*(){return new Promise(e=>
1{let t=null,i=null,s=0;const n=()=>{t&&(clearTimeout(t),t=null),i&&(clearInterval(i),i=null);try{window.speechSynthesis.removeEventListener("voiceschanged",r)}catch(Ue){}},a=()=>{s++;try{if(!window.speechSynthesis)return!1;const t=window.speechSynthesis.getVoices();if(t&&t.length>0)return n(),e(t),!0}catch(Ue){return!1}return!1};if(a())return;i=setInterval(()=>{(a()||s>=50)&&(clearInterval(i),i=null)},500);const r=()=>{a()&&n()};try{window.speechSynthesis.addEventListener("voiceschanged",r)}catch(Ue){}t=setTimeout(()=>{n();try{const t=window.speechSynthesis.getVoices();e(t||[])}catch(Ue){e([])}},1e4)})})}getInitConfig(){const e={volume:1,splitSentences:!1,listeners:{onvoiceschanged:e=>{e&&e.length},onstart:()=>{this.isStopped||(this.wasManuallyPaused?(this.isPlaying=!1,this.isPaused=!0):(this.isPlaying=!0,this.isPaused=!1),this.speakingStartTime=Date.now(),this.lastStartTime=Date.now(),this.startHeartbeat())},onend:()=>{this.isStopped||(this.isPlaying=!1,this.isPaused=!1,this.finishedNormally=!0)},onpause:()=>{this.isPaused=!0,this.isPlaying=!1,this.stopHeartbeat()},onresume:()=>{this.isStopped||(this.isPaused=!1,this.isPlaying=!0)},onerror:e=>{this.stopHeartbeat(),this.handleSpeechError(e)}}};switch(this.initializationAttempts){case 1:return this.isWindowsPackagedRuntime?l(o({},e),{lang:"en-US",rate:1.05,pitch:1,voice:this.selectBestVoice(["Microsoft","en-US","en-GB","en"])}):l(o({},e),{lang:"en-GB",rate:.9,pitch:1,voice:this.selectBestVoice(["Google UK English Female","en-GB","en"])});case 2:return l(o({},e),{lang:"en-US",rate:1,pitch:1,voice:this.selectBestVoice(["Google US English","en-US","en"])});default:return l(o({},e),{lang:"en",rate:1,pitch:1,voice:this.selectBestVoice(["en"]),volume:.8})}}selectBestVoice(e){try{const t=window.speechSynthesis.getVoices();if(!t||0===t.length)return null;for(const s of e){const e=t.find(e=>e.name.includes(s)||e.lang.startsWith(s)||e.lang===s);if(e)return e.name}const i=t.find(e=>e.lang.startsWith("en"));return i?i.name:t[0].name}catch(Ue){return null}}handleSpeechError(e){switch(this.categorizeError(e)){case Z:break;case Q:this.isInitialized=!1,this.initSpeech();break;default:this.errorCount++}}categorizeError(e){const t=e.error||e;return"interrupted"===t||"canceled"===t?Z:"not-allowed"===t||"network"===t?Y:"voice-not-found"===t||"voice-unavailable"===t?Q:X}cleanTextForTTS(e){return e?e.replace(/<[^>]*>/g,"").replace(/&[a-zA-Z0-9#]+;/g,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`(.*?)`/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1").replace(/!\[(.*?)\]\(.*?\)/g,"$1").replace(/<strong>(.*?)<\/strong>/gi,"$1").replace(/<b>(.*?)<\/b>/gi,"$1").replace(/<em>(.*?)<\/em>/gi,"$1").replace(/<i>(.*?)<\/i>/gi,"$1").replace(/<code>(.*?)<\/code>/gi,"$1").replace(/<pre>(.*?)<\/pre>/gi,"$1").replace(/<p[^>]*>(.*?)<\/p>/gi,"$1").replace(/<div[^>]*>(.*?)<\/div>/gi,"$1").replace(/<span[^>]*>(.*?)<\/span>/gi,"$1").replace(/^#{1,6}\s+(.*?)$/gm,"$1. ").replace(/^[\s]*[*+-]\s+(.*?)$/gm,"$1. ").replace(/^[\s]*\d+\.\s+(.*?)$/gm,"$1. ").replace(/^>\s+(.*?)$/gm,"$1. ").replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/\n{3,}/g,"\n\n").replace(/\s+/g," ").replace(/\s*\.\s*/g,". ").replace(/\s*,\s*/g,", ").replace(/\s*:\s*/g,": ").replace(/\s*;\s*/g,"; ").replace(/\s*!\s*/g,"! ").replace(/\s*\?\s*/g,"? ").replace(/^[pP]\s*/,"").replace(/[^\w\s.,!?;:()'\-]/g,"").trim():""}extractLessonText(e){if(!e)return"";let t="";if("string"==typeof e)t=e;else{if("object"!=typeof e)return"";{const i=[];if(e.main_content&&i.push(e.main_content),e.content&&i.push(e.content),e.text&&i.push(e.text),e.conclusion&&i.push(e.conclusion),0===i.length){const t=Object.keys(e).filter(t=>"string"==typeof e[t]&&e[t].trim().length>0&&(t.includes("text")||t.includes("content")||t.includes("body")||t.includes("description")));if(t.length>0)t.forEach(t=>i.push(e[t]));else try{const t=JSON.stringify(e);t.length>50&&i.push(t)}catch(s){}}t=i.map(e=>"string"==typeof e?e.replace(/^INTRODUCTION:\s*/i,""):e).join(" ")}}if(!t||0===t.trim().length)return"";const i=this.cleanTextForTTS(t);return!i||i.trim().length<10?t.trim():i}readLesson(e,t){return c(this,null,function*(){if(this.isStopped)return!1;if(this.useNativeTTS)this.isInitialized||(yield this.initSpeech());else{if(!this.browserSupport.speechSynthesis)return!1;if(!this.isInitialized&&(yield this.initSpeech(),!this.isInitialized))return!1}if(this.isPlaying)return!1;if(!e)return!1;if(!e.content)return!1;const i=this.extractLessonText(e.content);if(!i)return!1;if("string"!=typeof i)return!1;if(!i.trim())return!1;if(i.trim().length<10)return!1;try{return this.currentText=i,this.currentLessonId=t,this.fullText=i,this.errorCount=0,this.pausePosition=0,this.pauseTime=0,this.totalSpokenTime=0,this.speakingStartTime=0,this.finishedNormally=!1,this.wasManuallyPaused=!1,this.currentLessonTitle=e.title,this.currentChunkIndex=0,this.isChunkedSpeech=!1,this.currentChunks=null,this.fullText&&0!==this.fullText.length||(this.fullText=i),yield this.speak(this.fullText),g.updateMediaSession(e.title||"Lesson","Course",!0,()=>this.resume(),()=>this.pause()),!0}catch(Ue){return this.isPlaying=!1,this.isPaused=!1,!1}})}speak(e,t=0){return c(this,null,function*(){if(!this.isStopped&&(!this.browserSupport.isAndroid&&!this.browserSupport.isCapacitor||this.useNativeTTS||J||(yield this.checkNativeTTS()),this.useNativeTTS||this.isInitialized&&this.speech||(yield this.initSpeech(),this.isInitialized))){this.errorCount>=this.maxRetries&&(this.reset(),this.errorCount=0);try{if(this.isStopped)return;if(this.useNativeTTS&&J){let i=e;if(t>0&&t<e.length&&(i=e.substring(t)),!i||"string"!=typeof i||0===i.trim().length)return this.isPlaying=!1,void(this.isPaused=!1);const s=3500;if(i.length>s)return void(yield this.speakInChunksNative(i,s));this.isPlaying=!0,this.isPaused=!1,this.speakingStartTime=Date.now();try{yield J.speak({text:i,lang:"en-US",rate:1,pitch:1,volume:1,category:"ambient"});return(()=>{c(this,null,function*(){try{let e=!0,t=0;const i=200;for(;e&&!this.isStopped&&!this.isPaused&&t<i;){yield new Promise(e=>setTimeout(e,500));e=(yield J.getStatus()).isSpeaking,t++}this.isPlaying=!1,this.isPaused=!1}catch(e){this.isPlaying=!1,this.isPaused=!1}})})(),!0}catch(Ue){this.isPlaying=!1,this.isPaused=!1}if(this.useNativeTTS&&J)return}if(yield this.resumeAudioContext(),yield this.waitForVoices(),!(this.speech&&this.isInitialized||(yield this.initSpeech(),this.isInitialized)))return;if(!e)return this.isPlaying=!1,void(this.isPaused=!1);let s=e;if(t>0&&t<e.length&&(s=e.substring(t)),"string"!=typeof e)return this.isPlaying=!1,void(this.isPaused=!1);if(0===e.trim().length)return this.isPlaying=!1,void(this.isPaused=!1);if(e.trim().length<5)return this.isPlaying=!1,void(this.isPaused=!1);this.speech&&"function"==typeof this.speech.cancel&&(this.speech.cancel(),yield new Promise(e=>setTimeout(e,50)));const n=this.isWindowsPackagedRuntime?2200:1e3;if(s.length>n)return void(yield this.speakInChunks(s,n));if(this.isPlaying=!0,this.isPaused=!1,this.speakingStartTime=Date.now(),yield this.speakWithLibrary(s),!this.isStopped&&(this.isPlaying=!1,this.isPaused=!1,"function"==typeof this.onCompleteCallback))try{this.onCompleteCallback()}catch(i){}}catch(Ue){this.isPlaying=!1,this.isPaused=!1}}})}speakWithLibrary(e){return c(this,null,function*(){return new Promise(t=>{let i=null;const s=()=>c(this,null,function*(){try{yield this.speakWithBrowserUtterance(e)}catch(i){}finally{t()}});try{const n={text:e,splitSentences:!1};if(!this.speech||"function"!=typeof this.speech.speak)return void s();i=setTimeout(()=>{t()},12e4),this.speech.speak(n).then(e=>{i&&clearTimeout(i),t()}).catch(e=>{i&&clearTimeout(i),s()})}catch(Ue){i&&clearTimeout(i),s()}})})}speakWithBrowserUtterance(e){return c(this,null,function*(){if("undefined"==typeof window||!window.speechSynthesis||void 0===window.SpeechSynthesisUtterance)return;const t="string"==typeof e?e.trim():"";if(!t)return;yield this.resumeAudioContext(),(window.speechSynthesis.speaking||window.speechSynthesis.pending)&&window.speechSynthesis.cancel();const i=new SpeechSynthesisUtterance(t);i.lang="en-US",i.rate=this.isWindowsPackagedRuntime?1:.95,i.pitch=1,i.volume=1;const s=(window.speechSynthesis.getVoices()||[]).find(e=>e.lang&&e.lang.toLowerCase().startsWith("en"));s&&(i.voice=s),yield new Promise(e=>{i.onend=()=>e(),i.onerror=()=>e(),window.speechSynthesis.speak(i)})})}startHeartbeat(){this.stopHeartbeat(),this.useNativeTTS||this.isWindowsPackagedRuntime||(this.heartbeat=setInterval(()=>{this.isPlaying&&!this.isPaused&&"undefined"!=typeof window&&window.speechSynthesis&&(window.speechSynthesis.pause(),window.speechSynthesis.resume())},1e4))}stopHeartbeat(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=null)}createChunks(e,t=1e3){if(!e||"string"!=typeof e)return[];const i=[];let s="";const n=e.match(/[^.!?]+[.!?]*\s*/g)||[e];for(const a of n)s.length+a.length>t&&s.length>0?(i.push(s.trim()),s=a):s+=(s.length>0?" ":"")+a;if(s.trim().length>0&&i.push(s.trim()),0===i.length||1===i.length&&i[0].length>t){i.length=0;for(let s=0;s<e.length;s+=t)i.push(e.substring(s,s+t).trim())}return i}speakInChunks(e,t=1e3){return c(this,null,function*(){if(this.isStopped)return;const i=this.createChunks(e,t);this.currentChunks=i,this.currentChunkIndex=0,this.isChunkedSpeech=!0,this.isPlaying=!0,this.isPaused=!1,this.speakingStartTime=Date.now(),this.startHeartbeat();for(let e=0;e<i.length&&(i&&Array.isArray(i));e++){if(!this.isInitialized||this.errorCount>=this.maxRetries||this.isStopped){try{this.speech&&"function"==typeof this.speech.cancel&&this.speech.cancel()}catch(Ue){}break}if(this.isStopped)break;if(this.isPaused)return void(this.currentChunkIndex=e);if(e>=i.length)break;const t=i[e];if(t){this.currentChunkIndex=e;try{const s=this.speakWithLibrary(t);try{const e=new Promise((e,t)=>
1{const i=setInterval(()=>{this.isStopped&&(clearInterval(i),t(new Error("TTS_STOPPED")))},100);setTimeout(()=>{clearInterval(i)},3e4)});yield Promise.race([s,e])}catch(Ue){if("TTS_STOPPED"===Ue.message)return;throw Ue}if(this.isPaused)return;if(this.isStopped)break;if(this.isStopped)break;if(i&&e<i.length-1&&(yield new Promise(e=>setTimeout(e,25)),this.isStopped))break}catch(Ue){this.errorCount++}}}if(this.isChunkedSpeech=!1,this.isPaused||(this.currentChunks=null,this.currentChunkIndex=0,this.stopHeartbeat()),this.isPlaying=!1,!this.isStopped&&!this.isPaused&&"function"==typeof this.onCompleteCallback)try{this.onCompleteCallback()}catch(s){}})}speakChunksFrom(e){return c(this,null,function*(){if(!this.isStopped&&!this.isStopped&&this.isChunkedSpeech&&this.currentChunks&&Array.isArray(this.currentChunks)&&0!==this.currentChunks.length){(e<0||e>=this.currentChunks.length)&&(e=0);try{this.speech&&"function"==typeof this.speech.cancel&&this.speech.cancel()}catch(t){}this.isPlaying=!0,this.isPaused=!1,this.wasManuallyPaused=!1,this.speakingStartTime=Date.now(),this.startHeartbeat(),yield new Promise(e=>setTimeout(e,100));for(let t=e;t<this.currentChunks.length&&(this.currentChunks&&Array.isArray(this.currentChunks));t++){if(!this.isInitialized||this.errorCount>=this.maxRetries||this.isStopped){try{this.speech&&"function"==typeof this.speech.cancel&&this.speech.cancel()}catch(Ue){}break}if(this.isStopped)break;if(this.isPaused)return void(this.currentChunkIndex=t);if(t>=this.currentChunks.length)break;const e=this.currentChunks[t];if(e){this.currentChunkIndex=t;try{const i=new Promise(t=>{const i={text:e,splitSentences:!1};if(this.speech&&this.isInitialized)try{this.speakingStartTime=Date.now();const e=this.speech.speak(i);let s=!1;const n=e=>{s||(s=!0,this.isStopped||this.wasManuallyStopped,t())},a=e=>{s||(s=!0,e&&(e.includes("voice")||e.includes("not-allowed"))&&(this.isInitialized=!1,this.initSpeech()),t())};e.then(n).catch(a)}catch(Ue){t()}else t()});if(yield i,this.isPaused)return;if(this.isStopped)break;this.currentChunks&&t<this.currentChunks.length-1&&(yield new Promise(e=>setTimeout(e,100)))}catch(Ue){this.errorCount++}}}this.isChunkedSpeech=!1,this.isPaused||(this.currentChunks=null,this.currentChunkIndex=0,this.stopHeartbeat()),this.isPlaying=!1}})}resumeChunkedSpeech(){return c(this,null,function*(){return this.speakChunksFrom(this.currentChunkIndex)})}speakInChunksNative(e,t=2e3){return c(this,null,function*(){const i=this.createChunks(e,t);return this.isChunkedSpeech=!0,this.currentChunks=i,this.currentChunkIndex=0,this.isPlaying=!0,this.isPaused=!1,this.isStopped=!1,new Promise(e=>{let t=!1;(()=>{c(this,null,function*(){try{for(let a=0;a<i.length&&!this.isStopped;a++){this.currentChunkIndex=a;const s=i[a];yield J.speak({text:s,lang:"en-US",rate:.9,pitch:1,volume:1,queue:a>0}),t||(t=!0,e(!0)),a<i.length-1&&(yield new Promise(e=>setTimeout(e,50)))}let s=!0,n=0;for(;s&&!this.isStopped&&!this.isPaused&&n<600;){yield new Promise(e=>setTimeout(e,500));s=(yield J.getStatus()).isSpeaking,n++}}catch(Ue){t||(t=!0,e(!1))}finally{this.isChunkedSpeech=!1,this.isPlaying=!1,this.isPaused=!1}})})()})})}pause(){return c(this,null,function*(){if(this.isPlaying){if(this.isChunkedSpeech){this.isPaused=!0,this.isPlaying=!1,this.wasManuallyPaused=!0;try{this.speech&&this.speech.pause(),window.speechSynthesis&&window.speechSynthesis.pause()}catch(e){}return this.stopHeartbeat(),!0}try{this.speech&&(yield this.speech.pause()),this.isPaused=!0,this.isPlaying=!1,this.wasManuallyPaused=!0,this.stopHeartbeat()}catch(e){return yield this.stop(),!1}return g.updateMediaSession(this.currentLessonTitle||"Lesson","Course",!1),!0}return!1})}resume(){return c(this,null,function*(){if(this.isPaused){if(this.isChunkedSpeech)return this.isPaused=!1,this.isPlaying=!0,this.wasManuallyPaused=!1,this.startHeartbeat(),this.resumeChunkedSpeech();try{this.speech&&(yield this.speech.resume()),this.isPaused=!1,this.isPlaying=!0,this.wasManuallyPaused=!1,this.startHeartbeat()}catch(e){return!1}return g.updateMediaSession(this.currentLessonTitle||"Lesson","Course",!0),!0}return!1})}handleSpeakError(e,t,i){this.errorCount++,this.errorCount<this.maxRetries&&setTimeout(()=>{t&&t.trim().length>5&&this.speak(t,i)},1e3)}stop(){if(this.isInitialized)try{if(this.isStopped=!0,this.wasManuallyStopped=!0,this.stopHeartbeat(),this.useNativeTTS&&J)try{J.stop()}catch(e){}if(this.speech&&"function"==typeof this.speech.cancel&&this.speech.cancel(),"undefined"!=typeof window&&window.speechSynthesis)try{window.speechSynthesis.cancel()}catch(e){}this.isPlaying=!1,this.isPaused=!1,this.errorCount=0,this.currentText="",this.currentLessonId=null,this.fullText="",this.pausePosition=0,this.pauseTime=0,this.totalSpokenTime=0,this.speakingStartTime=0,this.finishedNormally=!1,this.wasManuallyPaused=!1,this.isChunkedSpeech=!1,this.currentChunks=null,this.currentChunkIndex=0,this.clearServerPauseData().catch(e=>{}),g.clearMediaSession()}catch(Ue){}finally{this.speakTimeout&&(clearTimeout(this.speakTimeout),this.speakTimeout=null)}else this.isStopped=!0,this.wasManuallyStopped=!0,this.isPlaying=!1,this.isPaused=!1}stopAndClear(){if(this.isInitialized)try{this.speech.cancel(),this.stopHeartbeat(),this.isPlaying=!1,this.isPaused=!1,this.errorCount=0,this.currentText="",this.currentLessonId=null,this.fullText="",this.pausePosition=0,this.pauseTime=0,this.totalSpokenTime=0,this.speakingStartTime=0,this.finishedNormally=!1,this.wasManuallyPaused=!1,this.isChunkedSpeech=!1,this.currentChunks=null,this.currentChunkIndex=0}catch(Ue){}finally{this.speakTimeout&&(clearTimeout(this.speakTimeout),this.speakTimeout=null)}}clearServerPauseData(){return c(this,null,function*(){try{if(this.currentLessonId){yield h("/api/tts/clear-pause-position",{method:"POST",body:JSON.stringify({lessonId:this.currentLessonId,serviceType:this.serviceType})})}}catch(Ue){}return Promise.resolve()})}testTTS(){return c(this,null,function*(){try{yield this.resumeAudioContext();const e=new SpeechSynthesisUtterance("Hello, this is a test.");return e.rate=1,e.pitch=1,e.volume=1,e.onstart=()=>{},e.onend=()=>{},e.onerror=e=>{},window.speechSynthesis.speak(e),!0}catch(Ue){return!1}})}reset(){try{this.stopHeartbeat(),this.isPlaying=!1,this.isPaused=!1,this.isChunkedSpeech=!1,this.errorCount=0,this.initializationAttempts=0,this.pauseTime=0,this.speakingStartTime=0,this.finishedNormally=!1,this.wasManuallyPaused=!1,this.currentText="",this.currentLessonId=null,this.fullText="",this.pausePosition=0,this.totalSpokenTime=0,this.currentChunks=null,this.currentChunkIndex=0,this.speakTimeout&&(clearTimeout(this.speakTimeout),this.speakTimeout=null)}catch(Ue){}}restart(){return c(this,null,function*(){try{return this.isStopped=!1,this.wasManuallyStopped=!1,this.heartbeat=null,this.reset(),yield this.initSpeech(),!0}catch(Ue){return!1}})}isSupported(){return this.browserSupport.speechSynthesis&&this.isInitialized}getStatus(){return{isPlaying:this.isPlaying,isPaused:this.isPaused,isStopped:this.isStopped,currentLessonId:this.currentLessonId,isSupported:this.isSupported(),errorCount:this.errorCount,serviceType:this.serviceType,isInitialized:this.isInitialized,browserSupport:this.browserSupport,initializationAttempts:this.initializationAttempts}}
1getStableStatus(){return this.getStatus()}setOnCompleteCallback(e){this.onCompleteCallback="function"==typeof e?e:null}getSpeakTTSState(){var e,t,i;try{return{hasSpeech:!!this.speech,speechType:typeof this.speech,hasPause:"function"==typeof(null==(e=this.speech)?void 0:e.pause),hasResume:"function"==typeof(null==(t=this.speech)?void 0:t.resume),hasCancel:"function"==typeof(null==(i=this.speech)?void 0:i.cancel),ourPaused:this.isPaused,ourPlaying:this.isPlaying,wasManuallyPaused:this.wasManuallyPaused}}catch(Ue){return{error:Ue.message}}}testTTSWorking(){return c(this,null,function*(){try{this.getSpeakTTSState();const e="Test.",t=new Promise(t=>{const i={text:e,splitSentences:!1};this.speech.speak(i).then(e=>{t({success:!0,result:e})}).catch(e=>{t({success:!1,error:e})})}),i=new Promise(e=>{setTimeout(()=>{e({success:!1,error:"timeout"})},3e3)});return yield Promise.race([t,i])}catch(Ue){return{success:!1,error:Ue}}})}testPauseResume(){return c(this,null,function*(){try{this.getSpeakTTSState();const e="This is a test of the pause and resume functionality. It should work correctly.";return yield this.speak(e),setTimeout(()=>c(this,null,function*(){yield this.pause(),setTimeout(()=>c(this,null,function*(){this.resume()}),1e3)}),2e3),!0}catch(Ue){return!1}})}canResume(){return this.isPaused&&this.fullText&&this.currentLessonId}isActuallyPaused(){try{return this.isPaused||this.wasManuallyPaused}catch(Ue){return this.isPaused||this.wasManuallyPaused}}restartFromPausePosition(e=null){return c(this,null,function*(){if(this.isStopped)return!1;if(!this.fullText)return!1;try{let i=this.pausePosition;if(e&&e.pausePosition&&(i=e.pausePosition,this.pausePosition=e.pausePosition),i<=0)return!1;if(this.isPlaying||this.isPaused)try{this.speech&&"function"==typeof this.speech.cancel&&this.speech.cancel()}catch(t){}this.isPlaying=!1,this.isPaused=!1,this.errorCount=0,this.wasManuallyPaused=!1,this.speakingStartTime=0,yield new Promise(e=>setTimeout(e,200));const s=this.fullText.substring(i);return!s||0===s.trim().length||!this.isStopped&&(yield this.speak(s),!0)}catch(Ue){return!1}})}forceReinitialize(){return c(this,null,function*(){this.isInitialized=!1,this.initializationAttempts=0,yield this.initSpeech()})}forceResetStoppingFlag(){this.isPlaying=!1,this.isPaused=!1,this.errorCount=0,this.pausePosition=0,this.pauseTime=0,this.totalSpokenTime=0,this.speakingStartTime=0,this.finishedNormally=!1,this.wasManuallyPaused=!1,this.speakTimeout&&(clearTimeout(this.speakTimeout),this.speakTimeout=null)}recordTTSPausePosition(e,t=null,i="manual"){return c(this,null,function*(){try{let s=null;null!=t&&"number"==typeof t&&t>=0&&(s=t);const n={lessonId:e,serviceType:this.serviceType,pauseTime:Date.now(),pauseReason:i,chunkIndex:s,totalSpokenTime:this.totalSpokenTime,pausePosition:this.pausePosition,fullTextLength:this.fullText?this.fullText.length:0};return yield h("/api/tts/record-pause",{method:"POST",body:JSON.stringify(n)})}catch(Ue){return null}})}getPausePosition(e){return c(this,null,function*(){try{const t=yield h(`/api/tts/pause-position?lessonId=${e}`,{method:"GET"});return t||null}catch(Ue){return null}})}isReadyForRequests(){return this.isInitialized&&!this.isPlaying}debugState(){this.isActuallyPaused()}resetPauseData(){this.pausePosition=0,this.pauseTime=0,this.totalSpokenTime=0,this.speakingStartTime=0,this.wasManuallyPaused=!1,this.finishedNormally=!1,this.currentLessonId&&this.clearPausePosition(this.currentLessonId).catch(e=>{})}clearPausePosition(e){return c(this,null,function*(){try{yield h("/api/tts/clear-pause-position",{method:"POST",body:JSON.stringify({lessonId:e,serviceType:this.serviceType})})}catch(Ue){}return Promise.resolve()})}}const ie=new te("private"),se=new te("public");"undefined"!=typeof window&&"localhost"===window.location.hostname&&(window.privateTTSService=ie,window.publicTTSService=se);const ne=({term:e,definition:t})=>{const[i,s]=y.useState(!1);return b.jsx("div",{className:"flashcard-container "+(i?"flipped":""),onClick:()=>s(!i),children:b.jsxs("div",{className:"flashcard-inner",children:[b.jsx("div",{className:"flashcard-front",children:b.jsx("p",{children:e})}),b.jsx("div",{className:"flashcard-back",children:b.jsx("p",{children:t})})]})})};
1ne.propTypes={term:d.string.isRequired,definition:d.string.isRequired};const ae=({language:e="javascript"})=>{const[t,i]=y.useState('// Type your code here...\nconsole.log("Hello, World!");'),[s,n]=y.useState([]),[a,r]=y.useState(!1),o=y.useRef(null);y.useEffect(()=>{o.current&&(o.current.scrollTop=o.current.scrollHeight)},[s]);return b.jsxs("div",{className:"code-console-wrapper",children:[b.jsxs("div",{className:"console-header",children:[b.jsx("div",{className:"console-tabs",children:b.jsxs("div",{className:"console-tab active",children:[b.jsx("span",{className:"tab-icon",children:"â¡"}),e.charAt(0).toUpperCase()+e.slice(1)," Console"]})}),b.jsxs("div",{className:"console-actions",children:[b.jsx("button",{className:"action-btn clear",onClick:()=>{n([])},title:"Clear Console",children:"Clear"}),b.jsx("button",{className:"action-btn run "+(a?"loading":""),onClick:()=>{r(!0);const e=[],i=console.log,s=console.error;console.log=(...t)=>{e.push({type:"log",content:t.map(e=>"object"==typeof e?JSON.stringify(e,null,2):String(e)).join(" ")})},console.error=(...t)=>{e.push({type:"error",content:t.map(e=>"object"==typeof e?JSON.stringify(e,null,2):String(e)).join(" ")})};try{new Function(t)(),0===e.length&&e.push({type:"system",content:"Code executed successfully (no output)."})}catch(a){e.push({type:"error",content:`Runtime Error: ${a.message}`})}finally{console.log=i,console.error=s,n(t=>[...t,...e]),r(!1)}},disabled:a,children:a?"Running...":"Run Code"})]})]}),b.jsxs("div",{className:"console-body",children:[b.jsx("div",{className:"editor-section",children:b.jsx("textarea",{value:t,onChange:e=>i(e.target.value),onKeyDown:e=>{if("Tab"===e.key){e.preventDefault();const s=e.target.selectionStart,n=e.target.selectionEnd,a=t.substring(0,s)+" "+t.substring(n);i(a),setTimeout(()=>{e.target.selectionStart=e.target.selectionEnd=s+2},0)}},spellCheck:"false",className:"code-editor",placeholder:"Write your code here..."})}),b.jsxs("div",{className:"output-section",children:[b.jsx("div",{className:"output-header",children:"Output"}),b.jsx("div",{className:"output-content",ref:o,children:0===s.length?b.jsx("div",{className:"output-placeholder",children:"Run your code to see results here..."}):s.map((e,t)=>b.jsxs("div",{className:`output-line ${e.type}`,children:[b.jsx("span",{className:"line-prefix",children:"error"===e.type?"â":"âº"}),b.jsx("pre",{className:"line-text",children:e.content})]},t))})]})]})]})};const re=new class{constructor(){this.metrics={renderTimes:new Map,apiCalls:new Map,imageLoads:new Map,componentRenders:new Map,flashcardRenders:0,lastFlashcardRender:0},this.thresholds={slowRender:100,slowApiCall:1e3,slowImageLoad:2e3,excessiveRenders:10},this.isEnabled=!0,this.initPerformanceObserver()}initPerformanceObserver(){if("PerformanceObserver"in window)try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration,0}).observe({entryTypes:["longtask"]});new PerformanceObserver(e=>{for(const t of e.getEntries())t.value,0}).observe({entryTypes:["layout-shift"]})}catch(Ue){}}trackRenderTime(e,t){this.isEnabled&&(this.metrics.renderTimes.has(e)||this.metrics.renderTimes.set(e,[]),this.metrics.renderTimes.get(e).push(t),this.thresholds.slowRender)}trackApiCall(e,t,i=!0){this.isEnabled&&(this.metrics.apiCalls.has(e)||this.metrics.apiCalls.set(e,[]),this.metrics.apiCalls.get(e).push({duration:t,success:i,timestamp:Date.now()}),this.thresholds.slowApiCall)}trackImageLoad(e,t,i=!1){this.isEnabled&&(this.metrics.imageLoads.has(e)||this.metrics.imageLoads.set(e,[]),this.metrics.imageLoads.get(e).push({duration:t,cacheHit:i,timestamp:Date.now()}),this.thresholds.slowImageLoad)}trackComponentRender(e){this.isEnabled&&(this.metrics.componentRenders.has(e)||this.metrics.componentRenders.set(e,0),this.metrics.componentRenders.set(e,this.metrics.componentRenders.get(e)+1))}trackFlashcardRender(){if(!this.isEnabled)return;const e=Date.now();this.metrics.flashcardRenders++,e-this.metrics.lastFlashcardRender<1e3?(this.metrics.flashcardRenders,this.thresholds.excessiveRenders):(this.metrics.flashcardRenders=1,this.metrics.lastFlashcardRender=e)}getPerformanceSummary(){const e={renderTimes:{},apiCalls:{},imageLoads:{},componentRenders:{},recommendations:[]};for(const[t,i]of this.metrics.renderTimes)if(i.length>0){const s=i.reduce((e,t)=>
1e+t,0)/i.length,n=Math.max(...i);e.renderTimes[t]={avg:s.toFixed(2),max:n,count:i.length},s>this.thresholds.slowRender&&e.recommendations.push("Consider memoizing "+t+" component")}for(const[t,i]of this.metrics.apiCalls)if(i.length>0){const s=i.reduce((e,t)=>e+t.duration,0)/i.length,n=Math.max(...i.map(e=>e.duration));e.apiCalls[t]={avg:s.toFixed(2),max:n,count:i.length},s>this.thresholds.slowApiCall&&e.recommendations.push("Consider caching or optimizing "+t+" API calls")}for(const[t,i]of this.metrics.imageLoads)if(i.length>0){const s=i.reduce((e,t)=>e+t.duration,0)/i.length,n=Math.max(...i.map(e=>e.duration)),a=i.filter(e=>e.cacheHit).length/i.length;e.imageLoads[t]={avg:s.toFixed(2),max:n,count:i.length,cacheHitRate:(100*a).toFixed(1)+"%"},s>this.thresholds.slowImageLoad&&e.recommendations.push("Consider optimizing image loading for "+t)}for(const[t,i]of this.metrics.componentRenders)e.componentRenders[t]=i,i>100&&e.recommendations.push("Component "+t+" is rendering too frequently - consider optimization");return e}resetMetrics(){this.metrics={renderTimes:new Map,apiCalls:new Map,imageLoads:new Map,componentRenders:new Map,flashcardRenders:0,lastFlashcardRender:0}}setEnabled(e){this.isEnabled=e}getMetrics(){return o({},this.metrics)}logPerformanceSummary(){const e=this.getPerformanceSummary();return e.recommendations.length>0&&e.recommendations.forEach(e=>{}),e}},oe=/\[\s*\{[\s\S]{0,300}?"question"\s*:/,le={option:/^\s*\(?[A-Da-d][.):]\s+\S/,marker:/^\s*(?:#{1,6}\s*)?(?:question\s*\d+|q\d+)\b/i,heading:/^\s*(?:#{1,6}\s*)?(?:mini[- ]?quiz|quiz(?:\s*time)?|knowledge\s+check|check\s+your\s+(?:knowledge|understanding)|test\s+your\s+(?:knowledge|understanding)|practice\s+questions|review\s+questions)\b[^\n]{0,40}$/i,answer:/^\s*(?:correct\s+)?answer\b\s*[:\-]/i},ce=e=>{if(!e||"string"!=typeof e)return-1;const t=le,i=e.split("\n"),s=i.map(e=>e.replace(/\*\*/g,"").trim());let n=0;for(let a=0;a<i.length;a++){const e=s[a];let r=t.heading.test(e)||t.marker.test(e);if(!r&&/\?\s*$/.test(e))for(let n=a+1;n<=a+3&&n<i.length;n++)if(s[n]){r=t.option.test(s[n]);break}if(r){let e=0,r=0,o=0;for(let n=a;n<Math.min(i.length,a+16);n++)t.option.test(s[n])&&e++,t.answer.test(s[n])&&r++,n>a&&t.marker.test(s[n])&&o++;if(e>=2||r>=1||o>=1)return n}n+=i[a].length+1}return-1},ue=(e,{preserveHeaders:t=!1}={})=>{if(!e||"string"!=typeof e)return"";const{text:i}=(e=>{if(!e||"string"!=typeof e)return{text:e||"",quiz:null};const t=e.match(oe);if(!t)return{text:e,quiz:null};const i=t.index;let s=0,n=!1,a=-1;for(let l=i;l<e.length;l++){const t=e[l];if(n)"\\"===t?l++:'"'===t&&(n=!1);else if('"'===t)n=!0;else if("["===t)s++;else if("]"===t&&(s--,0===s)){a=l+1;break}}let r=null;if(-1!==a)try{const t=JSON.parse(e.slice(i,a));Array.isArray(t)&&t.length>0&&(r=t)}catch(o){}else a=e.length;return{text:`${e.slice(0,i)} ${e.slice(a)}`.trim(),quiz:r}})(e);return((e,t=!1)=>{if(!e||"string"!=typeof e)return"";let i=e.replace(/\|\|\|---\|\|\|/g,"\n").replace(/\|\|\|/g,"\n").replace(/Content generation completed\./gi,"");return t||(i=i.replace(/^\s*#{1,6}\s*(?:INTRODUCTION|MAIN\s*CONTENT|CONCLUSION|QUIZ)\s*:?\s*$/gim,"")),i=i.replace(/^\s*(?:\d+\s*[.)]\s*)?(?:INTRODUCTION|MAIN\s*CONTENT|CONCLUSION|QUIZ)\s*:?\s*$/gim,"").replace(/^\s*(?:\d+\s*[.)]\s*)?(?:INTRODUCTION|MAIN\s*CONTENT|CONCLUSION|QUIZ)\s*:\s+/gim,""),i.replace(/\n{3,}/g,"\n\n").trim()})((e=>{const t=ce(e);return-1===t?e||"":(e||"").slice(0,t).trim()})(i),t)},he=e=>{if(!e)return!1;const t="string"==typeof e?e:["introduction","main_content","conclusion"].map(t=>"string"==typeof e[t]?e[t]:"").join("\n");return!!t.trim()&&(!!t.includes("|||")||(!!oe.test(t)||(!!/^\s*(?:\d+\s*[.)]\s*)?(?:INTRODUCTION|MAIN\s*CONTENT|CONCLUSION|QUIZ)\s*:/im.test(t)||-1!==ce(t))))},de=y.memo(({references:e,onCitationClick:t,isLoading:i=!1})=>{const[s,n]=y.useState(!1),{t:a}=f();if(i)return b.jsx("footer",{className:"academic-references-footer mt-12 pt-8 border-t-2 border-gray-300 dark:border-slate-700 bg-gray-50 dark:bg-slate-900 transition-colors duration-300",children:b.jsx("div",{className:"max-w-4xl mx-auto px-4",children:b.jsxs("div",{className:"academic-references-header w-full text-left text-2xl font-bold text-gray-900 dark:text-white mb-6 flex items-center justify-between p-3 rounded-lg",children:[b.jsx("span",{className:"font-bold text-gray-900 dark:text-white",children:a("practiceStudio.academicReferences")}),b.jsxs("div",{className:"flex items-center space-x-2",children:[b.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"}),b.jsx("span",{className:"text-sm text-gray-600 dark:text-slate-400",children:"Generating authentic references..."})]})]})})});if(!e||0===e.length)return b.jsx("footer",{className:"academic-references-footer mt-12 pt-8 border-t-2 border-gray-300 dark:border-slate-700 bg-gray-50 dark:bg-slate-900 transition-colors duration-300",children:b.jsxs("div",{className:"max-w-4xl mx-auto px-4",children:[b.jsxs("button",{onClick:()=>n(!s),className:"academic-references-header w-full text-left text-2xl font-bold text-gray-900 dark:text-white mb-6 flex items-center justify-between hover:bg-gray-100 dark:hover:bg-slate-800 p-3 rounded-lg transition-colors duration-200",children:[b.jsx("span",{className:"font-bold text-gray-900 dark:text-white",children:a("practiceStudio.academicReferences")}),b.jsx("svg",{className:"w-6 h-6 transform transition-transform duration-200 "+(s?"rotate-180":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:b.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})]}),b.jsx("div",{className:"academic-references-list space-y-4 transition-all duration-300 ease-in-out overflow-hidden "+(s?"max-h-screen opacity-100":"max-h-0 opacity-0"),children:b.jsx("div",{className:"citation-item bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-gray-200 dark:border-slate-700",children:b.jsxs("div",{className:"text-center text-gray-600 dark:text-slate-300",children:[b.jsx("p",{className:"font-semibold mb-2",children:a("practiceStudio.noReferences")}),b.jsx("p",{className:"text-sm mb-2",children:"References are generated dynamically based on lesson content."})]})})})]})});const r=e=>{try{return k.parse(e)}catch(Ue){return e}};return b.jsx("footer",{className:"academic-references-footer mt-12 pt-8 border-t-2 border-gray-300 dark:border-slate-700 bg-gray-50 dark:bg-slate-900 transition-colors duration-300",children:b.jsxs("div",{className:"max-w-4xl mx-auto px-4",children:[b.jsxs("button",{onClick:()=>n(!s),className:"academic-references-header w-full text-left text-2xl font-bold text-gray-900 dark:text-white mb-6 flex items-center justify-between hover:bg-gray-100 dark:hover:bg-slate-800 p-3 rounded-lg transition-colors duration-200",children:[b.jsx("span",{className:"font-bold text-gray-900 dark:text-white",children:a("practiceStudio.academicReferences")}),b.jsx("svg",{className:"w-6 h-6 transform transition-transform duration-200 text-gray-700 dark:text-slate-300 "+(s?"rotate-180":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:b.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})]}),b.jsxs("div",{className:"academic-references-list space-y-4 transition-all duration-300 ease-in-out overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-slate-700 "+(s?"max-h-[500px] opacity-100 pr-2":"max-h-0 opacity-0"),children:[e.map(e=>b.jsxs("div",{className:"citation-item bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-gray-200 dark:border-slate-700 hover:shadow-md transition-shadow duration-200",children:[b.jsxs("div",{className:"flex items-start",children:[b.jsx("span",{className:"citation-number inline-flex items-center justify-center w-8 h-8 bg-blue-600 text-white text-sm font-bold rounded-full mr-4 mt-1 cursor-pointer hover:bg-blue-700 transition-colors duration-200",onClick:()=>{return i=e.id,void(t&&"function"==typeof t&&t(i));var i},title:"Click to highlight citations in text",children:e.id}),b.jsx("div",{className:"citation-text flex-1 text-gray-800 dark:text-slate-200 leading-relaxed",dangerouslySetInnerHTML:{__html:r(e.citation)}})]}),b.jsx("div",{className:"mt-2 ml-12",children:b.jsx("span",{className:"inline-block px-2 py-1 text-xs font-medium bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-slate-300 rounded",children:e.type||"Academic Source"})})]},e.id)),b.jsx("div",{className:"mt-6 pt-4 border-t border-gray-200 dark:border-slate-700",children:b.jsx("p",{className:"text-sm text-gray-600 dark:text-slate-400 text-center"})})]})]})})});de.displayName="AcademicReferencesFooter";const me="3D Lab",pe=/\b(art history|history of art|visual arts? history|historia del arte|histoire de l['â]art|kunstgeschichte|storia dell['â ]arte|hist[oó]ria da arte|historia sztuki|istoria artei|ØªØ§Ø±ÙØ® اÙÙÙ|à
1¤à¤²à¤¾ à¤à¤¤à¤¿à¤¹à¤¾à¤¸|ÙÙ Ú©Û ØªØ§Ø±ÛØ®|èºæ¯å²)\b/i,ge=e=>Array.isArray(e)?e.map(e=>"string"==typeof e?e:(null==e?void 0:e.term)||(null==e?void 0:e.name)||(null==e?void 0:e.title)||"").filter(Boolean):[],fe=e=>"string"==typeof e?e:e&&"object"==typeof e?[e.introduction,e.main_content,e.mainContent,e.conclusion,e.summary].filter(e=>"string"==typeof e).join(" "):"",ye=(e,t)=>e.reduce((e,i)=>e+(i.test(t)?1:0),0),be=(e,t)=>({eligible:!0,confidence:"high",reasonCode:e.id,reason:e.reason,preferredTemplate:e.templates[0],allowedTemplates:[...e.templates],label:me,evidence:t,version:6}),we=[{id:"art-history-gallery",templates:["artwork-study"],reason:"Art-history lessons use the course artwork as primary evidence in a focused gallery study.",match:({courseSubject:e,courseTitle:t})=>pe.test(`${t||""} ${e||""}`)},{id:"robotics-system",templates:["robotics-lab"],reason:"Joint movement and reach are directly observable and manipulable.",match:({focus:e,content:t})=>/\b(robot(?:ic|ics)?|robot arm|manipulator|mechatronic|end effector|servo motor|forward kinematic|inverse kinematic|cobot)\b/i.test(e)||/\b(robot(?:ic|ics)?|robot arm|manipulator|cobot)\b/i.test(t)&&/\b(joint|reach|kinematic|end effector|servo|grip|actuat\w*)\b/i.test(t)},{id:"astronomical-system",templates:["solar-system"],reason:"A rotatable spatial model reveals scale, position, and orbital relationships.",match:({focus:e,content:t})=>/\b(orbital? mechanics|orbit(?:s|al|ing)?|solar system|planetary system|planetary motion|astronom\w*|heliocentric|geocentric)\b/i.test(`${e} ${t}`)||/\b(planet|moon|star)\b/i.test(e)&&/\b(orbit|rotation|revolution|distance|system)\b/i.test(t)},{id:"molecular-structure",templates:["molecule"],reason:"Three-dimensional bonds and molecular geometry need spatial inspection.",match:({focus:e,content:t})=>/\b(molecul\w*|molecular geometry|covalent bond|ionic bond|chemical bond|atomic structure|crystal lattice)\b/i.test(`${e} ${t}`)||/\b(atom|compound)\b/i.test(e)&&/\b(bond|geometry|structure|electron)\b/i.test(t)},{id:"cellular-structure",templates:["cell"],reason:"The learner benefits from inspecting nested biological structures in space.",match:({focus:e,content:t,courseSubject:i})=>!!/\b(biolog\w*|botan\w*|cytolog\w*|microbiolog\w*|life science|plant cells?|animal cells?|bacterial cells?|eukaryotic cells?|prokaryotic cells?|cell biology|cellular biology)\b/i.test(`${i} ${e}`)&&(/\b(organelle|mitochondri\w*|cell membrane|cell wall|cytoplasm|chloroplast|nucleus|vacuole|eukaryotic cell|prokaryotic cell)\b/i.test(`${e} ${t}`)||/\bcell(?:ular)?\b/i.test(e)&&/\b(biology|biological|nucleus|membrane|organelle|structure)\b/i.test(t))},{id:"anatomical-structure",templates:["assembly"],reason:"Rotation and labelled spatial relationships support anatomical understanding.",match:({focus:e,content:t})=>/\b(anatom\w*|skelet\w*|musculoskeletal|organ system|bone structure|muscle groups?|heart chambers?|cranial nerves?|vertebral column)\b/i.test(`${e} ${t}`)||/\b(heart|brain|lung|kidney|joint)\b/i.test(e)&&/\b(anatomy|chamber|lobe|structure|system|cross-section)\b/i.test(t)},{id:"physical-dynamics",templates:["physics-lab"],reason:"Changing a physical variable produces a visible, testable consequence.",match:({focus:e,content:t})=>/\b(projectile motion|kinematic\w*|trajectory|newton(?:'s)? laws?|gravitational acceleration|momentum|restitution)\b/i.test(`${e} ${t}`)||/\b(velocity|acceleration|gravity|launch angle|force)\b/i.test(e)&&/\b(calculate|measure|trajectory|motion|experiment|variable)\b/i.test(t)},{id:"continuous-physical-field",templates:["well-field"],reason:"The lesson teaches a continuous physical process whose changing field is visible.",match:({focus:e,content:t})=>/\b(fluid dynamics|turbulence|convection|heat transfer|thermal diffusion|wave propagation|shallow water|reaction[- ]diffusion|thermodynamic\w*|plasma dynamics|ocean currents?)\b/i.test(`${e} ${t}`)},{id:"physical-geography",templates:["terrain"],reason:"Landforms and water routes are spatial evidence central to the lesson.",match:({focus:e,text:t})=>{const i=[/\b(river|tributary|delta|waterway)\b/i,/\b(sea|ocean|coast\w*|shore\w*)\b/i,/\b(hill\
1w*|mountain\w*|valley|canyon|plateau|plain\w*)\b/i,/\b(island|peninsula|strait|harbou?r|port)\b/i,/\b(terrain|topograph\w*|landform\w*|physical geography|geographic features?|physical setting|geography of)\b/i,/\b(settlement site|defen[cs]ive position|trade route|access to water)\b/i],s=ye(i,e),n=ye(i,t);return s>=2||s>=1&&n>=3||/\b(terrain|topograph\w*|geograph\w*|physical geography|geographic features?|geography of)\b/i.test(e)&&n>=2}},{id:"armed-conflict-campaign",templates:["battle-map"],reason:"Concrete opposing forces and the shift in power are visible through warrior groups and phases.",match:({text:e})=>{const t=/\b(battle|war|warfare|combat|siege|invasion|revolt|rebellion|military campaign|conquest|raid)\b/i.test(e),i=/\b(conflict|fought|fighting|defeat(?:ed)?|victor(?:y|ious)|advance|retreat|mobilis\w*|mobiliz\w*|overthrow|clash(?:ed)?)\b/i.test(e),s=/\b(arm(?:y|ies)|troops?|forces?|warriors?|samurai|clans?|infantry|cavalry|navy|fleet|taira|minamoto)\b/i.test(e),n=/\b(arm(?:y|ies)|troops?|forces?|clans?|infantry|cavalry|navy|fleet|taira|minamoto)\b/i.test(e),a=/\b(between|against|versus|rival|opposing|two (?:powerful )?(?:clans|armies|forces)|taira|minamoto)\b/i.test(e);return!/\b(conflict theory|class conflict|workplace conflict|interpersonal conflict|conflict resolution|conflict management|theory of conflict|structuralis\w*|semiotic\w*)\b/i.test(e)&&s&&a&&(t||i&&n)}},{id:"territorial-movement",templates:["battle-map","terrain"],reason:"Positions and movement across territory change over meaningful phases.",match:({focus:e,text:t})=>/\b(battle|military campaign|siege|invasion|migration route|trade route|exploration voyage|expedition route|plate tectonic)\b/i.test(e)&&/\b(route|movement|advance|retreat|phase|position|territor\w*|from .{0,40} to|across)\b/i.test(t)},{id:"samurai-equipment-study",templates:["custom-model"],reason:"Samurai lessons use a physical armour-and-weapon exhibit so learners can inspect the equipment behind the warrior tradition.",match:({focus:e,text:t})=>/\b(samurai|bushido|kabuto|yoroi|d[oÅ]-?maru|katana|wakizashi|yumi|shogun)\b/i.test(t)&&!/\b(hierarch\w*|chain of command|social pyramid|feudal system|vassalage)\b/i.test(e)},{id:"visual-analysis-gallery",templates:["artwork-study"],reason:"A single course-linked image is the evidence learners need to inspect closely.",match:({focus:e})=>/\b(photograph\w*|photo analysis|visual culture|visual semiotic\w*|image analysis|rhetoric of the image|advertis(?:ing|ement)|poster|illustration|iconograph\w*|painting|fresco|mural|portraiture)\b/i.test(e)},{id:"historical-sequence",templates:["timeline"],reason:"The order and consequences of concrete events are the lessonâs central evidence.",match:({focus:e,text:t,courseSubject:i})=>{const s=/\b(chronolog\w*|sequence of events|follow the (?:historical )?(?:story|narrative|events)|timeline|from .{0,40} to|rise and fall|origin story|foundation myth|succession|turning points?)\b/i.test(`${e} ${t}`),n=/\b(history|historical|ancient|medieval|renaissance|empire|republic|dynasty|myth|legend|monarchy|reign|founded|founding)\b/i.test(`${e} ${i}`),a=/\b(historiograph\w*|competing interpretations?|interpretive lenses?|schools? of thought|social construction|ideological readings?|semiolog\w*|semiotic\w*|structuralis\w*|post[- ]?structuralis\w*|signifier|signified|denotation|connotation|ideolog\w*|discourse|deconstruction|intertextuality|cultural studies|visual culture|media studies|author function|narrative codes?)\b/i.test(`${e} ${t}`);return s&&n&&!a}},{id:"multivariable-surface",templates:["math-surface"],reason:"A rotatable surface exposes relationships between two inputs and one output.",match:({focus:e,content:t})=>/\b(3d graph|three-dimensional graph|surface plot|multivariable function|function of two variables|z\s*=\s*f\s*\(\s*x\s*,\s*y\s*\)|partial derivatives?|gradient field)\b/i.test(`${e} ${t}`)}],ke=/\b(sociolog\w*|social science|social studies|political theory|philosoph\w*|ethics?|institutions?|identity|norms?|values?|belief systems?|power relations?|ideolog\w*|discourse|semiolog\w*|semiotic\w*|signifier|signified|denotation|connotation|structuralis\w*|post[- ]?structuralis\w*|deconstruction|intertextuality|cultural studies|cultural critique|visual culture|media studies|representation|narrative codes?|author function|conflict theory|critical theory|feminis\w
1*|marxis\w*|postcoloni\w*|intersectionali\w*|public opinion|media framing|social construction|competing interpretations?)\b/i,ve=/\b(history|historical|ancient|medieval|renaissance|empire|republic|dynasty|myth|legend|origin story|foundation|reign|succession|chronolog\w*|sequence of events|rise and fall)\b/i,xe=/\b(geograph\w*|geolog\w*|earth science|landform\w*|topograph\w*|physical environment)\b/i;function Se({lessonTitle:e="",lessonContent:t="",courseTitle:i="",courseSubject:s="",learningObjectives:n=[],keyTerms:a=[]}={}){const r=ge(n).join(" "),o=ge(a).join(" "),l=fe(t).slice(0,6e3),c=`${e} ${r} ${o}`.trim(),u=`${i} ${s}`.trim(),h=`${c} ${l} ${u}`.trim();for(const d of we)if(d.match({focus:c,text:h,content:l,courseSubject:s,courseTitle:i}))return be(d,d.id);if(h){const e=function({text:e,courseSubject:t}){return ke.test(e)?{id:"generated-concept-model",templates:["concept-field"],reason:"The lesson will be generated as an interactive 3D relationship model."}:xe.test(t)?{id:"generated-terrain-model",templates:["terrain"],reason:"The lesson will be generated as a course-specific 3D terrain model."}:ve.test(`${t} ${e}`)?{id:"generated-history-model",templates:["timeline"],reason:"The lesson will be generated as a course-specific 3D historical model."}:{id:"generated-concept-model",templates:["concept-field"],reason:"The lesson will be generated as an interactive 3D model from its course content."}}({text:h,courseSubject:u});return be(e,e.id)}return{eligible:!1,confidence:"high",reasonCode:"missing-course-context",reason:"A lesson title, subject, or lesson content is required to generate a 3D model.",preferredTemplate:null,allowedTemplates:[],label:null,evidence:null,version:6}}const Ce={heading:{default:{label:"Discourse default",family:null},fraunces:{label:"Fraunces",family:"'Fraunces', Georgia, serif",gf:"Fraunces:opsz,[email protected],500;9..144,600;9..144,700"},playfair:{label:"Playfair Display",family:"'Playfair Display', Georgia, serif",gf:"Playfair+Display:wght@600;700"},lora:{label:"Lora",family:"'Lora', Georgia, serif",gf:"Lora:wght@600;700"},sora:{label:"Sora",family:"'Sora', sans-serif",gf:"Sora:wght@600;700"},bricolage:{label:"Bricolage Grotesque",family:"'Bricolage Grotesque', sans-serif",gf:"Bricolage+Grotesque:opsz,[email protected],600;12..96,700"},plexserif:{label:"IBM Plex Serif",family:"'IBM Plex Serif', Georgia, serif",gf:"IBM+Plex+Serif:wght@600;700"}},body:{default:{label:"Discourse default",family:null},newsreader:{label:"Newsreader",family:"'Newsreader', Georgia, serif",gf:"Newsreader:opsz,[email protected],400;6..72,600;6..72,700"},sourceserif:{label:"Source Serif 4",family:"'Source Serif 4', Georgia, serif",gf:"Source+Serif+4:opsz,[email protected],400;8..60,600;8..60,700"},literata:{label:"Literata",family:"'Literata', Georgia, serif",gf:"Literata:opsz,[email protected],400;7..72,600;7..72,700"},atkinson:{label:"Atkinson Hyperlegible",family:"'Atkinson Hyperlegible', sans-serif",gf:"Atkinson+Hyperlegible:wght@400;700"},nunito:{label:"Nunito Sans",family:"'Nunito Sans', sans-serif",gf:"Nunito+Sans:opsz,[email protected],400;6..12,600;6..12,700"},plexsans:{label:"IBM Plex Sans",family:"'IBM Plex Sans', sans-serif",gf:"IBM+Plex+Sans:wght@400;600;700"}}},Te={light:{bg:"#f9fafb",surface:"#ffffff",text:"#374151",heading:"#1a1a1a",accent:"#2563eb",link:"#2563eb",border:"#e5e7eb"},dark:{bg:"#020617",surface:"#0f172a",text:"#f1f5f9",heading:"#f8fafc",accent:"#3b82f6",link:"#60a5fa",border:"#1e293b"}},Pe={default:{label:"Discourse",tagline:"The classic app look",fonts:{heading:"default",body:"default"},light:Te.light,dark:Te.dark},manuscript:{label:"Manuscript",tagline:"Warm parchment & sepia ink",fonts:{heading:"fraunces",body:"newsreader"},light:{bg:"#f4eddd",surface:"#fdfaf1",text:"#43372a",heading:"#2c2318",accent:"#9a4a20",link:"#8a3d18",border:"#e3d7bc"},dark:{bg:"#181410",surface:"#241e17",text:"#e6dcc8",heading:"#f4ead6",accent:"#d98e54",link:"#e0a06b",border:"#3a3126"}},observatory:{label:"Observatory",tagline:"Deep ink & brass detail",fonts:{heading:"sora",body:"plexsans"},light:{bg:"#eef1f8",surface:"#ffffff",text:"#2b3550",heading:"#131b33",accent:"#2c418f",link:"#2c418f",border:"#d5dbeb"},dark:{bg:"#0a0f20",surface:"#131a31",text:"#c9d2ea",heading:"#eef1fb",accent:"#d9ab52",link:"#93a7ec",border:"#242e4e"}},botanist:{label:"Botanist",tagline:"Sage, moss & field notes",fonts:{heading:"lora",body:"sourceserif"},light:{bg:"#eef3ea",surface:"#fbfdf8",text:"#33402f",heading:"#1d2a1a",accent:"#3f6e4b",link:"#356146",border:"#d7e2cf"},dark:{bg:"#111611",surface:"#1a221a",text:"#d3ddce",heading:"#eef4ea",accent:"#8fbf99",link:"#a3ccab",border:"#2b352a"}},studio:{label:"Studio",tagline:"Terracotta & gallery white",fonts:{heading:"bricolage",body:"nunito"},light:{bg:"#faf6f1",surface:"#ffffff",text:"#403731",heading:"#221b16",accent:"#c25e33",link:"#ad4f28",border:"#ecdfd2"},dark:{bg:"#171210",surface:"#231b17",text:"#e8ddd4",heading:"#f7efe8",accent:"#e08b5f",link:"#e9a97f",border:"#3a2e27"}},blueprint:{label:"Blueprint",tagline:"Slate, grid lines & cyan",fonts:{heading:"plexserif",body:"plexsans"},light:{bg:"#eef2f5",surface:"#ffffff",text:"#31404c",heading:"#122430",accent:"#0e7290",link:"#0c647e",border:"#d7dfe6"},dark:{bg:"#0c1318",surface:"#15202a",text:"#c6d4dd",heading:"#ecf3f8",accent:"#4cc3e0",link:"#6fd0e8",border:"#243440"}}},Ie=["#2563eb","#7c3aed","#db2777","#dc2626","#ea580c","#ca8a04","#16a34a","#0d9488","#0284c7","#475569"],je={sm:{label:"Compact",scale:.94},md:{label:"Comfort",scale:1},lg:{label:"Large",scale:1.14}},ze={full:{label:"Full",width:"none"},comfortable:{label:"Reading",width:"46rem"},narrow:{label:"Narrow",width:"38rem"}},Le={theme:"default",headingFont:"default",bodyFont:"default",accent:null,textSize:"md",contentWidth:"full"};function _e(e){return!e||!(e.theme&&"default"!==e.theme||e.headingFont&&"default"!==e.headingFont||e.bodyFont&&"default"!==e.bodyFont||e.accent||e.textSize&&"md"!==e.textSize||e.contentWidth&&"full"!==e.contentWidth)}function Ne(e,t,i){var s;const n=null==e?void 0:e["heading"===i?"headingFont":"bodyFont"];
1if(n&&"default"!==n&&Ce[i][n])return n;const a=null==(s=null==t?void 0:t.fonts)?void 0:s[i];return a&&"default"!==a&&Ce[i][a]?a:null}function Re(e){var t,i,s,n;if(_e(e))return null;const a=Pe[e.theme]||Pe.default,r=o({},a.light),l=o({},a.dark);e.accent&&(r.accent=e.accent,r.link=e.accent,l.accent=e.accent,l.link=e.accent);const c={"--course-bg":r.bg,"--course-surface":r.surface,"--course-text":r.text,"--course-heading":r.heading,"--course-accent":r.accent,"--course-link":r.link,"--course-border":r.border,"--course-bg-dark":l.bg,"--course-surface-dark":l.surface,"--course-text-dark":l.text,"--course-heading-dark":l.heading,"--course-accent-dark":l.accent,"--course-link-dark":l.link,"--course-border-dark":l.border,"--course-font-scale":String(null!=(i=null==(t=je[e.textSize])?void 0:t.scale)?i:1),"--course-max-width":null!=(n=null==(s=ze[e.contentWidth])?void 0:s.width)?n:"none"},u=Ne(e,a,"heading"),h=Ne(e,a,"body");return u&&(c["--course-heading-font"]=Ce.heading[u].family),h&&(c["--course-body-font"]=Ce.body[h].family),c}const Me=new Set;function $e(e){const t=e.filter(e=>e&&!Me.has(e));if(!t.length||"undefined"==typeof document)return;t.forEach(e=>Me.add(e));const i=document.createElement("link");i.rel="stylesheet",i.href=`https://fonts.googleapis.com/css2?${t.map(e=>`family=${e}`).join("&")}&display=swap`,document.head.appendChild(i)}function Ae(e){if(_e(e))return;const t=Pe[e.theme]||Pe.default,i=[],s=Ne(e,t,"heading"),n=Ne(e,t,"body");s&&i.push(Ce.heading[s].gf),n&&i.push(Ce.body[n].gf),$e(i)}function Oe(){$e([...Object.values(Ce.heading).map(e=>e.gf).filter(Boolean),...Object.values(Ce.body).map(e=>e.gf).filter(Boolean)])}export{de as A,me as C,Le as D,ne as F,W as I,D as L,C as S,je as T,Se as a,re as b,z as c,I as d,ae as e,Oe as f,q as g,Pe as h,he as i,Ce as j,Ie as k,j as l,ze as m,Re as n,Ae as o,ie as p,se as q,fe as r,ue as s,T as t};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.