<!DOCTYPE html>
<html lang="ar">
<head>
<meta charset="UTF-8">
<title>PDF Viewer</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background-color: #f8f9fa; }
#toolbar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 15px; align-items: center; }
#toolbar button { background-color: #007bff; color: #fff; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; }
#toolbar button:hover { background-color: #0056b3; }
#toolbar input { font-size: 14px; margin-left: 5px; width: 50px; }
#viewerWrapper { display: flex; height: 80vh; border: 1px solid #dee2e6; background-color: #fff; border-radius: 5px; overflow: hidden; /* لا نسمح للـ wrapper بأن يسرق scroll */ box-shadow: 0 2px 6px rgba(0,0,0,0.1); }
#previewBar { width: 140px; height: 100%; overflow-y: auto; padding: 10px; background-color: #f1f3f5; display: flex; flex-direction: column; align-items: center; flex-shrink: 0; /* مهم: لا يقل حجمه */ }
#viewerContainer { flex: 1; overflow-y: auto; /* scroll مستقل للـ pages فقط */ display: flex; justify-content: center; align-items: flex-start; padding: 10px; }
.preview-canvas { display: block; margin-bottom: 8px; cursor: pointer; border: 1px solid #ced4da; border-radius: 3px; }
.preview-canvas:hover { border-color: #007bff; }
.preview-canvas.current { border: 2px solid #007bff; box-shadow: 0 0 8px rgba(0,123,255,0.5); }
#singlePageWrapper, #allPagesWrapper { width: 100%; display: flex; justify-content: center; align-items: flex-start; flex-wrap: wrap; }
.pageWrapper { position: relative; margin: 5px; display: flex; justify-content: center; }
#pdfCanvas, .allPageCanvas { display: block; width: unset; height: max-content; border-radius: 4px; box-shadow: 0 1px 4px rgba(0,0,0,0.1); }
</style>
</head>
<body>

<div id="toolbar">
    <button onclick="prevPage()">◀</button>
    <span>Page: <input type="number" id="pageInput" value="1" min="1" onchange="goToPage(this.value)"> / <span id="pageCount">--</span></span>
    <button onclick="nextPage()">▶</button>
    <button onclick="zoomOut()">-</button>
    <input type="number" id="zoomInput" value="100" onchange="setZoom(this.value)">
    <button onclick="zoomIn()">+</button>
    <button onclick="rotatePages()">⟳</button>
    <button onclick="toggleView()">Single / All</button>
    <!-- <button onclick="downloadPDF()">⬇</button>
    <button onclick="printPDF()">🖨</button> -->
    
</div>

<div id="viewerWrapper">
    <div id="previewBar"></div>
    <div id="viewerContainer">
        <div id="singlePageWrapper"><canvas id="pdfCanvas"></canvas></div>
        <div id="allPagesWrapper" style="display:none;"></div>
    </div>
</div>

<script>
var pdfUrl = "{$pdfPath}";
</script>

{literal}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js";

var pdfDoc=null, rotation=0, currentPage=1, viewMode="single";
var singleScale=1.0, allPagesScale=1.0;
var canvases=[], previewCanvases=[];
var singleWrapper=document.getElementById("singlePageWrapper");
var allPagesWrapper=document.getElementById("allPagesWrapper");
var container=document.getElementById("viewerContainer");
var singleCanvas=document.getElementById("pdfCanvas");
var ctx=singleCanvas.getContext("2d");
var previewBar=document.getElementById("previewBar");
var allPagesScrollListenerAdded = false;

// تحميل PDF
pdfjsLib.getDocument(pdfUrl).promise.then(function(pdf){
    pdfDoc = pdf;
    document.getElementById("pageCount").textContent = pdfDoc.numPages;
    document.getElementById("pageInput").max = pdfDoc.numPages;
    renderPreviewBar();
    renderSinglePage(currentPage);
});

// Single Page View
function renderSinglePage(num){
    viewMode = "single";
    singleWrapper.style.display = "flex";
    allPagesWrapper.style.display = "none";
    pdfDoc.getPage(num).then(function(page){
        var viewport = page.getViewport({scale:singleScale, rotation:rotation});
        singleCanvas.width = viewport.width;
        singleCanvas.height = viewport.height;
        page.render({canvasContext: ctx, viewport: viewport});
        currentPage = num;
        document.getElementById("pageInput").value = currentPage;
        updatePreviewHighlight();
    });
}

// All Pages View
function renderAllPages(){
    viewMode="all";
    singleWrapper.style.display="none";
    allPagesWrapper.style.display="flex";
    allPagesWrapper.innerHTML="";
    canvases=[];
    allPagesScrollListenerAdded = false;

    let promises = [];
    for(let i=1;i<=pdfDoc.numPages;i++){
        promises.push(
            pdfDoc.getPage(i).then(function(page){
                let viewport = page.getViewport({scale:allPagesScale, rotation:rotation});
                let wrapper = document.createElement("div");
                wrapper.className="pageWrapper";
                wrapper.style.flex=`1 1 100%`; 
                wrapper.style.display="flex"; 
                wrapper.style.justifyContent="center"; 
                let canvas = document.createElement("canvas");
                canvas.className="allPageCanvas";
                canvas.width = viewport.width;
                canvas.height = viewport.height;
                wrapper.appendChild(canvas);
                allPagesWrapper.appendChild(wrapper);
                page.render({canvasContext:canvas.getContext("2d"), viewport:viewport});
                canvases[i-1] = canvas;
            })
        );
    }

    Promise.all(promises).then(() => {
        scrollToPage(currentPage);
        setTimeout(initScrollListener, 50); 
    });
}

// Zoom ±10%
function zoomIn(){ if(viewMode==="single"){ singleScale += 0.1; renderSinglePage(currentPage); } else { allPagesScale += 0.1; redrawAllPages(); } updateZoomInput(); }
function zoomOut(){ if(viewMode==="single"){ singleScale = Math.max(0.1, singleScale-0.1); renderSinglePage(currentPage); } else { allPagesScale = Math.max(0.1, allPagesScale-0.1); redrawAllPages(); } updateZoomInput(); }
function setZoom(value){ let scale = parseFloat(value)/100; if(viewMode==="single"){ singleScale = scale; renderSinglePage(currentPage); } else { allPagesScale = scale; redrawAllPages(); } }
function updateZoomInput(){ document.getElementById("zoomInput").value = Math.round((viewMode==="single"?singleScale:allPagesScale)*100); }
function rotatePages(){ rotation = (rotation+90)%360; if(viewMode==="single") renderSinglePage(currentPage); else redrawAllPages(); }
function redrawAllPages(){ for(let i=1;i<=pdfDoc.numPages;i++){ pdfDoc.getPage(i).then(function(page){ var canvas = canvases[i-1]; if(canvas){ var viewport = page.getViewport({scale:allPagesScale, rotation:rotation}); canvas.width = viewport.width; canvas.height = viewport.height; page.render({canvasContext: canvas.getContext("2d"), viewport: viewport}); } }); } }

// Scroll listener
function initScrollListener(){
    if(allPagesScrollListenerAdded) return;
    allPagesScrollListenerAdded = true;
    container.addEventListener('scroll', function(){
        if(viewMode !== 'all') return;
        let containerRect = container.getBoundingClientRect();
        let midline = containerRect.top + container.clientHeight / 2;
        for (let i = 0; i < canvases.length; i++) {
            let canvas = canvases[i];
            let rect = canvas.getBoundingClientRect();
            if(midline >= rect.top && midline <= rect.bottom){
                if(currentPage !== i + 1){
                    currentPage = i + 1;
                    document.getElementById("pageInput").value = currentPage;
                    updatePreviewHighlight();
                }
                break;
            }
        }
    });
}

// Highlight current preview and center in preview bar
function updatePreviewHighlight(){
    previewCanvases.forEach((canvas, index) => {
        if(index === currentPage - 1){
            canvas.classList.add('current');
            let previewHeight = previewBar.clientHeight;
            let canvasOffset = canvas.offsetTop;
            let canvasHeight = canvas.offsetHeight;
            let scrollTop = canvasOffset - (previewHeight/2) + (canvasHeight/2);
            previewBar.scrollTo({ top: scrollTop, behavior: 'smooth' });
        } else {
            canvas.classList.remove('current');
        }
    });
}

// Pagination
function scrollToPage(pageNum){ let canvas = canvases[pageNum-1]; if(canvas){ canvas.scrollIntoView({behavior:"smooth", block:"start"}); currentPage = pageNum; document.getElementById("pageInput").value = currentPage; updatePreviewHighlight(); } }
function nextPage(){ if(viewMode==="single" && currentPage<pdfDoc.numPages){currentPage++; renderSinglePage(currentPage);} else if(viewMode==="all" && currentPage<pdfDoc.numPages){currentPage++; scrollToPage(currentPage);} }
function prevPage(){ if(viewMode==="single" && currentPage>1){currentPage--; renderSinglePage(currentPage);} else if(viewMode==="all" && currentPage>1){currentPage--; scrollToPage(currentPage);} }
function goToPage(value){ let pageNum = parseInt(value); if(isNaN(pageNum) || pageNum < 1 || pageNum > pdfDoc.numPages) return; currentPage = pageNum; if(viewMode==="single"){ renderSinglePage(currentPage);} else {scrollToPage(currentPage);} }

// Toggle View
function toggleView(){
    if(viewMode === "single"){
        if(allPagesWrapper.children.length === 0){
            renderAllPages();
        } else {
            viewMode = "all";
            singleWrapper.style.display = "none";
            allPagesWrapper.style.display = "flex";
            updatePreviewHighlight();
        }
    } else {
        renderSinglePage(currentPage);
    }
}

// Preview Bar
function renderPreviewBar(){ 
    previewBar.innerHTML=""; 
    for(let i=1;i<=pdfDoc.numPages;i++){ 
        let pageIndex=i; 
        pdfDoc.getPage(pageIndex).then(function(page){ 
            let viewport=page.getViewport({scale:0.2}); 
            let canvas=document.createElement("canvas"); 
            canvas.width=viewport.width; canvas.height=viewport.height; 
            canvas.className="preview-canvas"; 
            canvas.addEventListener("click",function(){ 
                currentPage=pageIndex; 
                if(viewMode==="single") renderSinglePage(currentPage); 
                else scrollToPage(currentPage); 
            }); 
            page.render({canvasContext:canvas.getContext("2d"), viewport:viewport}); 
            previewBar.appendChild(canvas); 
            previewCanvases[pageIndex-1]=canvas; 
        }); 
    } 
}

// Download & Print
function downloadPDF(){ var link=document.createElement("a"); link.href=pdfUrl; link.download="document.pdf"; document.body.appendChild(link); link.click(); document.body.removeChild(link); }
function printPDF(){ var printWindow=window.open(pdfUrl,"_blank"); printWindow.focus(); printWindow.print(); }
</script>
{/literal}
</body>
</html>
