import * as pdfjs from './pdfjs/pdf.min.mjs';
pdfjs.GlobalWorkerOptions.workerSrc='./pdfjs/pdf.worker.min.mjs';
const $=s=>document.querySelector(s),params=new URLSearchParams(location.search),raw=params.get('file')||'',base=new URL('.',location.href),file=new URL(raw,base);if(file.origin!==location.origin||!file.pathname.includes('/uploads/pdf/'))throw new Error('Blocked PDF path');if(params.get('print')!=='1')$('#print').remove();if(params.get('download')!=='1')$('#fallback').remove();
$('#fallback').href=file;let doc,page=+(localStorage.getItem('ef-pdf-'+file.pathname)||1),scale=1,rotation=0,rendering=false,pending=0;
async function render(n){if(!doc)return;if(rendering){pending=n;return}rendering=true;page=Math.max(1,Math.min(doc.numPages,n));const p=await doc.getPage(page),view=p.getViewport({scale:scale*1.35,rotation}),canvas=$('#pdf');canvas.width=view.width;canvas.height=view.height;await p.render({canvasContext:canvas.getContext('2d'),viewport:view}).promise;$('#page').value=page;$('#zoom').textContent=Math.round(scale*100)+'%';localStorage.setItem('ef-pdf-'+file.pathname,page);document.querySelectorAll('#thumbs canvas').forEach((x,i)=>x.classList.toggle('active',i===page-1));rendering=false;if(pending){const x=pending;pending=0;render(x)}}
async function thumbnails(){for(let n=1;n<=doc.numPages;n++){const p=await doc.getPage(n),v=p.getViewport({scale:.2}),c=document.createElement('canvas');c.width=v.width;c.height=v.height;c.title='Page '+n;c.onclick=()=>render(n);await p.render({canvasContext:c.getContext('2d'),viewport:v}).promise;$('#thumbs').append(c)}}
pdfjs.getDocument({url:file.href}).promise.then(async d=>{doc=d;$('#count').textContent=d.numPages;page=Math.min(page,d.numPages);$('#status').remove();await render(page);thumbnails();parent.examfitTrack?.('pdf_open',1,file.pathname)}).catch(e=>{$('#status').textContent='Unable to display this PDF. Use the direct-file fallback.'});
$('#prev').onclick=()=>render(page-1);$('#next').onclick=()=>render(page+1);$('#page').onchange=e=>render(+e.target.value);$('#in').onclick=()=>{scale=Math.min(3,scale+.15);render(page)};$('#out').onclick=()=>{scale=Math.max(.4,scale-.15);render(page)};$('#rotate').onclick=()=>{rotation=(rotation+90)%360;render(page)};$('#full').onclick=()=>document.documentElement.requestFullscreen?.();$('#print').onclick=()=>{parent.examfitTrack?.('pdf_print',1,file.pathname);window.print()};$('#thumbToggle').onclick=()=>$('#thumbs').classList.toggle('open');
$('#find').onclick=async()=>{const term=$('#search').value.trim().toLowerCase();if(!term)return;for(let n=page;n<=doc.numPages;n++){const text=(await (await doc.getPage(n)).getTextContent()).items.map(x=>x.str).join(' ');if(text.toLowerCase().includes(term)){render(n);$('#text').textContent='Found on page '+n+': '+text.slice(0,500);return}}$('#text').textContent='No match found from the current page.'};
