document.addEventListener('DOMContentLoaded', function () {
    var modal = document.getElementById('outgoing-modal');
    if (!modal) { return; }

    var actionInput = document.getElementById('outgoing-action');
    var idInput = document.getElementById('outgoing-id');
    var submitBtn = document.getElementById('outgoing-submit');
    var titleEl = document.getElementById('outgoing-modal-title');
    var lastFocused = null;

    function openModal(){
        lastFocused = document.activeElement;
        modal.classList.add('show');
        modal.setAttribute('aria-hidden','false');
        var first = document.getElementById('out-title');
        if (first) { try { first.focus(); } catch(_) {} }
        // Reset upload UI state when opening
        try { resetUploadButton(); } catch(_) {}
        try { var vf = document.getElementById('out-file-url'); var vb = document.querySelector('#outgoing-form .view-pdf-icon-btn'); if (vb) vb.style.display = (vf && vf.value) ? 'inline-flex' : 'none'; } catch(_) {}
    }
    function closeModal(){
        var active = document.activeElement;
        if (active && modal.contains(active)) { try { active.blur(); } catch(_) {} }
        // Hide modal immediately to prevent white box flash
        modal.style.display = 'none';
        modal.style.visibility = 'hidden';
        modal.style.opacity = '0';
        modal.classList.remove('show');
        modal.setAttribute('aria-hidden','true');
        // Force reflow to ensure styles are applied
        void modal.offsetHeight;
        if (lastFocused && document.contains(lastFocused)) { try { lastFocused.focus(); } catch(_) {} }
        lastFocused = null;
        // Reset upload UI on close
        try { resetUploadButton(); } catch(_) {}
    }

    function setCreate(){
        if (actionInput) actionInput.value = 'create';
        if (idInput) idInput.value = '0';
        var form = document.getElementById('outgoing-form');
        if (form) form.reset();
        if (submitBtn) submitBtn.textContent = (submitBtn.getAttribute('data-label-save') || 'Save');
        if (titleEl) titleEl.textContent = (titleEl.getAttribute('data-label-create') || 'Create');
    }

    function setUpdate(docId){
        if (actionInput) actionInput.value = 'update';
        if (idInput) idInput.value = docId;
        if (submitBtn) submitBtn.textContent = (submitBtn.getAttribute('data-label-update') || 'Cập nhật');
        if (titleEl) titleEl.textContent = (titleEl.getAttribute('data-label-update') || 'CẬP NHẬT CÔNG VĂN ĐI');
        
        // Fix modal state
        var modal = document.getElementById('outgoing-modal');
        if (modal) {
            modal.removeAttribute('aria-hidden');
            modal.setAttribute('aria-hidden', 'false');
            modal.removeAttribute('aria-hidden');
        }
    }

    // Function to view document PDF
    function viewDocument(docId) {
        if (!docId) return;
        
        // Get file URL from server
        fetch('modules/outgoing_service.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'fetch'
            },
            body: 'action=get_file_url&id=' + encodeURIComponent(docId)
        })
        .then(response => response.json())
        .then(data => {
            if ((data.success || data.ok) && data.file_url) {
                // Open PDF modal similar to incoming documents
                openPdfModal(data.file_url);
            } else {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + (data.message || 'Không thể mở file');
                if (window.showToast) { window.showToast('error', errorWithHeader); }
            }
        })
        .catch(error => {
            var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
            var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + 'Lỗi khi tải file';
            if (window.showToast) { window.showToast('error', errorWithHeader); }
        });
    }

    // Function to open PDF modal
    function openPdfModal(fileUrl) {
        // Check if mobile first
        var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
        
        // On mobile, directly open PDF in new tab - no modal needed
        if (isMobile) {
            var pdfUrl = 'modules/pdf_viewer.php?file=' + encodeURIComponent(fileUrl) + '#toolbar=1&navpanes=1&scrollbar=1';
            window.open(pdfUrl, '_blank');
            return; // Exit early, no modal needed
        }
        
        // Desktop only: Create modal for PDF preview
        // Save current modal state before opening PDF modal
        var currentModal = document.querySelector('.modal.show');
        if (currentModal) {
            window.currentModalState = {
                element: currentModal,
                display: currentModal.style.display,
                zIndex: currentModal.style.zIndex,
                classList: currentModal.classList.toString()
            };
        }
        
        // Create modal if it doesn't exist
        var existingModal = document.getElementById('pdf-viewer-modal');
        if (existingModal) {
            existingModal.remove();
        }

        var modal = document.createElement('div');
        modal.id = 'pdf-viewer-modal';
        modal.className = 'modal-overlay';
        
        // Desktop only - show PDF in iframe
        modal.innerHTML = `
            <div class="modal-content pdf-modal">
                <button type="button" class="modal-close" data-modal-close title="${window.getTooltipText ? window.getTooltipText('close') : 'Đóng'}">×</button>
                <div class="modal-body pdf-container" style="padding:0;height:100%;overflow:hidden;background:#3C3C3C;position:relative;">
                    <iframe id="pdf-iframe" src="" type="application/pdf" style="width:100%;height:100%;border:none;background:#3C3C3C;"></iframe>
                </div>
            </div>
        `;

        document.body.appendChild(modal);
        var contentEl = modal.querySelector('.modal-content');
        
        // Ensure modal is visible
        modal.style.display = 'flex';

        // Add event listeners for close buttons
        var closeButtons = modal.querySelectorAll('[data-modal-close]');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                closePdfModal();
            });
        });

        // Close modal when clicking outside
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closePdfModal();
            }
        });
        
        // Close modal with Escape key
        var escapeHandler = function(e) {
            if (e.key === 'Escape') {
                closePdfModal();
                document.removeEventListener('keydown', escapeHandler);
            }
        };
        document.addEventListener('keydown', escapeHandler);
        
        // Function to close PDF modal properly
        function closePdfModal() {
            // Remove PDF modal
            modal.remove();

            // Only restore a previously open modal if there actually was one
            var saved = window.currentModalState;
            if (saved && saved.element) {
                try {
                    var el = saved.element;
                    el.style.display = saved.display || 'flex';
                    el.style.zIndex = saved.zIndex || '100000';
                    el.classList.add('show');
                    el.removeAttribute('aria-hidden');
                    el.setAttribute('aria-hidden', 'false');
                } catch (_) {}
            }

            // Clear saved state
            window.currentModalState = null;
        }

        // Load PDF in iframe (Desktop only)
        try {
            // Construct full URL for PDF with toolbar enabled
            var pdfUrl = 'modules/pdf_viewer.php?file=' + encodeURIComponent(fileUrl) + '#toolbar=1&navpanes=1&scrollbar=1';
            
            var iframeEl = modal.querySelector('#pdf-iframe');
            if (iframeEl) {
                // Set source - browser will handle PDF rendering with toolbar
                iframeEl.src = pdfUrl;
                
                // Handle load error
                iframeEl.onerror = function() {
                    alert('Không thể tải PDF. Vui lòng thử lại.');
                    closePdfModal();
                };
            }
        } catch (error) {
            console.error('Error loading PDF:', error);
            alert('Không thể tải PDF');
        }
    }

    // Function to delete document
    function deleteDocument(docId) {
        if (!docId) {
            return;
        }
        
        // Get confirm message
        var confirmMsg = 'Bạn có chắc chắn muốn xóa công văn này?';
        if (window.__MESSAGES__ && window.__MESSAGES__['confirm_delete']) {
            confirmMsg = window.__MESSAGES__['confirm_delete'];
        }
        
        if (!confirm(confirmMsg)) {
            return;
        }
        
        // Prepare form data for delete
        var formData = new FormData();
        formData.append('action', 'delete');
        formData.append('id_document', docId);
        
        // Get license from hidden input
        var licenseEl = document.getElementById('outgoing-license');
        var license = (licenseEl && licenseEl.value) ? licenseEl.value : '';
        formData.append('license', license);
        
        // Send delete request
        fetch('modules/outgoing_service.php', { 
            method: 'POST', 
            headers: { 
                'X-Requested-With': 'fetch', 
                'Accept': 'application/json' 
            }, 
            body: formData 
        })
        .then(function(r){ return r.text(); })
        .then(function(text){
            var json = null;
            try { json = text ? JSON.parse(text) : null; } catch(_) {}
            if (!json) {
                var errorMsg = 'Lỗi kết nối mạng';
                if (window.showToast) {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(errorMsg);
                }
                return;
            }
            if (json && json.ok) {
                var msg = encodeURIComponent(json.message || 'Đã xóa thành công');
                location.href = 'index.php?outgoing=1&success=' + msg;
            } else {
                var err = (json && json.message) ? String(json.message) : 'Xóa thất bại';
                err = err.replace(/\n/g, '<br>');
                if (window.showToast) {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + err;
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(err);
                }
            }
        })
        .catch(function(){ 
            var errorMsg = 'Lỗi kết nối mạng';
            if (window.showToast) {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                window.showToast('error', errorWithHeader);
            } else {
                alert(errorMsg);
            }
        });
    }

    // Function to edit document
    function editDocument(docId) {
        if (!docId) {
            return;
        }
        
        // Find the document data from the table
        var editButton = document.querySelector('[data-outgoing-edit="' + docId + '"]');
        if (!editButton) {
            return;
        }
        
        var row = editButton.closest('tr');
        if (!row) {
            return;
        }
        
        // Get additional data from data attributes
        var rowData = row.getAttribute('data-document');
        var docData = rowData ? JSON.parse(rowData) : {};
        
        // Convert date from dd/mm/yyyy to yyyy-mm-dd
        var effectiveDate = docData.effective_date || '';
        var dateParts = effectiveDate.split('/');
        var formattedDate = '';
        if (dateParts.length === 3) {
            formattedDate = dateParts[2] + '-' + dateParts[1].padStart(2, '0') + '-' + dateParts[0].padStart(2, '0');
        }
        
        // Set update mode
        setUpdate(docId);
        
        // Set form data
        var docSymbolField = document.getElementById('out-symbol');
        var docCodeField = document.getElementById('out-code');
        var docTitleField = document.getElementById('out-title');
        var docSummaryField = document.getElementById('out-summary');
        var docReceiverField = document.getElementById('out-to');
        var docTypeField = document.getElementById('out-doc-type-id');
        var docPageTypeField = document.getElementById('out-type-doc-id');
        var docDateField = document.getElementById('out-date');
        var docQuantityField = document.getElementById('out-quantity');
        var docCompanyField = document.getElementById('out-company-id');
        var docFileField = document.getElementById('out-file-url');
        var docStorageField = document.getElementById('out-file-storage');
        var docNotesField = document.getElementById('out-notes');
        
        // Populate fields
        if (docSymbolField) docSymbolField.value = docData.symbol || '';
        if (docCodeField) docCodeField.value = docId;
        if (docTitleField) docTitleField.value = docData.title || '';
        if (docSummaryField) docSummaryField.value = docData.summary || '';
        if (docReceiverField) docReceiverField.value = docData.receiver || '';
        if (docDateField) docDateField.value = formattedDate;
        if (docQuantityField) docQuantityField.value = docData.quantity || '';
        if (docStorageField) docStorageField.value = docData.storage_location || '';
        if (docNotesField) docNotesField.value = docData.notes || '';
        if (docFileField) docFileField.value = docData.file_url || '';
        
        // Toggle view button based on file URL
        var viewBtn = document.querySelector('#outgoing-form .view-pdf-icon-btn');
        if (viewBtn && docFileField && docFileField.value && docFileField.value.trim()) {
            viewBtn.style.display = 'inline-flex';
        }
        
        // Set dropdowns (custom select)
        if (docTypeField && docData.doctype) {
            docTypeField.value = docData.doctype;
            var typeSelect = document.getElementById('out-doc-type-select');
            if (typeSelect) {
                var option = typeSelect.querySelector('[data-value="' + docData.doctype + '"]');
                if (option) {
                    var toggle = typeSelect.querySelector('.custom-select-toggle');
                    if (toggle) toggle.textContent = option.textContent;
                }
            }
        }
        
        if (docPageTypeField && docData.typedoc) {
            docPageTypeField.value = docData.typedoc;
            var pageTypeSelect = document.getElementById('out-docpage-type-select');
            if (pageTypeSelect) {
                var option = pageTypeSelect.querySelector('[data-value="' + docData.typedoc + '"]');
                if (option) {
                    var toggle = pageTypeSelect.querySelector('.custom-select-toggle');
                    if (toggle) toggle.textContent = option.textContent;
                }
            }
        }
        
        if (docCompanyField && docData.id_company) {
            docCompanyField.value = docData.id_company;
            var companySelect = document.getElementById('out-company-select');
            if (companySelect) {
                var option = companySelect.querySelector('[data-value="' + docData.id_company + '"]');
                if (option) {
                    var toggle = companySelect.querySelector('.custom-select-toggle');
                    if (toggle) toggle.textContent = option.textContent;
                }
            }
        }
        
        // Open modal
        openModal();
    }

    document.addEventListener('click', function(e){
        var addBtn = e.target.closest('[data-outgoing-open="create"]');
        if(addBtn){ setCreate(); openModal(); return; }

        var editBtn = e.target.closest('[data-outgoing-edit]');
        if(editBtn){ 
            var docId = editBtn.getAttribute('data-outgoing-edit');
            editDocument(docId);
            return; 
        }

        var viewBtn = e.target.closest('[data-outgoing-view]');
        if(viewBtn){ 
            var docId = viewBtn.getAttribute('data-outgoing-view');
            viewDocument(docId);
            return; 
        }

        var deleteBtn = e.target.closest('[data-outgoing-delete]');
        if(deleteBtn){ 
            var docId = deleteBtn.getAttribute('data-outgoing-delete');
            deleteDocument(docId);
            return; 
        }

        if(e.target.closest('[data-modal-close]')){ closeModal(); }
    });

    document.addEventListener('keydown', function(e){ if(e.key === 'Escape'){ closeModal(); }});

    var form = document.getElementById('outgoing-form');
    if (!form) return;

    // Toast helpers for consistent error style
    function getErrorTitle(){ try { return (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO'; } catch(_) { return 'THÔNG BÁO'; } }
    function showError(msg){ var html = '<div class="error-header">' + getErrorTitle() + '</div>' + String(msg || ''); if (window.showToast) window.showToast('error', html); }

    // Upload PDF behavior (mirror incoming but path GoDocument)
    (function(){
        var uploadBtn = document.querySelector('#outgoing-form .upload-pdf-icon-btn');
        var viewBtn = document.querySelector('#outgoing-form .view-pdf-icon-btn');
        var fileInput = document.querySelector('#outgoing-form input[type="file"][accept=".pdf"]');
        var fileUrlField = document.getElementById('out-file-url');
        if (!uploadBtn || !fileInput || !fileUrlField) return;

        function setUploadLoading(){
            uploadBtn.classList.remove('success','error');
            uploadBtn.disabled = true;
        }
        function setUploadSuccess(){
            uploadBtn.classList.remove('error');
            uploadBtn.classList.add('success');
            uploadBtn.disabled = false;
            if (viewBtn) { viewBtn.style.display = 'inline-flex'; viewBtn.title = 'Xem file PDF'; }
        }
        function setUploadError(){
            uploadBtn.classList.remove('success');
            uploadBtn.classList.add('error');
            uploadBtn.disabled = false;
        }
        function resetUploadButton(){
            uploadBtn.classList.remove('success','error');
            uploadBtn.disabled = false;
        }

        if (uploadBtn){ uploadBtn.addEventListener('click', function(){ fileInput.click(); }); }
        if (fileInput){
            fileInput.addEventListener('change', function(e){
                var file = e.target.files[0];
                if (!file) return;
                var msgOnlyPdf = (window.__MESSAGES__ && window.__MESSAGES__['incoming_form_upload_pdf']) ? window.__MESSAGES__['incoming_form_upload_pdf'] : 'Chỉ cho phép tệp PDF';
                var msgMax = (window.__MESSAGES__ && window.__MESSAGES__['incoming_max_size']) ? window.__MESSAGES__['incoming_max_size'] : 'Kích thước file quá lớn. Tối đa 50MB';
                if (file.type !== 'application/pdf') { showError(msgOnlyPdf); return; }
                if (file.size > 50*1024*1024) { showError(msgMax); return; }
                setUploadLoading();
                // Build final name using next document id if available
                var docId = (document.getElementById('out-code') && document.getElementById('out-code').value) || (document.getElementById('outgoing-id') && document.getElementById('outgoing-id').value) || '1';
                var formData = new FormData();
                formData.append('pdf_file', file);
                formData.append('document_id', docId);
                formData.append('target_dir', 'GoDocument');

                fetch('modules/incoming/upload_standalone.php', { method: 'POST', body: formData })
                    .then(function(r){
                        var ct = r.headers.get('content-type')||''; if (!ct.includes('application/json')) return r.text().then(function(t){ throw new Error(t);});
                        return r.json();
                    })
                    .then(function(data){
                        if (data && data.success) {
                            var relPath = data.final_path || ('data/File/GoDocument/' + (data.final_name || (docId + '.pdf')));
                            fileUrlField.value = relPath.replace(/\\/g,'/');
                            setUploadSuccess();
                        } else { setUploadError(); showError((data && data.message) ? String(data.message) : 'Upload failed'); }
                    })
                    .catch(function(){ setUploadError(); showError('Upload failed'); });
            });
        }

        if (viewBtn && fileUrlField){
            viewBtn.addEventListener('click', function(){
                var url = fileUrlField.value; 
                if (!url || !url.trim()) {
                    var msgNoPdf = 'Chưa có file PDF để xem';
                    if (window.showToast) {
                        var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                        var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + msgNoPdf;
                        window.showToast('error', errorWithHeader);
                    } else {
                        alert(msgNoPdf);
                    }
                    return;
                }
                // Open PDF modal similar to table view
                openPdfModal(url);
            });
        }
    })();

    form.addEventListener('submit', function(e){
        e.preventDefault();
        var submitBtnEl = document.getElementById('outgoing-submit');
        if (submitBtnEl) { submitBtnEl.disabled = true; }

        try {
            var licInput = document.getElementById('outgoing-license');
            if (licInput && licInput.value) { /* ok */ } else if (licInput) { licInput.value = licInput.value || ''; }
        } catch(_) {}

        var data = new FormData(form);
        if (!data.has('license')) {
            var licEl = document.getElementById('outgoing-license');
            data.append('license', (licEl && licEl.value) ? licEl.value : '');
        }
        var postUrl = form.getAttribute('action') || form.action;
        fetch(postUrl, { method: 'POST', headers: { 'X-Requested-With': 'fetch', 'Accept': 'application/json' }, body: data })
            .then(function(r){ return r.text(); })
            .then(function(text){
                var json = null;
                try { json = text ? JSON.parse(text) : null; } catch(_) {}
                if (!json) {
                    const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    showError('<div class="error-header">' + errorTitle + '</div>Network error');
                    if (submitBtnEl) { submitBtnEl.disabled = false; }
                    return;
                }
                if (json && json.ok) {
                    closeModal();
                    // Mark body as reloading and hide all elements immediately
                    document.body.classList.add('reloading');
                    var elementsToHide = document.querySelectorAll('.modal-backdrop, .modal-overlay, .user-actions-dropdown, .page-loader');
                    elementsToHide.forEach(function(el) {
                        el.style.display = 'none';
                        el.style.visibility = 'hidden';
                        el.style.opacity = '0';
                        el.classList.remove('show');
                    });
                    // Force reflow to ensure styles are applied
                    void document.body.offsetHeight;
                    // Add critical CSS to prevent flash
                    var style = document.createElement('style');
                    style.id = 'reload-prevent-flash';
                    style.textContent = '* { transition: none !important; animation: none !important; } .page-loader, .modal-backdrop, .modal-overlay { display: none !important; visibility: hidden !important; opacity: 0 !important; }';
                    document.head.appendChild(style);
                    // Use requestAnimationFrame to ensure DOM is updated before reload
                    var msg = encodeURIComponent(json.message || '');
                    requestAnimationFrame(function() {
                        requestAnimationFrame(function() {
                            location.href = 'index.php?outgoing=1&success=' + msg;
                        });
                    });
                } else {
                    var err = (json && json.message) ? String(json.message) : 'Error';
                    err = err.replace(/\n/g, '<br>');
                    showError(err);
                    if (submitBtnEl) { submitBtnEl.disabled = false; }
                }
            })
            .catch(function(){ 
                const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                showError('<div class="error-header">' + errorTitle + '</div>Network error'); 
                if (submitBtnEl) { submitBtnEl.disabled = false; } 
            });
    });

    // Quantity spinner behavior
    (function(){
        var input = document.getElementById('out-quantity');
        if (!input) return;
        // Keyboard arrows
        input.addEventListener('keydown', function(e){
            var val = parseInt(input.value) || 0;
            var min = parseInt(input.getAttribute('min')) || 0;
            if (e.key === 'ArrowUp') { e.preventDefault(); input.value = val + 1; input.dispatchEvent(new Event('input', { bubbles: true })); }
            if (e.key === 'ArrowDown') { e.preventDefault(); if (val > min) { input.value = val - 1; input.dispatchEvent(new Event('input', { bubbles: true })); } }
        });
        // Click spinner buttons
        var wrap = input.closest('.input-wrap');
        if (wrap){
            var up = wrap.querySelector('.spinner-up');
            var down = wrap.querySelector('.spinner-down');
            if (up){ up.addEventListener('click', function(){ var v = parseInt(input.value) || 0; input.value = v + 1; input.dispatchEvent(new Event('input', { bubbles: true })); }); }
            if (down){ down.addEventListener('click', function(){ var v = parseInt(input.value) || 0; var m = parseInt(input.getAttribute('min')) || 0; if (v > m) { input.value = v - 1; input.dispatchEvent(new Event('input', { bubbles: true })); } }); }
        }
    })();

    // ----- Custom select with portal to body (prevents overlap) -----
    function setupCustomSelectPortal(rootId, hiddenInputId){
        var custom = document.getElementById(rootId);
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById(hiddenInputId);
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){ if (isPortaled) return; anchorParent = menu.parentNode; anchorNext = menu.nextSibling; document.body.appendChild(menu); isPortaled = true; }
        function unmountMenu(){ if (!isPortaled) return; if (anchorParent){ if (anchorNext){ anchorParent.insertBefore(menu, anchorNext);} else { anchorParent.appendChild(menu);} } isPortaled = false; }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) { left = Math.max(pad, window.innerWidth - width - pad); }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){ menu.style.position=''; menu.style.left=''; menu.style.top=''; menu.style.width=''; menu.style.minWidth=''; menu.style.maxWidth=''; menu.style.maxHeight=''; menu.style.zIndex=''; menu.style.display=''; }
        function closeAll(){ custom.classList.remove('open'); clearMenuStyles(); unmountMenu(); if (closeOnScroll){ window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll=null; } if (closeOnResize){ window.removeEventListener('resize', closeOnResize); closeOnResize=null; } }

        // Prevent propagation so overlay doesn't close incorrectly
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen){
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else { closeAll(); }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return; e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    }

    setupCustomSelectPortal('out-doc-type-select', 'out-doc-type-id');
    setupCustomSelectPortal('out-docpage-type-select', 'out-type-doc-id');
    setupCustomSelectPortal('out-company-select', 'out-company-id');
    setupCustomSelectPortal('out-category-select', 'out-category-id');
    
    // Add click handlers for date icons and inputs
    function setupDateIconHandlers() {
        // Handle date icons
        var dateIcons = document.querySelectorAll('.date-icon');
        dateIcons.forEach(function(icon) {
            icon.addEventListener('click', function() {
                var targetId = this.getAttribute('data-target');
                var targetInput = document.getElementById(targetId);
                if (targetInput) {
                    try {
                        targetInput.focus();
                        targetInput.showPicker();
                    } catch (e) {
                        // Fallback for browsers without showPicker()
                        targetInput.click();
                    }
                }
            });
        });
        
        // Handle clicking anywhere on date inputs
        var dateInputs = document.querySelectorAll('input[type="date"]');
        dateInputs.forEach(function(input) {
            input.addEventListener('click', function(e) {
                try {
                    this.focus();
                    this.showPicker();
                } catch (err) {
                    // Fallback for browsers without showPicker()
                    // The native click will handle it
                }
            });
            
            // Also handle focus event
            input.addEventListener('focus', function(e) {
                try {
                    // Small delay to ensure focus is complete
                    setTimeout(function() {
                        input.showPicker();
                    }, 100);
                } catch (err) {
                    // Fallback - do nothing, native behavior will work
                }
            });
        });
    }
    
    // Setup date icon handlers
    setupDateIconHandlers();
});












