document.addEventListener('DOMContentLoaded', () => {
    // =================================================================
    // STATE & VARIABLES
    // =================================================================
    let selectedStudent = null;
    let settings = {};
    let certificates = [];
    let activeUserRole = 'Admin'; // Admin, Staff, Principal
    let currentScale = 1.0;
    
    // Elements
    const views = document.querySelectorAll('.view-pane');
    const navButtons = document.querySelectorAll('.nav-btn');
    const userRoleSelect = document.getElementById('user-role');
    const activeUserBadge = document.getElementById('active-user-badge');
    
    // Dashboard Elements
    const searchInput = document.getElementById('student-search-input');
    const autocompleteList = document.getElementById('search-autocomplete-list');
    const btnSearchClear = document.getElementById('btn-search-clear');
    const btnSearchTrigger = document.getElementById('btn-search-trigger');
    const studentProfile = document.getElementById('student-profile');
    const profileDetailsLayout = document.getElementById('profile-details-layout');
    
    // Profile Field Elements
    const lblAdmissionNo = document.getElementById('lbl-admission-no');
    const lblStudentName = document.getElementById('lbl-student-name');
    const lblFatherName = document.getElementById('lbl-father-name');
    const lblDob = document.getElementById('lbl-dob');
    const lblGrade = document.getElementById('lbl-grade');
    const lblBloodGroup = document.getElementById('lbl-blood-group');
    const lblAddress = document.getElementById('lbl-address');
    const lblMobile = document.getElementById('lbl-mobile');
    const profilePhoto = document.getElementById('profile-photo');
    
    // Control Panels
    const dropdownPurpose = document.getElementById('dropdown-purpose');
    const customPurposeContainer = document.getElementById('custom-purpose-container');
    const inputCustomPurpose = document.getElementById('input-custom-purpose');
    const dropdownAuthority = document.getElementById('dropdown-authority');
    const checkboxTwoCopy = document.getElementById('checkbox-two-copy');
    const selectPaperSize = document.getElementById('select-paper-size');
    
    // Action Buttons
    const btnPreview = document.getElementById('btn-preview');
    const btnPdf = document.getElementById('btn-pdf');
    const btnGenerate = document.getElementById('btn-generate');
    
    // History Elements
    const historySearchInput = document.getElementById('history-search-input');
    const historyTableBody = document.getElementById('history-table-body');
    const emptyHistoryState = document.getElementById('empty-history-state');
    
    // Settings Elements
    const setSchoolName = document.getElementById('set-school-name');
    const setAffiliation = document.getElementById('set-affiliation');
    const setMotto = document.getElementById('set-motto');
    const setAddress = document.getElementById('set-address');
    const setMobile = document.getElementById('set-mobile');
    const setEmail = document.getElementById('set-email');
    const setAcademicYear = document.getElementById('set-academic-year');
    const setCertPrefix = document.getElementById('set-cert-prefix');
    const setCertCounter = document.getElementById('set-cert-counter');
    const setPrincipalName = document.getElementById('set-principal-name');
    const setPrincipalTitle = document.getElementById('set-principal-title');
    const btnSaveSettings = document.getElementById('btn-save-settings');
    const prevLogo = document.getElementById('prev-logo');
    const prevSignature = document.getElementById('prev-signature');
    
    // Custom settings folder paths inputs
    const setPhotoFolder = document.getElementById('set-photo-folder');
    const setDatabaseFolder = document.getElementById('set-database-folder');
    
    // Modals & Overlays
    const previewModal = document.getElementById('preview-modal');
    const wordPagesContainer = document.getElementById('word-pages-container');
    const btnModalClose = document.getElementById('btn-modal-close');
    const btnModalPrint = document.getElementById('btn-modal-print');
    const btnZoomWidth = document.getElementById('btn-zoom-width');
    const btnZoomPage = document.getElementById('btn-zoom-page');
    const previewViewport = document.getElementById('preview-viewport');
    
    // Print Container
    const printContainer = document.getElementById('print-container');
    
    // Verification Pane
    const verificationPane = document.getElementById('verification-pane');
    const btnCloseVerify = document.getElementById('btn-close-verify');

    // =================================================================
    // INITIALIZATION
    // =================================================================
    initApp();

    async function initApp() {
        await loadSettings();
        await loadHistory();
        setupNavigation();
        setupSearch();
        setupRoleSimulation();
        setupControls();
        setupUploads();
        setupLogin();
        checkVerificationRoute();
    }

    // =================================================================
    // SETTINGS & LOG LOADING
    // =================================================================
    async function loadSettings() {
        try {
            const res = await fetch('/api/settings');
            settings = await res.json();
            
            // Update UI elements from settings
            document.getElementById('header-academic-year').textContent = `AY ${settings.academicYear}`;
            
            // Populate settings tab
            setSchoolName.value = settings.schoolName || '';
            setAffiliation.value = settings.affiliation || '';
            setMotto.value = settings.motto || '';
            setAddress.value = settings.address || '';
            setMobile.value = settings.mobile || '';
            setEmail.value = settings.email || '';
            setAcademicYear.value = settings.academicYear || '';
            setCertPrefix.value = settings.certificatePrefix || '';
            setCertCounter.value = settings.certificateCounter || 1;
            setPrincipalName.value = settings.principalName || '';
            setPrincipalTitle.value = settings.designation || '';
            
            // Load folder path fields
            if (setPhotoFolder) setPhotoFolder.value = settings.photoFolder || '';
            if (setDatabaseFolder) setDatabaseFolder.value = settings.databaseFolder || '';
            
            // Reload graphic assets previews
            if (prevLogo) {
                prevLogo.style.display = 'block';
                if (prevLogo.nextElementSibling) prevLogo.nextElementSibling.style.display = 'none';
                prevLogo.src = `assets/logo.png?t=${Date.now()}`;
            }
            if (prevSignature) {
                prevSignature.style.display = 'block';
                if (prevSignature.nextElementSibling) prevSignature.nextElementSibling.style.display = 'none';
                prevSignature.src = `assets/signature.png?t=${Date.now()}`;
            }
            const prevSeal = document.getElementById('prev-seal');
            if (prevSeal) {
                prevSeal.style.display = 'block';
                if (prevSeal.nextElementSibling) prevSeal.nextElementSibling.style.display = 'none';
                prevSeal.src = `assets/seal.png?t=${Date.now()}`;
            }
        } catch (err) {
            console.error("Error loading settings:", err);
        }
    }

    async function loadHistory() {
        try {
            const res = await fetch('/api/certificates');
            certificates = await res.json();
            renderHistoryTable(certificates);
        } catch (err) {
            console.error("Error loading history:", err);
        }
    }

    // =================================================================
    // NAVIGATION
    // =================================================================
    function setupNavigation() {
        navButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const target = btn.getAttribute('data-target');
                
                // Toggle nav active state
                navButtons.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                // Toggle view pane visibility
                views.forEach(view => {
                    if (view.id === target) {
                        view.classList.add('active');
                    } else {
                        view.classList.remove('active');
                    }
                });
                
                // Update topbar title
                const titles = {
                    'dashboard-view': 'Student Dashboard',
                    'history-view': 'Certificate History Log',
                    'settings-view': 'ERP Module Settings'
                };
                document.getElementById('current-view-title').textContent = titles[target] || 'Dashboard';
                
                // If switching to history, reload it
                if (target === 'history-view') {
                    loadHistory();
                }
            });
        });
    }

    // =================================================================
    // ROLE SIMULATION
    // =================================================================
    function setupRoleSimulation() {
        userRoleSelect.addEventListener('change', (e) => {
            activeUserRole = e.target.value;
            
            // Update topbar badge
            const badges = {
                'Staff': '<span class="status-indicator online"></span> Office Staff Mode',
                'Admin': '<span class="status-indicator online"></span> Admin Mode',
                'Principal': '<span class="status-indicator online"></span> Principal Mode'
            };
            activeUserBadge.innerHTML = badges[activeUserRole];
            
            // Adjust permission blocks
            applyRolePermissions();
        });
        
        // Initial call
        activeUserRole = userRoleSelect.value;
        applyRolePermissions();
    }

    function applyRolePermissions() {
        // Staff cannot access Settings tab
        const navSettingsBtn = document.getElementById('nav-settings');
        if (activeUserRole === 'Staff') {
            navSettingsBtn.style.display = 'none';
            // If they were on settings page, redirect to dashboard
            if (document.getElementById('settings-view').classList.contains('active')) {
                document.querySelector('[data-target="dashboard-view"]').click();
            }
        } else {
            navSettingsBtn.style.display = 'flex';
        }
        
        // Reload history table to apply new role-based action buttons
        renderHistoryTable(certificates);
    }

    // =================================================================
    // STUDENT SEARCH & AUTOCOMPLETE
    // =================================================================
    function setupSearch() {
        searchInput.addEventListener('input', async (e) => {
            const val = e.target.value.trim();
            closeAutocomplete();
            
            if (!val || val.length < 1) {
                return;
            }
            
            try {
                const res = await fetch(`/api/students?q=${encodeURIComponent(val)}`);
                const matches = await res.json();
                
                if (matches.length === 0) {
                    return;
                }
                
                const listContainer = document.createElement("div");
                listContainer.setAttribute("id", "autocomplete-list-container");
                listContainer.setAttribute("class", "autocomplete-items");
                searchInput.parentNode.appendChild(listContainer);
                
                matches.forEach(student => {
                    const row = document.createElement("div");
                    row.innerHTML = `<span class="autocomplete-name">${student.StudentName}</span><span class="autocomplete-adm">ID: ${student.AdmissionNo} (${student.Grade})</span>`;
                    
                    row.addEventListener('click', () => {
                        selectStudent(student);
                        closeAutocomplete();
                    });
                    
                    listContainer.appendChild(row);
                });
            } catch (err) {
                console.error("Autocomplete search error:", err);
            }
        });
        
        // Close autocomplete when clicking outside
        document.addEventListener("click", (e) => {
            if (e.target !== searchInput) {
                closeAutocomplete();
            }
        });
        
        async function performSearch() {
            const val = searchInput.value.trim();
            if (!val) return;
            
            try {
                const res = await fetch(`/api/students?q=${encodeURIComponent(val)}`);
                const matches = await res.json();
                
                if (matches.length > 0) {
                    selectStudent(matches[0]);
                    closeAutocomplete();
                } else {
                    alert("No student found matching that name or admission number. You can type their details manually below.");
                }
            } catch (err) {
                console.error("Search trigger error:", err);
                alert("Search failed. Please check your connection.");
            }
        }
        
        btnSearchTrigger.addEventListener('click', performSearch);
        
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                performSearch();
            }
        });

        btnSearchClear.addEventListener('click', () => {
            searchInput.value = '';
            resetStudentSelection();
        });

        // Add listeners for manual entry verification
        lblAdmissionNo.addEventListener('input', updateActionButtonsState);
        lblStudentName.addEventListener('input', updateActionButtonsState);
        
        // Initial button check
        updateActionButtonsState();
    }

    function closeAutocomplete() {
        const item = document.getElementById("autocomplete-list-container");
        if (item) {
            item.parentNode.removeChild(item);
        }
    }

    function selectStudent(student) {
        selectedStudent = student;
        searchInput.value = `${student.StudentName} (${student.AdmissionNo})`;
        
        // Update input values
        lblAdmissionNo.value = student.AdmissionNo || '';
        lblStudentName.value = student.StudentName || '';
        lblFatherName.value = student.FatherName || '';
        lblDob.value = student.DOB || '';
        lblGrade.value = student.Grade || '';
        lblBloodGroup.value = student.BloodGroup || '';
        lblAddress.value = student.Address || '';
        lblMobile.value = student.Mobile || '';
        
        // Handle photo load using dynamic lookup endpoint
        profilePhoto.src = `/api/photos/${student.ImageNo}?adm=${student.AdmissionNo}&name=${encodeURIComponent(student.StudentName)}&emis=${student.EMISNo}`;
        profilePhoto.onerror = () => {
            profilePhoto.src = 'assets/default-avatar.svg';
        };
        
        // Setup gender prefix radioactive toggle
        const isMaster = detectGenderIsBoy(student.StudentName);
        if (isMaster) {
            document.querySelector('input[name="gender-prefix"][value="Master"]').checked = true;
        } else {
            document.querySelector('input[name="gender-prefix"][value="Miss"]').checked = true;
        }
        
        updateActionButtonsState();
    }

    function resetStudentSelection() {
        selectedStudent = null;
        
        lblAdmissionNo.value = '';
        lblStudentName.value = '';
        lblFatherName.value = '';
        lblDob.value = '';
        lblGrade.value = '';
        lblBloodGroup.value = '';
        lblAddress.value = '';
        lblMobile.value = '';
        profilePhoto.src = 'assets/default-avatar.svg';
        
        updateActionButtonsState();
    }

    function updateActionButtonsState() {
        const hasName = lblStudentName.value.trim().length > 0;
        const hasAdm = lblAdmissionNo.value.trim().length > 0;
        const enabled = hasName && hasAdm;
        
        btnPreview.disabled = !enabled;
        btnPdf.disabled = !enabled;
        btnGenerate.disabled = !enabled;
    }

    // Helper: heuristically detect if the student is a boy/girl based on name
    function detectGenderIsBoy(name) {
        if (!name) return true;
        const n = name.toUpperCase();
        
        // Girls names indicators
        const girlsSuffixes = [
            'FATHIMA', 'AYSHA', 'SULAIHA', 'JASEENA', 'YASHVI', 'LAKISHA', 
            'HANYA', 'KARSHITHA', 'AYANA', 'KRISHIKA', 'SRI', 'MARIYAM', 
            'HIBAH', 'ARSHIYA', 'SAJIHA', 'KANISHKA', 'MUBEENA', 'RIFA', 
            'NOWRIN', 'SARIFFA', 'THASRIN', 'FAZRINA', 'HUMAIRA', 'FAEEZAH', 
            'SHAIMA', 'RAJEENA'
        ];
        
        for (let suffix of girlsSuffixes) {
            if (n.includes(suffix)) {
                return false;
            }
        }
        return true;
    }

    // =================================================================
    // CONTROLS & PURPOSE INPUT
    // =================================================================
    function setupControls() {
        dropdownPurpose.addEventListener('change', (e) => {
            if (e.target.value === 'Other') {
                customPurposeContainer.classList.remove('hidden');
            } else {
                customPurposeContainer.classList.add('hidden');
            }
        });
        
        // Settings Tab
        btnSaveSettings.addEventListener('click', saveSettingsHandler);
    }

    // =================================================================
    // SETTINGS SAVING
    // =================================================================
    async function saveSettingsHandler() {
        const payload = {
            schoolName: setSchoolName.value,
            affiliation: setAffiliation.value,
            motto: setMotto.value,
            address: setAddress.value,
            mobile: setMobile.value,
            email: setEmail.value,
            academicYear: setAcademicYear.value,
            certificatePrefix: setCertPrefix.value,
            certificateCounter: parseInt(setCertCounter.value) || 1,
            principalName: setPrincipalName.value,
            designation: setPrincipalTitle.value,
            photoFolder: setPhotoFolder.value,
            databaseFolder: setDatabaseFolder.value
        };
        
        try {
            const res = await fetch('/api/settings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            
            const data = await res.json();
            if (data.success) {
                alert("Settings saved successfully!");
                await loadSettings();
            } else {
                alert(`Error: ${data.message}`);
            }
        } catch (err) {
            console.error("Error saving settings:", err);
            alert("Network error saving settings.");
        }
    }

    // =================================================================
    // CERTIFICATE GENERATION & PRINT FLOW
    // =================================================================
    
    // Dynamic ROMAN NUMERALS for Grades 1 to 12
    function getGradeRoman(gradeStr) {
        if (!gradeStr) return '';
        const num = parseInt(gradeStr);
        if (isNaN(num)) {
            return gradeStr;
        }
        
        const romanMap = {
            1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 
            6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X', 
            11: 'XI', 12: 'XII'
        };
        
        return `Grade ${romanMap[num] || gradeStr}`;
    }

    function getSelectedPurpose() {
        if (dropdownPurpose.value === 'Other') {
            return inputCustomPurpose.value.trim() || 'Official Purpose';
        }
        return dropdownPurpose.value;
    }

    // Generate action button
    btnGenerate.addEventListener('click', async () => {
        const admissionNo = lblAdmissionNo.value.trim();
        const studentName = lblStudentName.value.trim();
        const fatherName = lblFatherName.value.trim();
        const dob = lblDob.value.trim();
        const grade = lblGrade.value.trim();
        
        if (!admissionNo || !studentName) return;
        
        const prefix = document.querySelector('input[name="gender-prefix"]:checked').value;
        const purpose = getSelectedPurpose();
        
        const payload = {
            admissionNo,
            studentName,
            fatherName,
            dob,
            grade,
            purpose,
            printedBy: activeUserRole
        };
        
        try {
            const res = await fetch('/api/certificates', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            
            if (data.success) {
                // Refresh local data (counter increments)
                await loadSettings();
                await loadHistory();
                
                // RENDER PAGES FOR PRINTING
                await renderCertificatePrintJob(data.certificate, prefix);
                
                // Trigger print
                window.print();
            } else {
                alert(`Generation failed: ${data.message}`);
            }
        } catch (err) {
            console.error("Error generating certificate:", err);
            alert("Error connecting to database server.");
        }
    });

    // Preview action button
    btnPreview.addEventListener('click', async () => {
        const admissionNo = lblAdmissionNo.value.trim();
        const studentName = lblStudentName.value.trim();
        const fatherName = lblFatherName.value.trim();
        const dob = lblDob.value.trim();
        const grade = lblGrade.value.trim();
        
        if (!admissionNo || !studentName) return;
        
        const prefix = document.querySelector('input[name="gender-prefix"]:checked').value;
        const purpose = getSelectedPurpose();
        
        // Mock a certificate object for layout preview
        const mockCert = {
            certificateNo: `${settings.certificatePrefix}${String(settings.certificateCounter).padStart(6, '0')} (PREVIEW)`,
            admissionNo,
            studentName,
            fatherName,
            dob,
            grade,
            purpose,
            issueDate: new Date().toLocaleDateString('en-GB')
        };
        
        await openPreviewModal(mockCert, prefix);
    });

    // PDF Export action button
    btnPdf.addEventListener('click', async () => {
        const admissionNo = lblAdmissionNo.value.trim();
        const studentName = lblStudentName.value.trim();
        if (!admissionNo || !studentName) return;
        
        if (confirm("Generating this PDF will lock the certificate in the printed history. Proceed?")) {
            btnGenerate.click();
        }
    });

    // =================================================================
    // LAYOUT TEMPLATE ENGINE
    // =================================================================
    async function createHtmlPage(cert, genderPrefix, copyType) {
        const pronoun = genderPrefix === 'Master' ? 'Son' : 'Daughter';
        const formattedGrade = getGradeRoman(cert.grade);
        
        const bodyHtml = `This is to certify that <span class="var">${genderPrefix} ${cert.studentName}</span>, Admission No. <span class="var">${cert.admissionNo}</span>, ${pronoun} of <span class="var">${cert.fatherName}</span>, born on <span class="var">${cert.dob}</span>, is a bonafide student of <span class="var">${settings.schoolName}</span>, Perungulam, Ramanathapuram District, Tamil Nadu. The student is presently studying in <span class="var">${formattedGrade} – Section A</span> during the Academic Year <span class="var">${settings.academicYear}</span>. This certificate is issued at the request of the student/parent for official purposes.`;

        // Generate QR code encoding plain text details so scanning works offline on any device
        const qrText = `AQIS BONAFIDE CERTIFICATE VERIFICATION
-------------------------------------
Certificate No: ${cert.certificateNo}
Admission No: ${cert.admissionNo}
Student Name: ${genderPrefix} ${cert.studentName}
DOB: ${cert.dob || ''}
Class/Grade: ${formattedGrade} - Section A
School: ${settings.schoolName}`;

        let qrDataUrl = '';
        try {
            const qrRes = await fetch(`/api/qrcode?text=${encodeURIComponent(qrText)}`);
            const qrData = await qrRes.json();
            qrDataUrl = qrData.qrDataUrl;
        } catch (e) {
            console.error("Failed to generate QR data URL:", e);
        }

        // Check signatory authority details
        let signatureImgHtml = '';
        let signTitle = 'Principal';
        
        if (dropdownAuthority.value === 'Principal') {
            signatureImgHtml = `<img src="assets/signature.png" class="cert-signature-img" onerror="this.style.display='none'">`;
            signTitle = settings.principalName ? `${settings.principalName}<br>${settings.designation}` : 'Principal';
        } else if (dropdownAuthority.value === 'Administrative Officer') {
            signTitle = 'Administrative Officer';
        } else {
            signTitle = 'Authorized Signatory';
        }

        // Build copying details with specific office fields (Received sign, purpose, printedBy, printDate)
        let footerBannerHtml = '';
        if (copyType === 'Student') {
            footerBannerHtml = `
                <div class="cert-copy-type">STUDENT / PARENT COPY</div>
                <div>Digitally Generated • No Signature Required • QR Verification Available</div>
            `;
        } else {
            const currentDate = new Date().toLocaleDateString('en-GB');
            footerBannerHtml = `
                <div class="cert-copy-type">OFFICE COPY</div>
                <div style="font-size: 8pt; display: flex; justify-content: space-between; width: 100%;">
                    <span>Issued By: ${cert.printedBy || 'Staff'}</span>
                    <span>Purpose: ${cert.purpose}</span>
                    <span>Print Date: ${currentDate}</span>
                    <span>Received Sign: _____________________</span>
                </div>
            `;
        }

        // Watermark Overlay tags (Only for Office Copy)
        const watermarkTextHtml = copyType === 'Student' ? '' : `<div class="cert-text-watermark">OFFICE COPY</div>`;

        // Image lookup using admission parameters
        const studentPhotoUrl = `/api/photos/default?adm=${cert.admissionNo}&name=${encodeURIComponent(cert.studentName)}`;

        const html = `
            <div class="print-page">
                <div class="cert-watermark" style="background-image: url('assets/logo.png')"></div>
                ${watermarkTextHtml}
                <div class="cert-border">
                    
                    <!-- Header -->
                    <div class="cert-header">
                        <div class="cert-logo-box">
                            <img src="assets/logo.png" onerror="this.src='assets/default-avatar.svg'">
                        </div>
                        <div class="cert-title-box">
                            <h2 class="cert-school-name">${settings.schoolName}</h2>
                            <div class="cert-school-meta">${settings.affiliation}</div>
                            <div class="cert-school-motto">${settings.motto}</div>
                        </div>
                        <div class="cert-contact-box">
                            Address: ${settings.address}<br>
                            Mobile: ${settings.mobile}<br>
                            Email: ${settings.email}
                        </div>
                    </div>
                    
                    <!-- Meta info row -->
                    <div class="cert-body-header">
                        <div class="cert-meta-item">
                            <span class="cert-num-lbl">Certificate No: <span class="cert-num-val">${cert.certificateNo}</span></span>
                        </div>
                        <div class="cert-meta-item">
                            <span>Date: <span class="cert-date-val">${cert.issueDate}</span></span>
                        </div>
                    </div>
                    
                    <!-- Title -->
                    <div class="cert-type-title">
                        <h2>BONAFIDE CERTIFICATE</h2>
                    </div>
                    
                    <!-- Content layout -->
                    <div class="cert-content-layout">
                        <div class="cert-body-text">
                            ${bodyHtml}
                        </div>
                        <div class="cert-photo-box">
                            <img src="${studentPhotoUrl}" onerror="this.src='assets/default-avatar.svg'">
                        </div>
                    </div>
                    
                    <!-- Signatures, seal and QR -->
                    <div class="cert-footer-layout">
                        <!-- Seal Place -->
                        <div class="cert-seal-area" style="position: relative; display: flex; align-items: center; justify-content: center;">
                            <img src="assets/seal.png?t=${Date.now()}" class="cert-seal-img" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">
                            <div class="dummy-seal" style="display: flex;"></div>
                        </div>
                        
                        <!-- Signature -->
                        <div class="cert-sign-area">
                            ${signatureImgHtml}
                            <div class="cert-sign-lbl">Signature</div>
                            <div class="cert-sign-title">${signTitle}</div>
                        </div>
                        
                        <!-- QR Code -->
                        <div class="cert-qr-area">
                            ${qrDataUrl ? `<img src="${qrDataUrl}" class="cert-qr-img">` : ''}
                        </div>
                    </div>
                    
                    <!-- Copy flag banner footer -->
                    <div class="cert-copy-banner">
                        ${footerBannerHtml}
                    </div>
                </div>
            </div>
        `;
        
        return html;
    }

    // Print Job Renderer
    async function renderCertificatePrintJob(cert, prefix) {
        printContainer.className = 'print-container'; // reset
        const paperFormat = selectPaperSize.value; // A5 or A4
        printContainer.classList.add(`format-${paperFormat.toLowerCase()}`);
        
        let htmlContent = '';
        
        if (checkboxTwoCopy.checked) {
            htmlContent += await createHtmlPage(cert, prefix, 'Student');
            htmlContent += await createHtmlPage(cert, prefix, 'Office');
        } else {
            htmlContent += await createHtmlPage(cert, prefix, 'Student');
        }
        
        printContainer.innerHTML = htmlContent;
    }

    // =================================================================
    // PRINT PREVIEW MODAL WORKFLOW
    // =================================================================
    async function openPreviewModal(cert, prefix) {
        previewModal.classList.add('active');
        wordPagesContainer.innerHTML = 'Rendering preview...';
        
        const paperFormat = selectPaperSize.value; // A5 or A4
        wordPagesContainer.className = 'word-pages-container'; // reset
        
        let htmlContent = '';
        if (paperFormat === 'A4') {
            wordPagesContainer.classList.add('format-a4-preview');
            if (checkboxTwoCopy.checked) {
                htmlContent += await createHtmlPage(cert, prefix, 'Student');
                htmlContent += await createHtmlPage(cert, prefix, 'Office');
            } else {
                htmlContent += await createHtmlPage(cert, prefix, 'Student');
            }
        } else {
            if (checkboxTwoCopy.checked) {
                htmlContent += await createHtmlPage(cert, prefix, 'Student');
                htmlContent += await createHtmlPage(cert, prefix, 'Office');
            } else {
                htmlContent += await createHtmlPage(cert, prefix, 'Student');
            }
        }
        
        wordPagesContainer.innerHTML = htmlContent;
        
        await renderCertificatePrintJob(cert, prefix);
        fitPageZoom();
    }

    // Zoom Functions
    btnZoomWidth.addEventListener('click', () => {
        const viewportWidth = previewViewport.clientWidth - 64;
        const pageElement = wordPagesContainer.querySelector('.print-page');
        if (!pageElement) return;
        
        const pageWidth = pageElement.clientWidth;
        currentScale = viewportWidth / pageWidth;
        applyZoom();
    });

    btnZoomPage.addEventListener('click', fitPageZoom);

    function fitPageZoom() {
        const viewportHeight = previewViewport.clientHeight - 64;
        const containerHeight = wordPagesContainer.scrollHeight || 600;
        
        currentScale = Math.min(1.0, viewportHeight / containerHeight);
        applyZoom();
    }

    function applyZoom() {
        wordPagesContainer.style.transform = `scale(${currentScale})`;
    }

    // Close preview modal
    btnModalClose.addEventListener('click', () => {
        previewModal.classList.remove('active');
    });

    // Print directly from preview modal
    btnModalPrint.addEventListener('click', () => {
        window.print();
    });

    // =================================================================
    // HISTORY RENDER & OPERATIONS
    // =================================================================
    function renderHistoryTable(certs) {
        historyTableBody.innerHTML = '';
        
        if (certs.length === 0) {
            emptyHistoryState.classList.remove('hidden');
            return;
        }
        emptyHistoryState.classList.add('hidden');
        
        const reversedCerts = [...certs].reverse();
        
        reversedCerts.forEach(cert => {
            const tr = document.createElement('tr');
            const status = cert.status || 'Active';
            const statusClass = status.toLowerCase() === 'active' ? 'active' : 'cancelled';
            
            let actionButtons = '';
            
            // 1. Reprint button
            const disableReprint = status === 'Cancelled' ? 'disabled' : '';
            actionButtons += `
                <button class="btn btn-outline btn-table" id="btn-reprint-${cert.id}" ${disableReprint}>
                    Reprint
                </button>
            `;
            
            // 2. Cancel button (Only for Admin & Principal)
            if (activeUserRole === 'Admin' || activeUserRole === 'Principal') {
                const disableCancel = status === 'Cancelled' ? 'disabled' : '';
                actionButtons += `
                    <button class="btn btn-table btn-table-cancel" id="btn-cancel-${cert.id}" ${disableCancel}>
                        Cancel
                    </button>
                `;
            }
            
            // 3. Delete button (Only for Admin)
            if (activeUserRole === 'Admin') {
                actionButtons += `
                    <button class="btn btn-table btn-table-delete" id="btn-delete-${cert.id}">
                        Delete
                    </button>
                `;
            }
            
            tr.innerHTML = `
                <td><strong>${cert.certificateNo || 'N/A'}</strong></td>
                <td>${cert.admissionNo || 'N/A'}</td>
                <td>${cert.studentName || 'N/A'}</td>
                <td>Grade ${cert.grade || 'N/A'}</td>
                <td>${cert.purpose || 'N/A'}</td>
                <td>${cert.issueDate || 'N/A'}</td>
                <td>${cert.printedBy || 'Staff'}</td>
                <td><span class="status-badge ${statusClass}">${status}</span></td>
                <td>
                    <div class="table-action-row">
                        ${actionButtons}
                    </div>
                </td>
            `;
            
            historyTableBody.appendChild(tr);
            
            const reprintBtn = tr.querySelector(`#btn-reprint-${cert.id}`);
            if (reprintBtn) {
                reprintBtn.addEventListener('click', () => reprintHandler(cert));
            }
            
            const cancelBtn = tr.querySelector(`#btn-cancel-${cert.id}`);
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => cancelHandler(cert));
            }
            
            const deleteBtn = tr.querySelector(`#btn-delete-${cert.id}`);
            if (deleteBtn) {
                deleteBtn.addEventListener('click', () => deleteHandler(cert));
            }
        });
    }

    // Reprint Handler
    async function reprintHandler(cert) {
        const isMaster = detectGenderIsBoy(cert.studentName);
        const prefix = isMaster ? 'Master' : 'Miss';
        await openPreviewModal(cert, prefix);
    }

    // Cancel Handler
    async function cancelHandler(cert) {
        if (!confirm(`Are you sure you want to cancel Certificate No ${cert.certificateNo}?`)) {
            return;
        }
        
        try {
            const res = await fetch(`/api/certificates/cancel/${cert.id}`, { method: 'POST' });
            const data = await res.json();
            
            if (data.success) {
                alert(`Certificate No ${cert.certificateNo} has been Cancelled.`);
                await loadHistory();
            } else {
                alert(`Cancellation failed: ${data.message}`);
            }
        } catch (e) {
            console.error(e);
            alert("Error sending request to server.");
        }
    }

    // Delete Handler
    async function deleteHandler(cert) {
        if (!confirm(`Warning: This will permanently delete Certificate No ${cert.certificateNo} from the log database. Proceed?`)) {
            return;
        }
        
        try {
            const res = await fetch(`/api/certificates/${cert.id}`, { method: 'DELETE' });
            const data = await res.json();
            
            if (data.success) {
                alert("Record deleted.");
                await loadHistory();
            } else {
                alert(`Deletion failed: ${data.message}`);
            }
        } catch (e) {
            console.error(e);
            alert("Error sending request to server.");
        }
    }

    // Filter History search
    historySearchInput.addEventListener('input', (e) => {
        const val = e.target.value.toLowerCase().trim();
        
        if (!val) {
            renderHistoryTable(certificates);
            return;
        }
        
        const filtered = certificates.filter(c => 
            c.certificateNo.toLowerCase().includes(val) ||
            c.studentName.toLowerCase().includes(val) ||
            c.admissionNo.toLowerCase().includes(val) ||
            c.purpose.toLowerCase().includes(val)
        );
        renderHistoryTable(filtered);
    });

    // =================================================================
    // QR SCANNED VERIFICATION SIMULATION
    // =================================================================
    function checkVerificationRoute() {
        const params = new URLSearchParams(window.location.search);
        const verifyCertNo = params.get('verify');
        
        if (verifyCertNo) {
            const queryAdm = params.get('adm') || 'N/A';
            const queryDob = params.get('dob') || 'N/A';
            const queryGrade = params.get('grade') || 'N/A';
            const queryName = params.get('name') || 'UNKNOWN';
            
            fetch('/api/certificates')
                .then(res => res.json())
                .then(certs => {
                    const cert = certs.find(c => c.certificateNo === verifyCertNo);
                    if (cert) {
                        displayVerification(cert, true);
                    } else {
                        // Display verified details loaded dynamically from the QR code parameters fallback
                        displayVerification({
                            certificateNo: verifyCertNo,
                            studentName: queryName,
                            admissionNo: queryAdm,
                            grade: queryGrade,
                            dob: queryDob,
                            issueDate: new Date().toLocaleDateString('en-GB'),
                            status: 'Active'
                        }, true);
                    }
                })
                .catch(err => {
                    console.error(err);
                    // Fallback to URL parameters if server connection is offline
                    displayVerification({
                        certificateNo: verifyCertNo,
                        studentName: queryName,
                        admissionNo: queryAdm,
                        grade: queryGrade,
                        dob: queryDob,
                        issueDate: new Date().toLocaleDateString('en-GB'),
                        status: 'Active'
                    }, true);
                });
        }
    }

    function displayVerification(cert, isValid) {
        verificationPane.classList.remove('hidden');
        
        const statusBox = verificationPane.querySelector('.verification-status');
        const verifyCertNoLbl = document.getElementById('verify-cert-no');
        const verifyNameLbl = document.getElementById('verify-student-name');
        const verifyAdmLbl = document.getElementById('verify-admission-no');
        const verifyDobLbl = document.getElementById('verify-dob');
        const verifyGradeLbl = document.getElementById('verify-grade');
        const verifyDateLbl = document.getElementById('verify-date');
        
        verifyCertNoLbl.textContent = cert.certificateNo || 'N/A';
        verifyNameLbl.textContent = cert.studentName || 'N/A';
        verifyAdmLbl.textContent = cert.admissionNo || 'N/A';
        verifyGradeLbl.textContent = getGradeRoman(cert.grade);
        verifyDateLbl.textContent = cert.issueDate || 'N/A';
        if (verifyDobLbl) {
            verifyDobLbl.textContent = cert.dob || 'N/A';
        }
        
        const status = cert.status || 'Active';
        if (isValid && status !== 'Cancelled') {
            statusBox.className = 'verification-status success';
            statusBox.innerHTML = `
                <svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                <h3>BONAFIDE CERTIFICATE VALID</h3>
            `;
        } else {
            statusBox.className = 'verification-status error';
            statusBox.innerHTML = `
                <svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="#ef4444" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" style="background-color: #fee2e2; border-radius: 50%; padding: 8px;"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                <h3 style="color: #ef4444;">${status === 'Cancelled' ? 'CERTIFICATE CANCELLED' : 'INVALID CERTIFICATE RECORD'}</h3>
            `;
        }
    }

    btnCloseVerify.addEventListener('click', () => {
        verificationPane.classList.add('hidden');
        window.history.replaceState({}, document.title, window.location.pathname);
    });

    function setupUploads() {
        // 1. Student photo upload listener
        const studentPhotoUpload = document.getElementById('student-photo-upload');
        if (studentPhotoUpload) {
            studentPhotoUpload.addEventListener('change', async (e) => {
                const file = e.target.files[0];
                if (!file) return;
                
                const admissionNo = lblAdmissionNo.value.trim();
                if (!admissionNo) {
                    alert("Please select a student or type an Admission No before uploading a photo.");
                    studentPhotoUpload.value = '';
                    return;
                }
                
                const reader = new FileReader();
                reader.onloadend = async () => {
                    const base64Data = reader.result;
                    try {
                        const res = await fetch('/api/upload/student-photo', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ admissionNo, imageData: base64Data })
                        });
                        const data = await res.json();
                        if (data.success) {
                            alert("Student photo uploaded and synchronized successfully!");
                            profilePhoto.src = `${data.url}&t=${Date.now()}`;
                        } else {
                            alert(`Upload failed: ${data.message}`);
                        }
                    } catch (err) {
                        console.error(err);
                        alert("Network error uploading photo.");
                    }
                };
                reader.readAsDataURL(file);
                studentPhotoUpload.value = '';
            });
        }
        
        // 2. Logo upload listener
        const uploadLogo = document.getElementById('upload-logo');
        if (uploadLogo) {
            uploadLogo.addEventListener('change', (e) => handleAssetUpload(e, 'logo'));
        }
        
        // 3. Signature upload listener
        const uploadSignature = document.getElementById('upload-signature');
        if (uploadSignature) {
            uploadSignature.addEventListener('change', (e) => handleAssetUpload(e, 'signature'));
        }
        
        // 4. Seal upload listener
        const uploadSeal = document.getElementById('upload-seal');
        if (uploadSeal) {
            uploadSeal.addEventListener('change', (e) => handleAssetUpload(e, 'seal'));
        }

        // 5. Delete asset buttons listeners
        const deleteAssetButtons = document.querySelectorAll('.btn-delete-asset');
        deleteAssetButtons.forEach(btn => {
            btn.addEventListener('click', async (e) => {
                const assetType = btn.getAttribute('data-asset');
                if (!confirm(`Are you sure you want to delete the ${assetType}? This will revert to the default placeholder.`)) {
                    return;
                }
                try {
                    const res = await fetch(`/api/assets/${assetType}`, { method: 'DELETE' });
                    const data = await res.json();
                    if (data.success) {
                        alert(`${assetType.charAt(0).toUpperCase() + assetType.slice(1)} deleted successfully!`);
                        
                        let imgEl = null;
                        if (assetType === 'logo') imgEl = prevLogo;
                        else if (assetType === 'signature') imgEl = prevSignature;
                        else if (assetType === 'seal') imgEl = document.getElementById('prev-seal');
                        
                        if (imgEl) {
                            imgEl.style.display = 'none';
                            if (imgEl.nextElementSibling) imgEl.nextElementSibling.style.display = 'block';
                            imgEl.removeAttribute('src');
                        }
                    } else {
                        alert(`Deletion failed: ${data.message}`);
                    }
                } catch (err) {
                    console.error(err);
                    alert("Network error deleting asset.");
                }
            });
        });
    }
    
    async function handleAssetUpload(e, assetType) {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onloadend = async () => {
            const base64Data = reader.result;
            try {
                const res = await fetch('/api/upload/asset', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ assetType, imageData: base64Data })
                });
                const data = await res.json();
                if (data.success) {
                    alert(`${assetType.charAt(0).toUpperCase() + assetType.slice(1)} graphic uploaded successfully!`);
                    
                    let imgEl = null;
                    if (assetType === 'logo') imgEl = prevLogo;
                    else if (assetType === 'signature') imgEl = prevSignature;
                    else if (assetType === 'seal') imgEl = document.getElementById('prev-seal');
                    
                    if (imgEl) {
                        imgEl.style.display = 'block';
                        if (imgEl.nextElementSibling) imgEl.nextElementSibling.style.display = 'none';
                        imgEl.src = `assets/${assetType}.png?t=${Date.now()}`;
                    }
                } else {
                    alert(`Upload failed: ${data.message}`);
                }
            } catch (err) {
                console.error(err);
                alert("Network error uploading asset.");
            }
        };
        reader.readAsDataURL(file);
        e.target.value = '';
    }

    function setupLogin() {
        const loginOverlay = document.getElementById('login-overlay');
        const loginUsernameInput = document.getElementById('login-username');
        const loginPasswordInput = document.getElementById('login-password');
        const loginErrorMsg = document.getElementById('login-error-msg');
        const btnLoginSubmit = document.getElementById('btn-login-submit');
        
        if (!loginOverlay) return;
        
        // Skip login if checking verification route
        const params = new URLSearchParams(window.location.search);
        if (params.get('verify')) {
            loginOverlay.classList.add('hidden');
            return;
        }
        
        btnLoginSubmit.addEventListener('click', executeLogin);
        loginPasswordInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') executeLogin();
        });
        
        function executeLogin() {
            const user = loginUsernameInput.value.trim().toLowerCase();
            const pass = loginPasswordInput.value.trim();
            
            let matchedRole = '';
            if (user === 'admin' && pass === 'admin') {
                matchedRole = 'Admin';
            } else if (user === 'staff' && pass === 'staff') {
                matchedRole = 'Staff';
            } else if (user === 'principal' && pass === 'principal') {
                matchedRole = 'Principal';
            }
            
            if (matchedRole) {
                userRoleSelect.value = matchedRole;
                userRoleSelect.dispatchEvent(new Event('change'));
                
                loginOverlay.classList.add('hidden');
                loginErrorMsg.classList.add('hidden');
            } else {
                loginErrorMsg.classList.remove('hidden');
            }
        }
    }

});
