if(!new URLSearchParams(location.search).has('accountEmbed')&&/^#\/pages\/(my|profile|coupons|settings)\/index$/.test(location.hash)){const key=location.hash.split('/')[2];location.replace('/account/#'+({my:'courses',profile:'profile',coupons:'coupons',settings:'settings'}[key]));}
if(new URLSearchParams(location.search).has('accountEmbed'))document.documentElement.classList.add('account-embedded');
import {renderMyCourses} from '/my-courses-desktop.js';
if (/^#\/pages\/(?:login|register)\/index(?:[?]|$)/.test(location.hash)) location.replace('/auth/');
import {cloudCall,temporaryURLs} from './api.js';import {parseTemplate,renderTemplate,patch} from './renderer.js';
const source=window.MINI_SOURCE,root=document.querySelector('#mini-root'),cache={},files=new Map();let page,template,scheduled=false,epoch=0;
function toast(message){const el=document.querySelector('#toast');el.textContent=message;el.hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>el.hidden=true,5000)}
function modal(o){return new Promise(resolve=>{const d=document.querySelector('#modal');d.classList.toggle('purchase-unlock-modal',o.title==='购买后解锁');d.setAttribute('aria-label',o.title||'提示');d.querySelector('h2').textContent=o.title||'提示';d.querySelector('p').textContent=o.content||'';const cancel=d.querySelector('#modal-cancel'),ok=d.querySelector('#modal-confirm');cancel.hidden=o.showCancel===false;ok.textContent=o.confirmText||'确定';cancel.textContent=o.cancelText||'取消';const finish=confirm=>{d.close();const r={confirm,cancel:!confirm};o.success?.(r);resolve(r)};ok.onclick=()=>finish(true);cancel.onclick=()=>finish(false);d.oncancel=e=>{e.preventDefault();finish(false)};if(!d.open)d.showModal()})}
function route(o,replace=false){const url=o.url||'/pages/home/index';if(/^\/pages\/(login|register)\/index/.test(url)){sessionStorage.setItem('laiyao:loginReturn',location.pathname+location.search+location.hash);location.assign('/auth/?returnTo='+encodeURIComponent(location.pathname+location.search+location.hash));return;}const target=window.laiyaoDestination?.('/learning#'+url);if(target&&target.pathname!=='/learning'&&!new URLSearchParams(location.search).has('accountEmbed')){location.assign(target.href);o.success?.({});return}if(!/^\/pages\/[\w/-]+(?:\?.*)?$/.test(url))return toast('页面地址无效');if(replace)location.replace('#'+url);else location.hash=url;o.success?.({});}
function complete(o,fn){return Promise.resolve().then(fn).then(r=>{o.success?.(r);o.complete?.(r);return r},e=>{o.fail?.(e);o.complete?.(e);if(!o.fail)throw e});}
const fs={readFile:o=>complete(o,async()=>{const file=files.get(o.filePath);if(!file)throw Error('文件不可用');return {data:await file.slice(o.position||0,o.length?(o.position||0)+o.length:undefined).arrayBuffer()}}),unlink:o=>{if(o.filePath?.startsWith('blob:'))URL.revokeObjectURL(o.filePath);files.delete(o.filePath);o.success?.({})},writeFile:o=>complete(o,()=>{files.set(o.filePath,new Blob([o.data]));return{}})};
const wx={cloud:{init(){},callFunction:async({name,data})=>({result:await cloudCall(name,data)}),getTempFileURL:temporaryURLs},env:{USER_DATA_PATH:'/virtual'},
 getStorageSync:key=>{try{return JSON.parse(sessionStorage.getItem('laiyao:'+key)||'null')}catch{return null}},setStorageSync:(key,value)=>sessionStorage.setItem('laiyao:'+key,JSON.stringify(value)),removeStorageSync:key=>sessionStorage.removeItem('laiyao:'+key),
 showToast:o=>toast(o.title),showModal:modal,showLoading:o=>toast(o.title||'处理中…'),hideLoading:()=>document.querySelector('#toast').hidden=true,
 navigateTo:route,redirectTo:o=>route(o,true),switchTab:route,navigateBack:()=>history.length>1?history.back():route({url:'/pages/home/index'}),
 setNavigationBarTitle:o=>{o={...o,title:String(o.title||'').replaceAll('自学专区','学习中心')};document.querySelector('#page-title').textContent=o.title;document.title=o.title+' · 莱矅智能'},
 getSystemInfoSync:()=>({platform:'web',system:'Browser',windowWidth:root.clientWidth,windowHeight:innerHeight,screenWidth:screen.width,screenHeight:screen.height,pixelRatio:devicePixelRatio}),getWindowInfo:()=>wx.getSystemInfoSync(),getDeviceInfo:()=>wx.getSystemInfoSync(),
 showShareMenu(){},stopPullDownRefresh(){},pageScrollTo:o=>window.scrollTo({top:o.scrollTop||0,behavior:'smooth'}),
 setClipboardData:o=>complete(o,async()=>{await navigator.clipboard.writeText(o.data);toast('已复制');return{}}),
 openCustomerServiceSession:o=>complete(o,()=>{if(o.extInfo?.url&&/^https:\/\//.test(o.extInfo.url))window.open(o.extInfo.url,'_blank','noopener');else throw Error('请通过联系页面咨询');return{}}),
 showActionSheet:o=>modal({title:'请选择',content:o.itemList.map((s,i)=>`${i+1}. ${s}`).join('\n')}).then(r=>{if(r.confirm){const n=prompt('请输入选项序号');if(n!==null&&Number(n)>0&&Number(n)<=o.itemList.length)o.success?.({tapIndex:Number(n)-1});else o.fail?.(Error('已取消'))}}),
 chooseMessageFile:o=>complete(o,()=>new Promise((resolve,reject)=>{const input=document.createElement('input');input.type='file';input.accept=(o.extension||[]).map(x=>'.'+x).join(',');input.onchange=()=>{const f=input.files[0];if(!f)return reject(Error('未选择文件'));const path=URL.createObjectURL(f);files.set(path,f);resolve({tempFiles:[{name:f.name,path,size:f.size,tempFilePath:path}]})};input.oncancel=()=>reject(Error('已取消选择'));input.click()})),
 getFileSystemManager:()=>fs,getFileInfo:o=>complete(o,()=>({size:files.get(o.filePath)?.size||0})),
 uploadFile:o=>complete(o,async()=>{const body=new FormData();for(const[k,v]of Object.entries(o.formData||{}))body.append(k,v);const f=files.get(o.filePath);if(!f)throw Error('文件不存在，请重新选择');body.append(o.name||'file',f,f.name||'upload');const local=new URL(o.url,location.href).origin===location.origin&&new URL(o.url,location.href).pathname==='/practicum-files/upload';const r=await fetch(o.url,{method:'POST',body:local?f:body,...(local?{headers:{'Content-Type':'application/octet-stream'}}:{})});return {statusCode:r.status,data:await r.text()}}),
 request:o=>complete(o,async()=>{const response=await fetch(o.url,{method:o.method||'GET',headers:new URL(o.url,location.href).origin===location.origin&&new URL(o.url,location.href).pathname==='/practicum-files/part'?{...o.header,'Content-Type':'application/octet-stream'}:o.header,body:['GET','HEAD'].includes(o.method||'GET')?undefined:typeof o.data==='object'&&!(o.data instanceof ArrayBuffer)&&!(o.data instanceof Blob)?JSON.stringify(o.data):o.data});const data=o.responseType==='arraybuffer'?await response.arrayBuffer():await response.text();return{statusCode:response.status,data}}),
 downloadFile:o=>complete(o,async()=>{const r=await fetch(o.url);if(!r.ok)throw Error('下载失败');const blob=await r.blob(),url=URL.createObjectURL(blob);files.set(url,blob);return{statusCode:r.status,tempFilePath:url}}),
 openDocument:o=>complete(o,()=>{const url=files.has(o.filePath)?URL.createObjectURL(files.get(o.filePath)):o.filePath;if(!/^(blob:|https?:)/.test(url))throw Error('文件地址无效');window.open(url,'_blank','noopener');return{}}),
 previewImage:o=>{const u=o.current||o.urls?.[0];if(u&&/^(https?:|blob:|data:image\/)/.test(u))window.open(u,'_blank','noopener')},previewMedia:o=>wx.previewImage({urls:o.sources.map(s=>s.url)}),shareFileMessage:o=>wx.openDocument(o),
 createVideoContext:()=>({play:()=>root.querySelector('video')?.play().catch(()=>toast('请点击播放器开始播放')),pause:()=>root.querySelector('video')?.pause(),seek:n=>{const v=root.querySelector('video');if(v)v.currentTime=n},requestFullScreen:()=>{const shell=root.querySelector('.video-shell'),video=shell?.querySelector('video');if(shell?.requestFullscreen)shell.requestFullscreen().catch(()=>{if(video?.webkitEnterFullscreen)video.webkitEnterFullscreen();else toast('请使用播放器自带的全屏按钮')});else if(video?.webkitEnterFullscreen)video.webkitEnterFullscreen();else toast('请使用播放器自带的全屏按钮')},exitFullScreen:()=>document.exitFullscreen()}),
 createSelectorQuery(){let selector='',fields={};const q={in:()=>q,select:s=>(selector=s,q),fields:f=>(fields=f,q),boundingClientRect:cb=>(q.cb=cb,q),exec:cb=>{requestAnimationFrame(()=>{const n=root.querySelector(selector);if(n?.tagName==='CANVAS')n.createImage=()=>new Image();const rect=n?.getBoundingClientRect();const r=n?{node:n,width:rect.width,height:rect.height,...rect}:null;q.cb?.(r);cb?.([r])})}};return q},
 canvasToTempFilePath:o=>complete(o,()=>{const c=o.canvas||root.querySelector('#'+o.canvasId);if(!c)throw Error('画布不可用');return{tempFilePath:c.toDataURL('image/png')}}),
 createCanvasContext(id){const c=root.querySelector('#'+id);if(!c)return{};c.width=600;c.height=420;const ctx=c.getContext('2d');return new Proxy(ctx,{get(target,k){if(k==='setFillStyle')return v=>target.fillStyle=v;if(k==='setStrokeStyle')return v=>target.strokeStyle=v;if(k==='setFontSize')return v=>target.font=v+'px sans-serif';if(k==='setTextAlign')return v=>target.textAlign=v;if(k==='draw')return(_,cb)=>cb?.();const v=target[k];return typeof v==='function'?v.bind(target):v}})}
};
window.wx=wx;window.getCurrentPages=()=>page?[page]:[];window.getApp=()=>({globalData:{cloudReady:true}});
function normalize(from,request){const parts=(from.slice(0,from.lastIndexOf('/')+1)+request).split('/'),out=[];for(const p of parts){if(p==='.'||!p)continue;if(p==='..')out.pop();else out.push(p)}return out.join('/')+(request.endsWith('.js')?'':'.js')}
function requireModule(name){if(cache[name])return cache[name].exports;const code=source.modules[name];if(code===undefined)throw Error('模块不存在：'+name);const module={exports:{}};cache[name]=module;new Function('require','module','exports','Page','App','wx','getApp','getCurrentPages',code+'\n//# sourceURL=/learning/source/'+name)(request=>requireModule(normalize(name,request)),module,module.exports,p=>{page=p},()=>{},wx,window.getApp,window.getCurrentPages);return module.exports;}
function schedule(){if(scheduled)return;scheduled=true;queueMicrotask(()=>{scheduled=false;if(!page||!template)return;try{if(root.dataset.page==='pages/my/index'){renderMyCourses(root,page.data.myCourses||[]);return;}patch(root,renderTemplate(template,page.data,(name,e)=>{if(name==='__wechatOnly')return modal({title:'电脑端登录',content:'请使用手机号与密码或短信验证码登录。浏览器不提供微信小程序手机号授权。',showCancel:false});try{Promise.resolve(page[name]?.call(page,e)).catch(err=>toast(err.message||'操作未完成'))}catch(err){toast(err.message||'操作未完成')}}))}catch(e){toast('页面渲染失败，请刷新后重试');console.error(e)}})}
async function navigate(){const destination=window.laiyaoDestination?.(location.href);if(destination&&destination.href!==location.href){location.replace(destination.href);return;}if(/^#\/pages\/(?:login|register)\/index(?:[?]|$)/.test(location.hash)){location.replace('/auth/?returnTo='+encodeURIComponent(sessionStorage.getItem('laiyao:loginReturn')||'/academy/'));return;}const mine=++epoch;page?.onHide?.();page?.onUnload?.();const raw=location.hash.slice(1)||'/pages/home/index';const [pathname,query='']=raw.split('?');if(window.LAIYAO_CONFIG.localMode&&/^\/pages\/(interview|interview-questions|exam|exam-papers|exam-do)\/index$/.test(pathname)){location.replace('/question-center/?mode='+ (pathname.includes('/exam')?'exam':'interview'));return;}const key=pathname.replace(/^\//,'');const info=source.pages[key];document.body.classList.toggle('practicum-workspace', /^pages\/(practicum-(campus|enterprise)|school-(cooperation|portal|training|training-task|training-report))\/index$/.test(key));root.dataset.page=key;root.replaceChildren();if(!info||key==='pages/admin/index'||key==='pages/cloud-init/index'){root.textContent='该页面不可用，请通过左侧导航继续。';return}delete cache[key+'.js'];try{requireModule(key+'.js');page.data=structuredClone(page.data||{});const current=page;page.setData=(values,callback)=>{for(const [key,value]of Object.entries(values)){const parts=key.replace(/\[(\d+)\]/g,'.$1').split('.');let at=current.data;for(const p of parts.slice(0,-1))at=at[p]??=(/^\d+$/.test(parts[parts.indexOf(p)+1])?[]:{});at[parts.at(-1)]=value;}if(current===page)schedule();if(callback)queueMicrotask(callback)};template=parseTemplate(info.template.replaceAll('自学专区','学习中心'));document.querySelector('#mini-style').textContent='';wx.setNavigationBarTitle({title:info.config.navigationBarTitleText||'学习平台'});document.querySelectorAll('.learn-sidebar a').forEach(a=>a.classList.toggle('active',a.hash==='#'+pathname));schedule();await page.onLoad?.(Object.fromEntries(new URLSearchParams(query)));if(mine!==epoch)return;await page.onShow?.();window.scrollTo(0,0)}catch(e){root.textContent='页面加载失败：'+e.message;console.error(e)}}
document.querySelector('#mini-global').textContent='';document.querySelector('#back').onclick=()=>wx.navigateBack();document.querySelector('#refresh').onclick=()=>navigate();window.addEventListener('hashchange',navigate);window.addEventListener('pagehide',()=>{page?.onHide?.();page?.onUnload?.()});window.addEventListener('resize',()=>page?.onResize?.());document.addEventListener('fullscreenchange',()=>page?.handleWatermarkFullscreen?.({detail:{fullScreen:!!document.fullscreenElement,direction:'horizontal'}}));
if(window.LAIYAO_CONFIG.localMode)document.querySelector('#connection-status').textContent='本地预览环境 · 个人学习与实训操作需登录，内容以当前环境的授权为准。';
else if(!window.LAIYAO_CONFIG.env||!window.LAIYAO_CONFIG.gatewayEnabled)document.querySelector('#connection-status').textContent='独立环境待配置：官网界面可预览，课程和个人数据尚未连接。不会读取原小程序的数据。';
setInterval(()=>{for(const s of root.querySelectorAll('.swiper-web')){const nodes=[...s.children];if(nodes.length<2)continue;const active=nodes.findIndex(n=>n.style.display==='block');nodes.forEach((n,i)=>n.style.display=i===(active+1)%nodes.length?'block':'none')}},5000);
await navigate();
