document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('vc-textInput');
    const characterCountDisplay = document.getElementById('vc-characterCount');
    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) {
        return text.split('').reduce((acc, char) => {
            acc[char] = (acc[char] || 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();
    }

    // Update character count
    function updateCharacterCount(text) {
        characterCountDisplay.textContent = `Characters: ${text.length}`;
    }
    
    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 totalChars = textInput.value.length;
        let rows = Object.entries(frequencies).map(([char, count]) => ({
            char: displayChar(char),
            count,
            percentage: totalChars > 0 ? formatPercentage((count / totalChars) * 100) : "0"
        }));

        // Sort rows according to current selection
        rows = sortRows(rows, sortOptions.value);

        // Clear existing rows
        frequencyTableBody.innerHTML = '';

        // Append new rows
        rows.forEach(row => {
            const tr = document.createElement('tr');
            tr.innerHTML = `<td>${sanitizeString(row.char)}</td><td>${sanitizeString(row.count.toString())}</td><td>${sanitizeString(row.percentage)}%</td>`;
            frequencyTableBody.appendChild(tr);
        });

        // Add a bold total row
        const totalRow = document.createElement('tr');
        totalRow.style.fontWeight = 'bold';
        const percentageText = totalChars > 0 ? "100%" : "0%";
        totalRow.innerHTML = `<td>Total</td><td>${totalChars}</td><td>${percentageText}</td>`;
        frequencyTableBody.appendChild(totalRow);
    }

    // Sorting function
    function sortRows(rows, criteria) {
        switch (criteria) {
            case 'mostOccurrences':
                return rows.sort((a, b) => b.count - a.count);
            case 'leastOccurrences':
                return rows.sort((a, b) => a.count - b.count);
            case 'az':
                return rows.sort((a, b) => a.char.localeCompare(b.char));
            case 'za':
                return rows.sort((a, b) => b.char.localeCompare(a.char));
            default:
                return rows;
        }
    }

    // Function to export table data to CSV
    async function exportToCsv() {
    downloadCsvButton.textContent = 'Preparing CSV...';
    downloadCsvButton.disabled = true; // Disable the button to prevent multiple clicks

    try {
        await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate delay

        let csvContent = "data:text/csv;charset=utf-8,Character,Occurrences,Percentage\n";
        const frequencies = calculateFrequency(textInput.value);
        const totalChars = Object.values(frequencies).reduce((acc, count) => acc + count, 0);

        if (totalChars > 0) {
            Object.entries(frequencies).forEach(([char, count]) => {
                const percentage = formatPercentage((count / totalChars) * 100);
                csvContent += `${displayChar(char)},${count},${percentage}%\n`;
            });
        }

        csvContent += "Total," + totalChars + "," + (totalChars > 0 ? "100%" : "0%");
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "character_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; // Re-enable the button
    }
}




    // 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', () => {
        updateCharacterCount(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
    updateCharacterCount(textInput.value); // Update character count initially
    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'); // Ensure this ID matches your HTML
    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');
});




















