document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('vc-textInput');
    const wordCountDisplay = document.getElementById('vc-wordCount'); // Ensure this ID matches your HTML
    const sortOptions = document.getElementById('sortOptions');
    const frequencyTableBody = document.getElementById('vc-frequencyTable').getElementsByTagName('tbody')[0];
    const copyButton = document.getElementById('vc-copyButton');
    const downloadCsvButton = document.getElementById('vc-downloadCsv');

    // Debounce function to limit how often a function can run
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            const later = () => {
                clearTimeout(timeout);
                func.apply(this, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }


    // Function to calculate character frequencies
    function calculateFrequency(text) {
        const words = text.toLowerCase().match(/\b(\w+)\b/g); // Extract words and convert to lowercase
        if (!words) return {}; // Return an empty object if no words are found
        return words.reduce((acc, word) => {
            acc[word] = (acc[word] || 0) + 1;
            return acc;
        }, {});
    }

    // Display character function (handles space and enter)
    function displayChar(char) {
        if (char === ' ') return '[space]';
        if (char === '\n') return '[enter]';
        return char;
    }

    // Format percentage values to remove unnecessary trailing zeros
    function formatPercentage(value) {
        return parseFloat(value.toFixed(2)).toString();
    }

    function updateWordCount(text) {
        // Use match to find words and count them, counting only non-space sequences
        const words = text.match(/\b(\w+)\b/g); // Matches words based on word boundaries
        const wordCount = words ? words.length : 0; // Check if words exist, else set count to 0
        const wordCountDisplay = document.getElementById('vc-wordCount');
        wordCountDisplay.textContent = `Words: ${wordCount}`;
    }
    
    function sanitizeString(str) {
        const temp = document.createElement('div');
        temp.textContent = str;
        return temp.innerHTML;
    }

    // Function to update the frequency table and total row
    function updateFrequencyTable(frequencies) {
    const totalWords = Object.values(frequencies).reduce((acc, count) => acc + count, 0);

    // Map frequency data to rows
    let rows = Object.entries(frequencies).map(([word, count]) => ({
        word: word,
        count: count,
        percentage: totalWords > 0 ? formatPercentage((count / totalWords) * 100) : "0%"
    }));

    // Sort the rows based on current sort selection
    rows = sortRows(rows, sortOptions.value);

    // Clear the table before adding new rows
    frequencyTableBody.innerHTML = '';

    // Append each row to the table
    rows.forEach(row => {
        const truncatedWord = truncateWord(row.word, 20); // Truncate words to manage display space
        const tr = document.createElement('tr');
        tr.innerHTML = `<td title="${sanitizeString(row.word)}">${sanitizeString(truncatedWord)}</td>
                        <td>${sanitizeString(row.count.toString())}</td>
                        <td>${sanitizeString(row.percentage)}%</td>`;
        frequencyTableBody.appendChild(tr);
    });

    // Optionally add a total row at the end for summary
    const totalRow = document.createElement('tr');
    totalRow.style.fontWeight = 'bold';
    totalRow.innerHTML = `<td>Total</td><td>${totalWords}</td><td>${totalWords > 0 ? '100%' : '0%'}</td>`;
    frequencyTableBody.appendChild(totalRow);
}


    // Sorting function
    function sortRows(rows, criteria) {
        switch (criteria) {
            case 'mostOccurrences':
                // Sort primarily by descending occurrences, secondarily by alphabetical order
                return rows.sort((a, b) => {
                    if (b.count === a.count) { // If counts are equal, sort alphabetically
                        return a.word.localeCompare(b.word);
                    }
                    return b.count - a.count;
                });
            case 'leastOccurrences':
                // Sort primarily by ascending occurrences, secondarily by alphabetical order
                return rows.sort((a, b) => {
                    if (a.count === b.count) { // If counts are equal, sort alphabetically
                        return a.word.localeCompare(b.word);
                    }
                    return a.count - b.count;
                });
            case 'az':
                // Sort alphabetically
                return rows.sort((a, b) => a.word.localeCompare(b.word));
            case 'za':
                // Sort in reverse alphabetical order
                return rows.sort((a, b) => b.word.localeCompare(a.word));
            default:
                return rows;
        }
    }
    
    // Function to truncate long words
    function truncateWord(word, maxLength) {
        if (word.length > maxLength) {
            return word.substring(0, maxLength) + '...'; // Truncate and append ellipsis
        }
        return word;
    }
    




    // Function to export table data to CSV
    async function exportToCsv() {
        downloadCsvButton.textContent = 'Preparing CSV...';
        downloadCsvButton.disabled = true;
    
        try {
            await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate delay
    
            let csvContent = "data:text/csv;charset=utf-8,Word,Occurrences,Percentage\n";
            const frequencies = calculateFrequency(textInput.value);
            const totalWords = Object.values(frequencies).reduce((acc, count) => acc + count, 0);
    
            if (totalWords > 0) {
                Object.entries(frequencies).forEach(([word, count]) => {
                    const percentage = formatPercentage((count / totalWords) * 100);
                    csvContent += `${sanitizeString(word)},${count},${percentage}%\n`;
                });
            }
    
            csvContent += "Total," + totalWords + "," + (totalWords > 0 ? "100%" : "0%");
            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "word_frequency.csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            console.error('Error preparing CSV:', error);
        } finally {
            downloadCsvButton.textContent = 'Download as CSV';
            downloadCsvButton.disabled = false;
        }
    }




    // Debounced update for frequency table to optimize performance
    const debouncedUpdateFrequencyTable = debounce(() => {
        const frequencies = calculateFrequency(textInput.value);
        updateFrequencyTable(frequencies);
    }, 300); // 300 ms debounce time

    textInput.addEventListener('input', () => {
        updateWordCount(textInput.value);
        debouncedUpdateFrequencyTable();
    });

    sortOptions.addEventListener('change', () => {
        const frequencies = calculateFrequency(textInput.value);
        updateFrequencyTable(frequencies);
    });

    copyButton.addEventListener('click', () => {
        navigator.clipboard.writeText(textInput.value).then(() => {
            copyButton.textContent = 'Copied!';
            setTimeout(() => { copyButton.textContent = 'Copy Text'; }, 2000);
        }).catch(err => console.error('Error copying text: ', err));
    });

    downloadCsvButton.addEventListener('click', exportToCsv);

    // Ensure the total row is displayed correctly on page load
    updateWordCount(textInput.value);
    debouncedUpdateFrequencyTable(); // Update frequency table initially
});













// 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.`);  
};

//Nav styles on scroll
const scrollHeader = () =>{
    const navbarElement = selectElement('#header');
    if(this.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');
});

