(function ($) {
    var SifencyPDFHandler = function ($scope, $) {
        var $wrapper = $scope.find('.sifency-pdf-wrapper');
        if (!$wrapper.length) return;

        var url = $wrapper.data('pdf-url');
        var initialScale = $wrapper.data('pdf-scale');
        
        var canvas = $wrapper.find('.sifency-pdf-canvas')[0];
        var ctx = canvas.getContext('2d');
        var $loader = $wrapper.find('.sifency-pdf-loader');
        var $pageInfo = $wrapper.find('.sifency-pdf-page-info');
        var $currPage = $wrapper.find('.sifency-pdf-curr-page');
        var $totalPage = $wrapper.find('.sifency-pdf-total-page');

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            scale = 1.0,
            canvasContainer = $wrapper.find('.sifency-pdf-canvas-container');


        function renderPage(num) {
            pageRendering = true;
            $loader.show();

            pdfDoc.getPage(num).then(function (page) {
                var viewport = page.getViewport({ scale: 1 });
                
                var containerWidth = canvasContainer.width();
                var computedScale = 1;

                if (initialScale === 'page-width' || initialScale === 'page-fit') {
                   computedScale = (containerWidth - 20) / viewport.width; 
                   scale = computedScale;
                } else if(initialScale === 'page-actual') {
                   scale = 1;
                }
                
                viewport = page.getViewport({ scale: scale });

                canvas.height = viewport.height;
                canvas.width = viewport.width;

                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                
                var renderTask = page.render(renderContext);

                renderTask.promise.then(function () {
                    pageRendering = false;
                    $loader.hide();
                    if (pageNumPending !== null) {
                        renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

            $currPage.text(num);
        }

        function queueRenderPage(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                renderPage(num);
            }
        }

        function onPrevPage() {
            if (pageNum <= 1) return;
            pageNum--;
            queueRenderPage(pageNum);
        }

        function onNextPage() {
            if (pageNum >= pdfDoc.numPages) return;
            pageNum++;
            queueRenderPage(pageNum);
        }
        
        function onZoomIn() {
            scale += 0.2;
            initialScale = 'custom';
            queueRenderPage(pageNum);
        }

        function onZoomOut() {
            if(scale <= 0.4) return;
            scale -= 0.2;
            initialScale = 'custom';
            queueRenderPage(pageNum);
        }

        if (typeof pdfjsLib !== 'undefined') {
            pdfjsLib.getDocument(url).promise.then(function (pdfDoc_) {
                pdfDoc = pdfDoc_;
                $totalPage.text(pdfDoc.numPages);
                renderPage(pageNum);
            }).catch(function(error) {
                $loader.html('<p style="color:#fff; padding:20px;">Error loading PDF.<br/>'+error.message+'</p>');
                console.error('Error loading PDF:', error);
            });
        } else {
            console.error('PDF.js library not loaded');
        }

        $wrapper.find('.sifency-pdf-prev').on('click', onPrevPage);
        $wrapper.find('.sifency-pdf-next').on('click', onNextPage);
        $wrapper.find('.sifency-pdf-zoom-in').on('click', onZoomIn);
        $wrapper.find('.sifency-pdf-zoom-out').on('click', onZoomOut);
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-pdf-viewer.default', SifencyPDFHandler);
    });

})(jQuery);