(function() {

    window.attachGlobalValidation = function(formSelector, saveBtnSelector, options = {}) {
        const form = document.querySelector(formSelector);
        const saveBtn = document.querySelector(saveBtnSelector);
        if (!form || !saveBtn) return;

        const containerId = options.containerId || 'addContainer';
        const printTitleText = options.printTitle || 'Trade License';

        function isVisible(el) {
            if (!el) return false;
            if (el.hidden) return false;
            const style = window.getComputedStyle(el);
            if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
            if (el.offsetParent === null && el.getClientRects().length === 0) return false;
            return true;
        }

        function getVisibleRequiredFields() {
            return Array.from(form.querySelectorAll('[required]')).filter(f => {
                let node = f;
                while (node && node !== document) {
                    if (!isVisible(node)) return false;
                    node = node.parentElement;
                }
                return true;
            });
        }

        function findOrCreateErrorSpan(field) {
            const container = field.closest('.col-md-12') || field.closest('.form-group') || field.parentElement || document;
            const nameClass = field.name ? `${field.name}_err` : null;
            const idClass = field.id ? `${field.id}_err` : null;

            if (container) {
                if (nameClass) {
                    const byName = container.querySelector(`.${nameClass}`);
                    if (byName) return byName;
                }
                if (idClass) {
                    const byId = container.querySelector(`.${idClass}`);
                    if (byId) return byId;
                }
                const any = container.querySelector('.text-danger.required-error') || container.querySelector('.text-danger');
                if (any) return any;
            }

            if (field.type === 'checkbox') {
                let label = field.id ? document.querySelector(`label[for="${field.id}"]`) : null;
                if (!label) label = field.nextElementSibling && field.nextElementSibling.tagName === 'LABEL' ? field.nextElementSibling : null;
                const span = document.createElement('span');
                span.className = 'text-danger required-error';
                span.style.fontSize = '13px';
                span.style.display = 'none';
                if (label && label.parentElement) label.parentElement.insertBefore(span, label.nextSibling);
                else container.appendChild(span);
                return span;
            }

            const span = document.createElement('span');
            span.className = 'text-danger required-error';
            span.style.fontSize = '13px';
            span.style.display = 'none';
            container.appendChild(span);
            return span;
        }

        function showAllErrors() {
            let allValid = true;
            getVisibleRequiredFields().forEach(field => {
                const val = (field.value || '').trim();
                const errorSpan = findOrCreateErrorSpan(field);
                let notFilled = false;

                if (field.type === 'file') notFilled = !field.files || field.files.length === 0;
                else if (field.type === 'checkbox') notFilled = !field.checked;
                else notFilled = val === '';

                if (field.type === 'checkbox' && (field.id === 'is_correct_info' || field.name === 'is_correct_info')) {
                    if (notFilled) {
                        errorSpan.textContent = 'Please accept the declaration.';
                        errorSpan.style.display = 'block';
                        allValid = false;
                        return;
                    } else {
                        errorSpan.textContent = '';
                        errorSpan.style.display = 'none';
                        return;
                    }
                }

                if (notFilled) {
                    errorSpan.textContent = 'This field is required';
                    errorSpan.style.display = 'block';
                    allValid = false;
                } else {
                    errorSpan.textContent = '';
                    errorSpan.style.display = 'none';
                }
            });
            return allValid;
        }

        function clearFieldError(e) {
            const field = e.target;
            if (!isVisible(field)) return;

            const span = findOrCreateErrorSpan(field);
            let filled = false;
            if (field.type === 'file') filled = field.files && field.files.length > 0;
            else if (field.type === 'checkbox') filled = field.checked;
            else filled = (field.value || '').trim() !== '';

            if (filled) {
                span.textContent = '';
                span.style.display = 'none';
            }
        }

        form.addEventListener('input', clearFieldError, true);
        form.addEventListener('change', clearFieldError, true);

        saveBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const form = saveBtn.closest('form');
            if (!form) return;

            const requiredValid = showAllErrors();
            const formatValid = window.validateAllFields ? window.validateAllFields(form) : true;

            if (!requiredValid || !formatValid) {
                // const firstErr = form.querySelector('.is-invalid, .text-danger:visible');
                // if (firstErr) firstErr.scrollIntoView({ behavior: 'smooth', block: 'center' });
                // return;
                const firstErr = $('.is-invalid, .text-danger:visible').first()[0];
                if (firstErr) firstErr.scrollIntoView({ behavior: 'smooth', block: 'center' });
                return;               
            }

            // Show upload/footer
            const uploadSection = document.getElementById('upload_section');
            if (uploadSection) uploadSection.style.display = 'block';
            const cardFooter = document.getElementById('card-footer');
            if (cardFooter) cardFooter.style.display = 'block';
            saveBtn.style.display = 'none';

            const addContainer = document.getElementById(containerId) || form.querySelector(`#${containerId}`);
            if (!addContainer) return;
            const clone = addContainer.cloneNode(true);

            clone.style.cssText = `
                font-size:16px; line-height:1.4; padding:20px; margin:0 auto;
                background:#fff; width:210mm; min-height:297mm; box-sizing:border-box;
            `;

            Array.from(clone.querySelectorAll('*')).forEach(el => {
                el.style.fontSize = '16px';
                el.style.margin = '4px 0';
            });

            const printTitle = document.createElement('h2');
            printTitle.style.textAlign = 'center';
            printTitle.style.marginBottom = '18px';
            printTitle.style.fontSize = '18px';
            printTitle.textContent = printTitleText;
            clone.insertBefore(printTitle, clone.firstChild);

            Array.from(clone.querySelectorAll('button')).forEach(btn => btn.remove());
            Array.from(clone.querySelectorAll('.card')).forEach(card => {
                card.style.background = 'white';
                card.style.boxShadow = 'none';
                card.style.border = '1px solid #ccc';
                card.style.marginBottom = '12px';
                card.style.padding = '12px';
            });

            // --- Replace select with selected text ---
            Array.from(clone.querySelectorAll('select')).forEach(sel => {
                try {
                    let orig = null;
                    if (sel.id) orig = form.querySelector(`#${sel.id}`);
                    if (!orig && sel.name) orig = form.querySelector(`select[name="${sel.name}"]`);
                    if (!orig) {
                        const allOrig = Array.from(form.querySelectorAll('select'));
                        const allClone = Array.from(clone.querySelectorAll('select'));
                        const pos = allClone.indexOf(sel);
                        if (allOrig[pos]) orig = allOrig[pos];
                    }

                    let text = '-';
                    if (orig) {
                        if (orig.multiple) {
                            const arr = Array.from(orig.selectedOptions || []).map(o => o.text.trim()).filter(Boolean);
                            text = arr.length ? arr.join(', ') : '-';
                        } else {
                            const opt = orig.options[orig.selectedIndex];
                            if (opt && opt.text) text = opt.text.trim();
                        }

                        // Handle bootstrap-select
                        const bs = orig.closest('.bootstrap-select');
                        if (bs) {
                            const fo = bs.querySelector('.filter-option, .dropdown-toggle .filter-option-inner-inner');
                            if (fo && fo.textContent.trim()) text = fo.textContent.trim();
                        }

                        // Handle select2
                        const s2 = document.querySelector(`#${orig.id} + .select2-container .select2-selection__rendered`);
                        if (s2 && s2.textContent.trim()) text = s2.textContent.trim();
                    }

                    const display = document.createElement('div');
                    display.className = (sel.className ? sel.className + ' ' : '') + 'selected-value';
                    display.style.margin = '4px 0';
                    display.textContent = text || '-';
                    if (sel.parentElement) sel.parentElement.replaceChild(display, sel);
                    else sel.remove();
                } catch (err) {
                    sel.remove();
                }
            });

            let printContainer = document.getElementById('printContainer');
            if (!printContainer) {
                printContainer = document.createElement('div');
                printContainer.id = 'printContainer';
                printContainer.style.position = 'fixed';
                printContainer.style.left = '-9999px';
                document.body.appendChild(printContainer);
            }

            printContainer.innerHTML = '';
            printContainer.appendChild(clone);

            const uploadClone = clone.querySelector('#upload_section');
            if (uploadClone) uploadClone.remove();

          // --- Replace file inputs with file names ---
            Array.from(clone.querySelectorAll('input[type="file"]')).forEach(fileInput => {
                let fileName = '';
                const orig = form.querySelector(`#${fileInput.id}`) || form.querySelector(`[name="${fileInput.name}"]`);

                if (orig && orig.files && orig.files.length > 0) {
                    fileName = orig.files[0].name;
                } else {
                    fileName = (orig && orig.value ? orig.value.split('\\').pop() : '') || '-';
                }

                // Create a text input to display file name instead of a div
                const textInput = document.createElement('input');
                textInput.type = 'text';
                textInput.className = fileInput.className + ' file-name-display';
                textInput.style.margin = '4px 0';
                textInput.style.background = '#f8f9fa';
                textInput.style.border = '1px solid #ccc';
                textInput.style.padding = '5px 8px';
                textInput.style.width = fileInput.offsetWidth ? fileInput.offsetWidth + 'px' : '100%';
                textInput.value = fileName;
                textInput.readOnly = true;

                if (fileInput.parentElement) {
                    fileInput.parentElement.replaceChild(textInput, fileInput);
                } else {
                    fileInput.remove();
                }
            });



            html2canvas(clone, { scrollY: -window.scrollY, backgroundColor: '#fff', scale: 1, useCORS: true })
            .then(canvas => {
                const imgData = canvas.toDataURL('image/jpeg', 0.6);
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF('p', 'mm', 'a4');
                const margin = 10;
                pdf.addImage(
                    imgData,
                    'JPEG',
                    margin,
                    margin,
                    pdf.internal.pageSize.getWidth() - margin*2,
                    pdf.internal.pageSize.getHeight() - margin*2
                );
                pdf.save(`${printTitleText}.pdf`);
            })
            .catch(err => {
                console.error('PDF generation failed', err);
                alert('Unable to generate PDF. Please try again.');
            });
        });
    };

})();
