document.addEventListener('DOMContentLoaded', function() {
    const fileInput = document.getElementById('pdfFile');
    const fileLabel = document.getElementById('fileLabel');
    const countWordsBtn = document.getElementById('countWordsBtn');
    const confirmationMessage = document.getElementById('fileDropConfirmation');
    const dragText = document.getElementById('dragText');

    // Drag and drop events
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        fileLabel.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        fileLabel.addEventListener(eventName, () => fileLabel.classList.add('highlight'), false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        fileLabel.addEventListener(eventName, () => fileLabel.classList.remove('highlight'), false);
    });

    fileLabel.addEventListener('drop', handleDrop, false);

    // Change event for file input
    fileInput.addEventListener('change', function() {
        if (fileInput.files.length > 0) {
            const fileName = fileInput.files[0].name;
            displayConfirmation(fileName);
        }
    });

    // Count words button click
    countWordsBtn.addEventListener('click', countWords);
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

function handleDrop(e) {
    let dt = e.dataTransfer;
    let files = dt.files;

    // Assign dropped file to input for further processing
    document.getElementById('pdfFile').files = files;

    if (files.length > 0) {
        displayConfirmation(files[0].name);
    }
}

function displayConfirmation(fileName) {
    // Hide the drag and drop text and show confirmation message
    document.getElementById('dragText').style.display = 'none';
    const confirmationMessage = document.getElementById('fileDropConfirmation');
    confirmationMessage.style.display = 'block';
    confirmationMessage.textContent = `File "${fileName}" successfully uploaded!`;
}

function countWords() {
    const fileInput = document.getElementById('pdfFile');
    const file = fileInput.files[0];
    
    if (!file) {
        alert("Please upload a PDF file.");
        return;
    }

    const fileReader = new FileReader();
    
    fileReader.onload = function() {
        const typedArray = new Uint8Array(this.result);
        
        // Ensure PDF.js is loaded and available
        if (typeof pdfjsLib === 'undefined') {
            alert("PDF.js is not loaded!");
            return;
        }

        pdfjsLib.getDocument(typedArray).promise.then(function(pdf) {
            let totalText = '';
            let countPromises = [];
            
            for (let i = 1; i <= pdf.numPages; i++) {
                countPromises.push(pdf.getPage(i).then(function(page) {
                    return page.getTextContent().then(function(textContent) {
                        const pageText = textContent.items.map(item => item.str).join(' ');
                        totalText += pageText + ' '; // Add a space after each page's text
                    });
                }));
            }
            
            Promise.all(countPromises).then(function() {
                let cleanedText = totalText.replace(/[^a-zA-Z'-\s]/g, '').replace(/\s\s+/g, ' ');
                const words = cleanedText.match(/\b[a-zA-Z']+(?:-\w+)*\b/g);
                const wordCount = words ? words.length : 0;

                document.getElementById('vc-nounCount').textContent = `${wordCount}`;
            });
        });
    };
    
    fileReader.readAsArrayBuffer(file);
    
    // Ensure the PDF.js worker script is correctly referenced
    pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';
}










// Grab elements
const selectElement = (selector) => {
    const element = document.querySelector(selector);
    if(element) return element;
    throw new Error(`Something went wrong! Make sure that ${selector} exists/is typed correctly.`);  
};

const scrollHeader = () => {
    const navbarElement = selectElement('#header');
    if(window.scrollY >= 15) {
        navbarElement.classList.add('activated');
    } else {
        navbarElement.classList.remove('activated');
    }
};


window.addEventListener('scroll', scrollHeader);

// Open menu & search pop-up
const menuToggleIcon = selectElement('#menu-toggle-icon');
//const formOpenBtn = selectElement('#search-icon');
const formCloseBtn = selectElement('#form-close-btn');
const searchContainer = selectElement('#search-form-container');

const toggleMenu = () =>{
    const mobileMenu = selectElement('#menu');
    mobileMenu.classList.toggle('activated');
    menuToggleIcon.classList.toggle('activated');
}

menuToggleIcon.addEventListener('click', toggleMenu);

// Open/Close search form popup
//formOpenBtn.addEventListener('click', () => searchContainer.classList.add('activated'));
formCloseBtn.addEventListener('click', () => searchContainer.classList.remove('activated'));
// -- Close the search form popup on ESC keypress
window.addEventListener('keyup', (event) => {
    if(event.key === 'Escape') searchContainer.classList.remove('activated');
});









