<?php
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
?>

<style>
    /* CSS chung */
    .pdf-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        max-width: 100%;
    }
    
    .pdf-toolbar {
        background: #2c3e50;
        padding: 12px 15px;
        margin-bottom: 15px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 12px;
        box-shadow: 0 3px 8px rgba(0,0,0,0.15);
    }

    /* Bố trí các nhóm nút */
    .toolbar-left, .toolbar-center, .toolbar-right {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .toolbar-group {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    /* Nhóm nút zoom */
    .toolbar-group.zoom-group {
        display: flex;
        align-items: center;
        background: rgba(255,255,255,0.08);
        border-radius: 4px;
        padding: 0 5px;
    }
    
    .pdf-toolbar button {
        padding: 8px 15px;
        background: #3498db;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 14px;
        transition: all 0.3s ease;
        white-space: nowrap;
    }
    
    .pdf-toolbar button:hover {
        background: #2980b9;
        transform: translateY(-1px);
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }
    
    .pdf-toolbar button i {
        font-size: 16px;
    }
    
    #zoom-level {
        min-width: 60px;
        text-align: center;
        font-weight: 600;
        color: white;
        padding: 8px 10px;
        border-radius: 3px;
        user-select: none;
        background: rgba(255,255,255,0.12);
    }
    
    #pdf-viewer {
        flex: 1;
        border: 1px solid #ddd;
        border-radius: 6px;
        min-height: 500px;
        position: relative;
        background: #f5f5f5;
        overflow-y: auto;
        padding: 20px 10px;
    }
    
    .loading {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 1.2em;
        color: #555;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 15px;
    }
    
    .loading:after {
        content: "";
        width: 40px;
        height: 40px;
        border: 4px solid #ddd;
        border-top: 4px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .pdf-page {
        margin: 0 auto 30px;
        position: relative;
        box-shadow: 0 3px 10px rgba(0,0,0,0.15);
        background: white;
        transition: transform 0.2s ease;
    }

    .pdf-page:hover {
        transform: translateY(-2px);
    }
    
    .page-label {
        background: #2c3e50;
        color: white;
        padding: 6px 15px;
        font-size: 0.9em;
        text-align: center;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
        font-weight: 500;
    }
    
    /* Download button */
    #download-btn {
        background: #27ae60;
    }
    
    #download-btn:hover {
        background: #219653;
    }

    /* Print button */
    #print-btn {
        background: #9b59b6;
    }
    
    #print-btn:hover {
        background: #8e44ad;
    }
    
    /* Password dialog */
    #password-dialog {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.7);
        z-index: 1000;
        backdrop-filter: blur(3px);
    }
    
    .password-dialog-content {
        background: white;
        width: 380px;
        margin: 100px auto;
        padding: 25px;
        border-radius: 8px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.3);
        animation: fadeInDown 0.3s ease;
    }

    @keyframes fadeInDown {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .password-input {
        width: 100%;
        padding: 12px;
        margin: 15px 0;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 16px;
        transition: border 0.3s ease;
    }

    .password-input:focus {
        border-color: #3498db;
        outline: none;
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
    }
    
    .password-submit {
        padding: 10px 25px;
        background: #3498db;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        transition: background 0.3s;
    }
    
    .password-submit:hover {
        background: #2980b9;
    }
    
    .password-cancel {
        background: #95a5a6;
        margin-left: 10px;
    }
    
    .password-cancel:hover {
        background: #7f8c8d;
    }
    
    #password-error {
        color: #e74c3c;
        margin-top: 10px;
        display: none;
        font-size: 14px;
        padding: 8px;
        background-color: rgba(231, 76, 60, 0.1);
        border-radius: 4px;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
        .pdf-toolbar {
            flex-direction: column;
            align-items: flex-start;
            gap: 15px;
            padding: 15px;
        }
        
        .toolbar-left, .toolbar-center, .toolbar-right {
            width: 100%;
            justify-content: space-between;
        }

        .search-container {
            width: 100%;
        }

        #search-input {
            flex: 1;
        }

        .password-dialog-content {
            width: 90%;
            margin: 50px auto;
            padding: 20px;
        }
    }

    /* Search input and results */
    .search-container {
        display: flex;
        align-items: center;
        gap: 10px;
        position: relative;
    }

    #search-input {
        padding: 8px 12px;
        border: 1px solid rgba(255,255,255,0.2);
        border-radius: 4px;
        font-size: 14px;
        width: 220px;
        background: rgba(255,255,255,0.1);
        color: white;
    }

    #search-input::placeholder {
        color: rgba(255,255,255,0.6);
    }

    #search-input:focus {
        outline: none;
        border-color: #3498db;
        background: rgba(255,255,255,0.15);
    }

    .search-navigation {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    #search-results {
        color: white;
        font-size: 14px;
        background: rgba(255,255,255,0.1);
        padding: 5px 10px;
        border-radius: 3px;
        min-width: 60px;
        text-align: center;
    }

    #prev-match, #next-match {
        padding: 5px 8px;
        background: rgba(255,255,255,0.1);
        border: none;
        border-radius: 3px;
        cursor: pointer;
        color: white;
    }

    #prev-match:hover, #next-match:hover {
        background: rgba(255,255,255,0.2);
    }

    .highlight {
        background-color: rgba(255, 255, 0, 0.5);
        border-radius: 2px;
        box-shadow: 0 0 0 2px rgba(255, 255, 0, 0.5);
    }

    .current-highlight {
        background-color: #ff9632;
        box-shadow: 0 0 0 2px rgba(255, 150, 50, 0.7);
    }

    .text-layer {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        overflow: hidden;
        opacity: 0.2;
        line-height: 1.0;
        user-select: text;
    }

    .text-layer > span {
        color: transparent;
        position: absolute;
        white-space: pre;
        cursor: text;
        transform-origin: 0% 0%;
    }

    /* Hiển thị trạng thái đang tải */
    .page-loading {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #666;
        font-size: 14px;
    }

    .annotation-layer {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        overflow: hidden;
        z-index: 3;
        pointer-events: none;
    }

    .annotation-layer a {
        pointer-events: auto;
    }

	.annotation-layer input,
	.annotation-layer select,
	.annotation-layer textarea {
		pointer-events: auto;
		background: rgba(255, 255, 0, 0.1);
		border: 1px dashed #888;
	}

	.annotation-layer input:focus {
		background: rgba(255, 255, 200, 0.3);
	}


    /* Hiệu ứng hover cho link (tùy chọn) */
    .annotation-layer a:hover {
        outline: 2px solid rgba(0, 100, 255, 0.2);
    }

	.print-loading {
		animation: fadeIn 0.3s ease;
		box-shadow: 0 5px 15px rgba(0,0,0,0.3);
	}

	@keyframes fadeIn {
		from { opacity: 0; transform: translate(-50%, -60%); }
		to { opacity: 1; transform: translate(-50%, -50%); }
	}


</style>

<div class="pdf-container">
    <!-- Thanh công cụ được cải tiến -->
    <div class="pdf-toolbar">
        <div class="toolbar-left">
            <div class="toolbar-group">
                <button id="download-btn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-download" viewBox="0 0 16 16">
                    <path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5"/>
                    <path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708z"/>
                    </svg>
                     <?php echo Text::_('EDOCMAN_DOWNLOAD'); ?>
                </button>
                <button id="print-btn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-printer-fill" viewBox="0 0 16 16">
                    <path d="M5 1a2 2 0 0 0-2 2v1h10V3a2 2 0 0 0-2-2zm6 8H5a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1"/>
                    <path d="M0 7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-1v-2a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2H2a2 2 0 0 1-2-2zm2.5 1a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1"/>
                    </svg>
                     <?php echo Text::_('JGLOBAL_PRINT'); ?>
                </button>
            </div>
        </div>
        
        <div class="toolbar-center">
            <div class="toolbar-group zoom-group">
                <button id="zoom-out">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-zoom-out" viewBox="0 0 16 16">
                    <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11M13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0"/>
                    <path d="M10.344 11.742q.044.06.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1 1 0 0 0-.115-.1 6.5 6.5 0 0 1-1.398 1.4z"/>
                    <path fill-rule="evenodd" d="M3 6.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5"/>
                    </svg>
                </button>
                <span id="zoom-level">100%</span>
                <button id="zoom-in">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-zoom-in" viewBox="0 0 16 16">
                    <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11M13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0"/>
                    <path d="M10.344 11.742q.044.06.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1 1 0 0 0-.115-.1 6.5 6.5 0 0 1-1.398 1.4z"/>
                    <path fill-rule="evenodd" d="M6.5 3a.5.5 0 0 1 .5.5V6h2.5a.5.5 0 0 1 0 1H7v2.5a.5.5 0 0 1-1 0V7H3.5a.5.5 0 0 1 0-1H6V3.5a.5.5 0 0 1 .5-.5"/>
                    </svg>
                </button>
            </div>
        </div>

        <div class="toolbar-right">
            <!-- Search Input với navigation buttons -->
            <div class="toolbar-group search-container">
                <input type="text" id="search-input" placeholder="<?php echo Text::_('EDOCMAN_SEARCH'); ?>">
                <div class="search-navigation">
                    <button id="prev-match" title="<?php echo Text::_('EDOCMAN_PREVIOUS_MATCH'); ?>">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-up" viewBox="0 0 16 16">
                        <path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708z"/>
                        </svg>
                    </button>
                    <span id="search-results"></span>
                    <button id="next-match" title="<?php echo Text::_('EDOCMAN_NEXT_MATCH'); ?>">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16">
                        <path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Phần hiển thị PDF -->
    <div id="pdf-viewer"></div>
</div>

<!-- Password Dialog -->
<div id="password-dialog">
    <div class="password-dialog-content">
        <h3 style="margin-top:0;"><?php echo Text::_('EDOCMAN_PDF_PASSWORD_REQUIRED'); ?></h3>
        <input type="password" id="pdf-password" class="password-input" placeholder="<?php echo Text::_('EDOCMAN_ENTER_PASSWORD'); ?>">
        <div id="password-error"></div>
        <div style="text-align: right; margin-top: 20px;">
            <button id="submit-password" class="password-submit"><?php echo Text::_('JSUBMIT'); ?></button>
            <button id="cancel-password" class="password-submit password-cancel"><?php echo Text::_('JCANCEL'); ?></button>
        </div>
    </div>
</div>

<script type="module">
import * as pdfjsLib from "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.0.375/pdf.min.mjs";

// Biến PHP cho JavaScript
const rootUrl = '<?php echo Uri::root(); ?>';
const documentUrl = <?php echo json_encode($this->documenturl); ?>;
const documentFilename = '<?php echo basename($this->documenturl); ?>';
const txtLoading = '<?php echo Text::_("EDOCMAN_LOADING"); ?>...';
const txtUpdating = '<?php echo Text::_("EDOCMAN_UPDATING"); ?>...';
const txtPasswordIncorrect = '<?php echo Text::_("EDOCMAN_PDF_PASSWORD_INCORRECT"); ?>';
const txtAttemptsRemaining = '<?php echo Text::_("EDOCMAN_ATTEMPTS_REMAINING"); ?>';
const txtPasswordFailed = '<?php echo Text::_("EDOCMAN_PDF_PASSWORD_FAILED"); ?>';
const txtPasswordCanceled = '<?php echo Text::_("EDOCMAN_PDF_PASSWORD_CANCELED"); ?>';

// Thiết lập worker path đúng cách
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.0.375/pdf.worker.min.mjs";

document.addEventListener('DOMContentLoaded', function() {
    // Thiết lập các biến cần thiết
    const pdfUrl = rootUrl + 'edocmanviewer/' + documentUrl;
    let currentScale = 1.0;
    let pdfDoc = null;
    let passwordAttempts = 0;
    const MAX_PASSWORD_ATTEMPTS = 3;
    let textContents = []; // Lưu trữ nội dung văn bản của mỗi trang
    let currentMatchIndex = -1; // Theo dõi kết quả tìm kiếm hiện tại
    let totalMatches = 0; // Tổng số kết quả tìm kiếm
    let matches = []; // Lưu trữ tất cả các kết quả tìm kiếm
    let currentHighlightElement = null; // Phần tử đang được highlight
    let renderInProgress = false; // Theo dõi trạng thái rendering

    // Khởi tạo PDF viewer
    initPDFViewer();

    // Hàm khởi tạo PDF viewer
    function initPDFViewer() {
        const pdfViewer = document.getElementById('pdf-viewer');
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.textContent = txtLoading;
        pdfViewer.appendChild(loadingDiv);

        // Tải PDF
        pdfjsLib.getDocument(pdfUrl).promise
            .then(function(doc) {
                pdfDoc = doc;
                displayPDF(pdfUrl, pdfViewer);
                
                // Thiết lập lazy loading
                setTimeout(setupLazyLoading, 1000);
            })
            .catch(function(error) {
                if (error.name === 'PasswordException') {
                    showPasswordDialog();
                } else {
                    pdfViewer.innerHTML = `<div class="loading" style="color:red;">${error.message}</div>`;
                }
            });

        // Xử lý sự kiện cho các nút và đầu vào
        document.getElementById('print-btn').addEventListener('click', printPDF);
        document.getElementById('download-btn').addEventListener('click', downloadPDF);
        document.getElementById('zoom-in').addEventListener('click', () => {
            if (pdfDoc) adjustZoom(Math.min(3.0, currentScale + 0.25));
        });
        document.getElementById('zoom-out').addEventListener('click', () => {
            if (pdfDoc && currentScale > 0.5) adjustZoom(currentScale - 0.25);
        });
        
        // Xử lý tìm kiếm và điều hướng
        const searchInput = document.getElementById('search-input');
        searchInput.addEventListener('input', debounce(function() {
            searchPDF(this.value.trim());
        }, 300));
        
        document.getElementById('prev-match').addEventListener('click', navigatePrevMatch);
        document.getElementById('next-match').addEventListener('click', navigateNextMatch);
        
        // Xử lý mật khẩu PDF
        document.getElementById('submit-password').addEventListener('click', function() {
            const password = document.getElementById('pdf-password').value.trim();
            if (password) loadPDFWithPassword(password);
        });
        
        document.getElementById('cancel-password').addEventListener('click', function() {
            document.getElementById('password-dialog').style.display = 'none';
            document.getElementById('pdf-viewer').innerHTML = 
                `<div class="loading" style="color:red;">${txtPasswordCanceled}</div>`;
        });
        
        document.getElementById('pdf-password').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const password = this.value.trim();
                if (password) loadPDFWithPassword(password);
            }
        });

        // Phím tắt
        document.addEventListener('keydown', function(e) {
            // Ctrl+F để tìm kiếm
            if (e.ctrlKey && e.key === 'f') {
                e.preventDefault();
                searchInput.focus();
            }
            
            // Enter để đi đến kết quả tiếp theo
            if (e.key === 'Enter' && document.activeElement === searchInput) {
                navigateNextMatch();
            }
            
            // Shift+Enter để đi đến kết quả trước đó
            if (e.key === 'Enter' && e.shiftKey && document.activeElement === searchInput) {
                navigatePrevMatch();
            }
            
            // Ctrl+/Ctrl- để zoom
            if (e.ctrlKey && e.key === '=') {
                e.preventDefault();
                if (pdfDoc) adjustZoom(Math.min(3.0, currentScale + 0.25));
            }
            
            if (e.ctrlKey && e.key === '-') {
                e.preventDefault();
                if (pdfDoc && currentScale > 0.5) adjustZoom(currentScale - 0.25);
            }
        });

        // Wheel zoom với Ctrl key
        document.addEventListener('wheel', function(e) {
            if (e.ctrlKey) {
                e.preventDefault();
                
                if (!renderInProgress && pdfDoc) {
                    const delta = -Math.sign(e.deltaY);
                    const zoomStep = 0.1;
                    const newScale = Math.max(0.5, Math.min(3.0, currentScale + delta * zoomStep));
                    
                    if (newScale !== currentScale) {
                        adjustZoom(newScale);
                    }
                }
            }
        }, { passive: false });
    }

    // ========== DOWNLOAD FUNCTION ==========
    function downloadPDF() {
        const link = document.createElement('a');
        link.href = pdfUrl;
        link.download = documentFilename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // ========== PASSWORD HANDLING ==========
    function showPasswordDialog(errorMessage = '') {
        const dialog = document.getElementById('password-dialog');
        const passwordInput = document.getElementById('pdf-password');
        const errorElement = document.getElementById('password-error');
        
        passwordInput.value = '';
        dialog.style.display = 'block';
        passwordInput.focus();
        
        if (errorMessage) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = 'block';
        } else {
            errorElement.style.display = 'none';
        }
    }

    function loadPDFWithPassword(password) {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.textContent = txtLoading;
        document.getElementById('pdf-viewer').innerHTML = '';
        document.getElementById('pdf-viewer').appendChild(loadingDiv);
        
        pdfjsLib.getDocument({
            url: pdfUrl,
            password: password
        }).promise.then(function(doc) {
            document.getElementById('password-dialog').style.display = 'none';
            pdfDoc = doc;
            displayPDF(pdfUrl, document.getElementById('pdf-viewer'));
            passwordAttempts = 0;
        }).catch(function(error) {
            passwordAttempts++;
            
            if (error.name === 'PasswordException' && passwordAttempts < MAX_PASSWORD_ATTEMPTS) {
                const remainingAttempts = MAX_PASSWORD_ATTEMPTS - passwordAttempts;
                showPasswordDialog(`${txtPasswordIncorrect} (${remainingAttempts} ${txtAttemptsRemaining})`);
            } else {
                document.getElementById('password-dialog').style.display = 'none';
                document.getElementById('pdf-viewer').innerHTML = 
                    `<div class="loading" style="color:red;">${txtPasswordFailed}</div>`;
            }
        });
    }

    // ========== PDF VIEWER FUNCTIONS ==========
    function printPDF() {
		// Hiển thị thông báo đang chuẩn bị
		const loadingMessage = document.createElement('div');
		loadingMessage.className = 'print-loading';
		loadingMessage.textContent = '<?php echo Text::_("EDOCMAN_PREPARE_PRINTING")?>...';
		loadingMessage.style.position = 'fixed';
		loadingMessage.style.top = '50%';
		loadingMessage.style.left = '50%';
		loadingMessage.style.transform = 'translate(-50%, -50%)';
		loadingMessage.style.background = 'rgba(0,0,0,0.7)';
		loadingMessage.style.color = 'white';
		loadingMessage.style.padding = '15px 20px';
		loadingMessage.style.borderRadius = '5px';
		loadingMessage.style.zIndex = '9999';
		document.body.appendChild(loadingMessage);
		
		// Phương pháp 1: Sử dụng PDF.js để in
		if (pdfDoc) {
			// Tạo blob URL từ ArrayBuffer của PDF
			fetch(pdfUrl)
				.then(response => response.blob())
				.then(blob => {
					const blobUrl = URL.createObjectURL(blob);
					
					// Xóa thông báo loading
					document.body.removeChild(loadingMessage);
					
					// Mở tab mới với PDF gốc và in
					const printWindow = window.open(blobUrl, '_blank');
					if (printWindow) {
						printWindow.addEventListener('load', function() {
							setTimeout(() => {
								printWindow.print();
								// Giải phóng blob URL sau khi in xong
								setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
							}, 1000);
						});
					} else {
						alert('<?php echo Text::_("EDOCMAN_OPENING_POPUP_TO_PRINT")?>');
						// Nếu không mở được tab mới, tạo link tải xuống
						const downloadLink = document.createElement('a');
						downloadLink.href = blobUrl;
						downloadLink.download = documentFilename || 'document.pdf';
						downloadLink.click();
						setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
					}
				})
				.catch(error => {
					console.error('Error when printing:', error);
					document.body.removeChild(loadingMessage);
					
					// Phương pháp dự phòng: Mở PDF trong tab mới
					window.open(pdfUrl, '_blank');
				});
		} else {
			document.body.removeChild(loadingMessage);
			// Nếu không có pdfDoc, mở trực tiếp URL
			window.open(pdfUrl, '_blank');
		}
	}



    function adjustZoom(scale) {
		if (renderInProgress) return; // Tránh render đồng thời

		renderInProgress = true;
		currentScale = scale;
		document.getElementById('zoom-level').textContent = Math.round(scale * 100) + '%';
		
		const pages = document.querySelectorAll('.pdf-page');
		const renderPromises = [];
		
		pages.forEach(pageDiv => {
			pageDiv.classList.add('zooming');
			const loadingIndicator = document.createElement('div');
			loadingIndicator.className = 'page-loading';
			loadingIndicator.textContent = txtUpdating;
			pageDiv.appendChild(loadingIndicator);
			
			const canvas = pageDiv.querySelector('canvas');
			if (canvas) {
				const pageNum = parseInt(pageDiv.dataset.pageNum);
				const renderPromise = pdfDoc.getPage(pageNum).then(function(page) {
					const viewport = page.getViewport({ scale: currentScale });
					canvas.width = viewport.width;
					canvas.height = viewport.height;
					pageDiv.style.width = viewport.width + 'px';
					
					return page.render({
						canvasContext: canvas.getContext('2d'),
						viewport: viewport
					}).promise.then(() => {
						// Cập nhật text layer nếu có
						const textLayer = pageDiv.querySelector('.text-layer');
						if (textLayer) {
							updateTextLayer(page, pageNum, textLayer);
						}
						pageDiv.removeChild(loadingIndicator);
					});
				});
				
				renderPromises.push(renderPromise);
			}
		});
		
		Promise.all(renderPromises).then(() => {
			renderInProgress = false;
			// Nếu có kết quả tìm kiếm, cập nhật lại highlights
			if (matches.length > 0 && currentMatchIndex >= 0) {
				navigateToMatch(currentMatchIndex);
			}
		});

		// Cập nhật vị trí của tất cả các input và select trong annotation layer
		document.querySelectorAll('.annotation-layer input, .annotation-layer select').forEach(element => {
			const originalRect = element.dataset.originalRect;
			if (!originalRect) return; // Bỏ qua nếu không có tọa độ gốc
			
			const [x1, y1, x2, y2] = originalRect.split(',').map(Number);
			
			// Tính toán vị trí mới dựa trên tỉ lệ zoom
			element.style.left = `${x1 * scale}px`;
			element.style.top = `${y1 * scale}px`;
			element.style.width = `${(x2 - x1) * scale}px`;
			element.style.height = `${(y2 - y1) * scale}px`;
		});
	}


    async function updateTextLayer(page, pageNum, textLayerDiv) {
        const textContent = await page.getTextContent();
        const viewport = page.getViewport({ scale: currentScale });
        textLayerDiv.innerHTML = '';
        textLayerDiv.style.width = `${viewport.width}px`;
        textLayerDiv.style.height = `${viewport.height}px`;
        
        // Thêm mới: Lấy annotations để xử lý link
        const annotations = await page.getAnnotations();
        const linkService = {
            navigateToDestination: (dest) => {
                // Xử lý khi click vào link trong PDF
                if (typeof dest === 'string') {
                    // Link ngoài - mở trong tab mới
                    window.open(dest, '_blank');
                } else if (Array.isArray(dest) && dest.length > 0) {
                    // Link nội bộ - chuyển đến trang
                    const pageNumber = dest[0].num || dest[0];
                    if (pageNumber) {
                        const pageDiv = document.querySelector(`.pdf-page[data-page-num="${pageNumber}"]`);
                        if (pageDiv) {
                            pageDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }
                    }
                }
            }
        };
        
        // Xử lý text content như cũ
        textContent.items.forEach(item => {
            const tx = item.transform[4];
            const ty = viewport.height - item.transform[5];
            const fontHeight = Math.sqrt((item.transform[2] * item.transform[2]) + 
                                        (item.transform[3] * item.transform[3]));
            const angle = Math.atan2(item.transform[1], item.transform[0]);
            
            const span = document.createElement('span');
            span.textContent = item.str;
            span.style.left = `${tx}px`;
            span.style.top = `${ty}px`;
            span.style.fontSize = `${fontHeight}px`;
            span.style.transform = `rotate(${angle}rad)`;
            
            textLayerDiv.appendChild(span);
        });
        
        // Thêm mới: Xử lý annotations (link)
        if (annotations) {
            const annotationLayer = document.createElement('div');
            annotationLayer.className = 'annotation-layer';
            annotationLayer.style.position = 'absolute';
            annotationLayer.style.left = '0';
            annotationLayer.style.top = '0';
            annotationLayer.style.width = `${viewport.width}px`;
            annotationLayer.style.height = `${viewport.height}px`;
            
            // Thêm vào trang
            const pageDiv = document.querySelector(`.pdf-page[data-page-num="${pageNum}"]`);
            pageDiv.appendChild(annotationLayer);
            
            // Xử lý từng annotation
            annotations.filter(a => a.subtype === 'Link').forEach(link => {
                const rect = pdfjsLib.Util.normalizeRect(link.rect);
                const [x1, y1, x2, y2] = pdfjsLib.Util.normalizeRect(
                    viewport.convertToViewportRectangle(rect)
                );
                
                const linkElement = document.createElement('a');
                linkElement.style.position = 'absolute';
                linkElement.style.left = `${Math.min(x1, x2)}px`;
                linkElement.style.top = `${Math.min(y1, y2)}px`;
                linkElement.style.width = `${Math.abs(x2 - x1)}px`;
                linkElement.style.height = `${Math.abs(y2 - y1)}px`;
                linkElement.style.cursor = 'pointer';
                
                if (link.url) {
                    linkElement.href = link.url;
                    linkElement.target = '_blank';
                    linkElement.rel = 'noopener noreferrer';
                } else if (link.dest) {
                    linkElement.addEventListener('click', () => {
                        linkService.navigateToDestination(link.dest);
                    });
                }
                
                annotationLayer.appendChild(linkElement);
            });
        }
    }


    function displayPDF(pdfUrl, viewerDiv) {
        // Xóa nội dung viewer trước khi render để tránh hiển thị trùng lặp
        viewerDiv.innerHTML = '';

        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.textContent = txtLoading;
        viewerDiv.appendChild(loadingDiv);

        pdfDoc.getPage(1).then(async function(page) {
            const totalPages = pdfDoc.numPages;
            const pageRenderingPromises = [];

            for (let pageNum = 1; pageNum <= totalPages; pageNum++) {
                pageRenderingPromises.push(
                    pdfDoc.getPage(pageNum).then(function(page) {
                        return renderPage(page, pageNum, totalPages, viewerDiv);
                    })
                );
            }

            await Promise.all(pageRenderingPromises);
            await extractTextFromPDF(); // Trích xuất text sau khi render trang

            // Cuộn đến trang đầu tiên sau khi render
            const firstPage = document.querySelector('.pdf-page[data-page-num="1"]');
            if (firstPage) {
                firstPage.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }

            loadingDiv.style.transition = 'opacity 0.5s ease';
            loadingDiv.style.opacity = '0';
            setTimeout(() => {
                if (viewerDiv.contains(loadingDiv)) {
                    viewerDiv.removeChild(loadingDiv);
                }
            }, 500);
        }).catch(error => {
            loadingDiv.textContent = `Error: ${error.message}`;
            loadingDiv.style.color = 'red';
        });
    }

    function renderPage(page, pageNum, totalPages, container) {
        const viewport = page.getViewport({ scale: currentScale });
        const pageDiv = document.createElement('div');
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        pageDiv.className = 'pdf-page';
        pageDiv.dataset.pageNum = pageNum;
        pageDiv.style.width = viewport.width + 'px';
        
        const label = document.createElement('div');
        label.className = 'page-label';
        label.textContent = `${pageNum}/${totalPages}`;
        pageDiv.appendChild(label);
        pageDiv.appendChild(canvas);

        // Tạo text layer cho tìm kiếm
        const textLayerDiv = document.createElement('div');
        textLayerDiv.className = 'text-layer';
        pageDiv.appendChild(textLayerDiv);
        
        // Thêm mới: Tạo annotation layer cho links
        const annotationLayerDiv = document.createElement('div');
        annotationLayerDiv.className = 'annotation-layer';
        pageDiv.appendChild(annotationLayerDiv);
        
        container.appendChild(pageDiv);
        
        return page.render({
            canvasContext: ctx,
            viewport: viewport
        }).promise.then(() => {
            // Khởi tạo text layer và annotation layer sau khi render canvas
            return Promise.all([
                page.getTextContent().then(textContent => {
                    const textItems = textContent.items.map(item => item.str).join(' ');
                    textContents.push({ pageNum, text: textItems, items: textContent.items });
                    updateTextLayer(page, pageNum, textLayerDiv);
                }),
                page.getAnnotations().then(annotations => {
                    if (annotations.length > 0) {
                        renderAnnotations(annotations, viewport, annotationLayerDiv, page);
                    }
                })
            ]);
        });
    }

    
    function renderAnnotations(annotations, viewport, annotationLayerDiv, page) {
		const LINK_ANNOTATION = 15; // Loại annotation cho link
		const WIDGET_ANNOTATION = 20; // Loại annotation cho form fields

		annotations.filter(a => a.annotationType === WIDGET_ANNOTATION).forEach(annotation => {
			const rect = pdfjsLib.Util.normalizeRect(annotation.rect);
			const [x1, y1, x2, y2] = viewport.convertToViewportRectangle(rect);
			
			// Tạo phần tử form tương ứng
			let formElement;
			switch(annotation.fieldType) {
				case 'Tx': // Text field
					formElement = createTextField(annotation, x1, y1, x2, y2, viewport);
					break;
				
				case 'Btn': // Button/Checkbox
					if(annotation.checkBox) {
						formElement = createCheckboxField(annotation, x1, y1, x2, y2, viewport);
					}
					break;
				
				case 'Ch': // Dropdown
					formElement = createDropdownField(annotation, x1, y1, x2, y2, viewport);
					break;
				
				// Thêm các loại field khác nếu cần
			}

			if(formElement) {
				annotationLayerDiv.appendChild(formElement);
			}
		});

		// Xử lý link annotations như trước...
	}

	function createTextField(annotation, x1, y1, x2, y2, viewport) {
		const input = document.createElement('input');
		input.type = 'text';
		input.style.position = 'absolute';
		input.style.left = `${Math.min(x1, x2)}px`;
		input.style.top = `${Math.min(y1, y2)}px`;
		input.style.width = `${Math.abs(x2 - x1)}px`;
		input.style.height = `${Math.abs(y2 - y1)}px`;
		
		// Cập nhật các thuộc tính từ PDF
		input.value = annotation.value || '';
		if(annotation.readonly) input.readOnly = true;

		input.dataset.originalRect = [x1, y1, x2 - x1, y2 - y1].join(',');
		
		return input;
	}

	function createCheckboxField(annotation, x1, y1, x2, y2, viewport) {
		const checkbox = document.createElement('input');
		checkbox.type = 'checkbox';
		checkbox.style.position = 'absolute';
		checkbox.style.left = `${Math.min(x1, x2)}px`;
		checkbox.style.top = `${Math.min(y1, y2)}px`;
		checkbox.checked = !!annotation.value;
		if(annotation.readonly) checkbox.disabled = true;

		checkbox.dataset.originalRect = [x1, y1, x2 - x1, y2 - y1].join(',');
		
		return checkbox;
	}



    // ========== SEARCH FUNCTIONS ==========
    async function extractTextFromPDF() {
        textContents = [];
        for (let pageNum = 1; pageNum <= pdfDoc.numPages; pageNum++) {
            const page = await pdfDoc.getPage(pageNum);
            const textContent = await page.getTextContent();
            const textItems = textContent.items.map(item => item.str).join(' ');
            textContents.push({ pageNum, text: textItems, items: textContent.items });
        }
    }

    function searchPDF(query) {
        if (!query) {
            clearHighlights();
            document.getElementById('search-results').textContent = '';
            return;
        }

        clearHighlights();
        matches = [];
        totalMatches = 0;
        currentMatchIndex = -1;

        textContents.forEach((content) => {
            const pageNum = content.pageNum;
            const text = content.text.toLowerCase();
            query = query.toLowerCase();
            let matchIndex = text.indexOf(query);
            
            while (matchIndex !== -1) {
                matches.push({ pageNum, startIndex: matchIndex, queryLength: query.length });
                totalMatches++;
                matchIndex = text.indexOf(query, matchIndex + 1);
            }
        });

        document.getElementById('search-results').textContent = totalMatches > 0 ? `0 / ${totalMatches}` : '<?php echo Text::_("EDOCMAN_CANNOT_FOUND")?>';

        if (totalMatches > 0) {
            navigateToMatch(0);
        }
    }

    function clearHighlights() {
        const highlightedElements = document.querySelectorAll('.highlight, .current-highlight');
        highlightedElements.forEach(element => {
            element.classList.remove('highlight', 'current-highlight');
        });
        
        currentHighlightElement = null;
    }

    async function highlightText(pageNum, startIndex, queryLength) {
        const pageDiv = document.querySelector(`.pdf-page[data-page-num="${pageNum}"]`);
        if (!pageDiv) return;

        const page = await pdfDoc.getPage(pageNum);
        const textContent = await page.getTextContent();
        let accumulatedText = '';
        const textLayer = pageDiv.querySelector('.text-layer');
        
        if (!textLayer) return;
        
        // Tìm span chứa kết quả tìm kiếm
        for (let i = 0; i < textContent.items.length; i++) {
            const item = textContent.items[i];
            const text = item.str;
            const start = accumulatedText.length;
            accumulatedText += text + ' ';
            
            // Kiểm tra xem kết quả tìm kiếm có nằm trong span này không
            if (start <= startIndex && startIndex < start + text.length) {
                const spans = textLayer.querySelectorAll('span');
                
                if (spans[i]) {
                    spans[i].classList.add('highlight');
                    
                    // Nếu đây là kết quả tìm kiếm hiện tại, thêm class đặc biệt
                    if (matches[currentMatchIndex] && 
                        matches[currentMatchIndex].pageNum === pageNum && 
                        matches[currentMatchIndex].startIndex === startIndex) {
                        spans[i].classList.add('current-highlight');
                        currentHighlightElement = spans[i];
                    }
                }
                
                return spans[i];
            }
        }
        
        return null;
    }

    function navigateToMatch(index) {
        if (totalMatches === 0 || index < 0 || index >= totalMatches) return;

        clearHighlights();
        currentMatchIndex = index;
        const match = matches[currentMatchIndex];
        const pageDiv = document.querySelector(`.pdf-page[data-page-num="${match.pageNum}"]`);
        
        if (!pageDiv) return;
        
        highlightText(match.pageNum, match.startIndex, match.queryLength)
            .then(highlightElement => {
                if (highlightElement) {
                    // Cuộn đến kết quả tìm kiếm với đủ khoảng trống phía trên
                    pageDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    setTimeout(() => {
                        const rect = highlightElement.getBoundingClientRect();
                        const topOffset = rect.top - 150;
                        if (topOffset > 0) {
                            window.scrollBy({
                                top: topOffset,
                                behavior: 'smooth'
                            });
                        }
                    }, 300);
                } else {
                    pageDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
                
                document.getElementById('search-results').textContent = `${currentMatchIndex + 1} / ${totalMatches}`;
            });
    }

    function navigateNextMatch() {
        if (totalMatches === 0) return;
        const nextIndex = (currentMatchIndex + 1) % totalMatches;
        navigateToMatch(nextIndex);
    }

    function navigatePrevMatch() {
        if (totalMatches === 0) return;
        const prevIndex = (currentMatchIndex - 1 + totalMatches) % totalMatches;
        navigateToMatch(prevIndex);
    }

    // Đảm bảo tính năng tìm kiếm hoạt động khi cuộn trang
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(this, args);
            }, wait);
        };
    }

    // Tối ưu hiệu suất bằng cách lazy loading các trang PDF khi cuộn
    function setupLazyLoading() {
        const options = {
            root: null,
            rootMargin: '100px',
            threshold: 0.1
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const pageDiv = entry.target;
                    const pageNum = parseInt(pageDiv.dataset.pageNum);
                    
                    // Kiểm tra xem trang đã được render chưa
                    if (!pageDiv.dataset.rendered) {
                        pageDiv.dataset.rendered = 'true';
                        
                        // Cập nhật text layer nếu cần
                        const textLayer = pageDiv.querySelector('.text-layer');
                        if (textLayer && textLayer.children.length === 0) {
                            pdfDoc.getPage(pageNum).then(page => {
                                updateTextLayer(page, pageNum, textLayer);
                            });
                        }
                    }
                }
            });
        }, options);

        // Theo dõi tất cả các trang PDF
        document.querySelectorAll('.pdf-page').forEach(pageDiv => {
            observer.observe(pageDiv);
        });
    }
});
</script>

