/**
 * PDF rendering with PDF.js for maca Restu (mobile-friendly)
 */
(function (window) {
    'use strict';

    var loadPromise = null;

    function getPdfConfig() {
        return window.macaMenulistPdfConfig || {};
    }

    function getPdfLibBase() {
        var config = getPdfConfig();
        if (config.pdfLibUrl) {
            return config.pdfLibUrl.replace(/pdf\.min\.js.*$/, '');
        }
        return 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/';
    }

    function ensureHttps(url) {
        if (!url) {
            return url;
        }
        if (window.location.protocol === 'https:' && url.indexOf('http://') === 0) {
            return 'https://' + url.substring(7);
        }
        return url;
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text == null ? '' : String(text);
        return div.innerHTML;
    }

    function loadLibrary() {
        if (window.pdfjsLib) {
            return Promise.resolve(window.pdfjsLib);
        }

        if (loadPromise) {
            return loadPromise;
        }

        loadPromise = new Promise(function (resolve, reject) {
            var config = getPdfConfig();
            var script = document.createElement('script');
            script.src = config.pdfLibUrl || getPdfLibBase() + 'pdf.min.js';
            script.onload = function () {
                window.pdfjsLib.GlobalWorkerOptions.workerSrc =
                    config.workerUrl || getPdfLibBase() + 'pdf.worker.min.js';
                resolve(window.pdfjsLib);
            };
            script.onerror = function () {
                loadPromise = null;
                reject(new Error('PDF.js failed to load'));
            };
            document.head.appendChild(script);
        });

        return loadPromise;
    }

    function iframeFallback(container, fileUrl, title) {
        fileUrl = ensureHttps(fileUrl);
        container.innerHTML =
            '<div class="maca-pdf-embed">' +
            '<iframe src="' +
            escapeHtml(fileUrl) +
            '#toolbar=0&navpanes=0" title="' +
            escapeHtml(title) +
            '" style="width:100%;height:90vh;min-height:400px;border:0;display:block;"></iframe>' +
            '</div>';
    }

    function render(container, fileUrl, title, options) {
        options = options || {};
        var config = getPdfConfig();
        var showTitle = false;
        if (Object.prototype.hasOwnProperty.call(options, 'showTitle')) {
            showTitle = !!options.showTitle;
        } else if (Object.prototype.hasOwnProperty.call(config, 'showMenuTitle')) {
            showTitle = !!config.showMenuTitle;
        }
        var scale = options.scale || (window.innerWidth < 600 ? 1.1 : 1.5);

        if (!container || !fileUrl) {
            return Promise.reject(new Error('Missing container or file URL'));
        }

        fileUrl = ensureHttps(fileUrl);

        var html =
            '<div class="maca-pdf-js-view">' +
            (showTitle && title ? '<h2 class="maca-menu-title">' + escapeHtml(title) + '</h2>' : '') +
            '<div class="maca-pdf-js-pages"><p class="maca-pdf-js-loading">' +
            escapeHtml(options.loadingText || 'Loading...') +
            '</p></div></div>';

        container.innerHTML = html;

        var pagesRoot = container.querySelector('.maca-pdf-js-pages');

        return loadLibrary()
            .then(function (pdfjsLib) {
                return pdfjsLib.getDocument(fileUrl).promise;
            })
            .then(function (pdf) {
                pagesRoot.innerHTML = '';
                var chain = Promise.resolve();

                for (var i = 1; i <= pdf.numPages; i++) {
                    (function (pageNum) {
                        chain = chain.then(function () {
                            return pdf.getPage(pageNum).then(function (page) {
                                var viewport = page.getViewport({ scale: scale });
                                var canvas = document.createElement('canvas');
                                canvas.width = viewport.width;
                                canvas.height = viewport.height;
                                canvas.style.maxWidth = '100%';
                                canvas.style.height = 'auto';
                                canvas.style.display = 'block';
                                canvas.style.margin = '12px auto';
                                canvas.style.boxShadow = '0 2px 8px rgba(0,0,0,0.12)';
                                pagesRoot.appendChild(canvas);
                                return page.render({
                                    canvasContext: canvas.getContext('2d'),
                                    viewport: viewport
                                }).promise;
                            });
                        });
                    })(i);
                }

                return chain;
            })
            .catch(function () {
                iframeFallback(container, fileUrl, title);
            });
    }

    window.MacaMenulistPdf = {
        render: render,
        loadLibrary: loadLibrary
    };
})(window);
