import {baseLabs} from './labs.js';
import {advancedLabs} from './labs-advanced.js';
const labs={...baseLabs,...advancedLabs};
for(const root of document.querySelectorAll('[data-lab]')){
 try{const mount=labs[root.dataset.lab];if(!mount)throw Error('Unknown laboratory');mount(root);}
 catch(err){root.textContent='The laboratory could not initialize: '+err.message;root.setAttribute('role','alert');}
}
const menu=document.querySelector('#menu-toggle'),sidebar=document.querySelector('#sidebar');
menu?.addEventListener('click',()=>{const open=menu.getAttribute('aria-expanded')!=='true';menu.setAttribute('aria-expanded',String(open));menu.setAttribute('aria-label',open?'Close chapter navigation':'Open chapter navigation');sidebar.classList.toggle('open',open);});
document.addEventListener('keydown',e=>{if(e.key==='Escape'){menu?.setAttribute('aria-expanded','false');sidebar?.classList.remove('open');}});
const key='qc26-reading-v1',read=()=>{try{return JSON.parse(localStorage.getItem(key))||{done:[],last:''};}catch{return {done:[],last:''};}},save=x=>{try{localStorage.setItem(key,JSON.stringify(x));}catch{}};
let progress=read();if(!Array.isArray(progress.done))progress.done=[];
const page=document.body.dataset.page,complete=document.querySelector('[data-complete]');
if(complete){progress.last=location.pathname;save(progress);}
function showProgress(){
 const count=progress.done.length,p=document.querySelector('#reading-progress'),label=document.querySelector('#progress-label');if(p)p.value=count;if(label)label.textContent=count+' of 25 chapters';
 for(const link of document.querySelectorAll('[data-chapter]')){const done=progress.done.includes(link.dataset.chapter);link.classList.toggle('done',done);if(done)link.setAttribute('title','Marked complete');else link.removeAttribute('title');}
 if(complete){const done=progress.done.includes(page);complete.textContent=done?'Chapter marked complete ✓':'Mark chapter complete';complete.setAttribute('aria-pressed',String(done));}
 const resume=document.querySelector('#resume-reading');if(resume&&/^\/chapters\/[a-z-]+\/$/.test(progress.last)){resume.href=progress.last;resume.hidden=false;}
}
complete?.addEventListener('click',()=>{progress.done=progress.done.includes(page)?progress.done.filter(x=>x!==page):[...progress.done,page];save(progress);showProgress();});
document.querySelector('#reset-progress')?.addEventListener('click',()=>{progress={done:[],last:''};save(progress);showProgress();const resume=document.querySelector('#resume-reading');if(resume)resume.hidden=true;});showProgress();
const input=document.querySelector('#book-search'),results=document.querySelector('#search-results');let indexPromise=null,timer=null,revision=0;
const escape=s=>s.replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
input?.addEventListener('input',()=>{
 clearTimeout(timer);const turn=++revision,q=input.value.trim().toLowerCase();if(q.length<2){results.hidden=true;results.innerHTML='';return;}
 timer=setTimeout(async()=>{try{
  indexPromise??=fetch('/search-index.json').then(r=>{if(!r.ok)throw Error('Search unavailable');return r.json();});const index=await indexPromise;if(turn!==revision)return;
  const words=q.split(/\s+/),matches=index.map(x=>({...x,hay:(x.title+' '+x.chapter+' '+x.text).toLowerCase()})).filter(x=>words.every(w=>x.hay.includes(w))).sort((a,b)=>Number(b.title.toLowerCase().includes(q))-Number(a.title.toLowerCase().includes(q))).slice(0,15);
  results.hidden=false;results.innerHTML='<p class="search-status">'+(matches.length?matches.length+' matching sections':'No matching sections')+'</p>'+matches.map(x=>{const p=x.text.toLowerCase().indexOf(words[0]),start=Math.max(0,p-35),snippet=x.text.slice(start,start+140);return '<a href="'+x.url+'"><strong>'+escape(x.title)+'</strong><small>'+escape(x.chapter)+'</small><span>'+(start?'…':'')+escape(snippet)+'…</span></a>';}).join('');
 }catch{if(turn===revision){results.hidden=false;results.textContent='Search could not load. The chapter navigation remains available.';indexPromise=null;}}},160);
});
