<script lang="ts">
    import pdfjsLib from "pdfjs-dist";
    pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.jsdelivr.net/npm/pdfjs-dist/build/pdf.worker.min.js";

    let pdfDoc;
    let numPages = 1;
    let currentPage = 1;
    let canvasRef;
    export let value;

    async function loadPDF(value) {
        const loadingTask = pdfjsLib.getDocument(value.url);
        pdfDoc = await loadingTask.promise;
        numPages = pdfDoc.numPages;
        currentPage = 1;
        renderPage();
    }

    function renderPage() {
        pdfDoc.getPage(currentPage).then((page) => {
            const viewport = page.getViewport({ scale: 1.5 });
            const canvasContext = canvasRef.getContext("2d");
            canvasRef.width = viewport.width;
            canvasRef.height = viewport.height;

            page.render({
                canvasContext,
                viewport,
            });
        });
    }

    function nextPage() {
        if (currentPage < numPages) {
            currentPage++;
            renderPage();
        }
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            renderPage();
        }
    }

    $: if (value?.url) {
        loadPDF(value);
    }
</script>

<div>
    <div class="pdf-viewer">
        <canvas bind:this={canvasRef}></canvas>
    </div>
    <div class="controls">
        <button on:click={prevPage} disabled={currentPage === 1}>⬅️ Anterior</button>
        <span>{currentPage} / {numPages}</span>
        <button on:click={nextPage} disabled={currentPage === numPages}>Siguiente ➡️</button>
    </div>
</div>

<style>
    .pdf-viewer {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 500px;
    }
    .controls {
        display: flex;
        justify-content: center;
        gap: 10px;
        margin-top: 10px;
    }
</style>