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');
    const caseSensitiveCheckbox = document.getElementById('caseSensitive');

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

    // Initialize frequencies for letters depending on case sensitivity
    function initializeFrequencies(caseSensitive) {
        let frequencies = {};
        if (caseSensitive) {
            // Initialize both uppercase and lowercase
            for (let char = 65; char <= 90; char++) { // A-Z
                frequencies[String.fromCharCode(char)] = 0; // Uppercase
                frequencies[String.fromCharCode(char + 32)] = 0; // Lowercase
            }
        } else {
            // Initialize only uppercase
            for (let char = 65; char <= 90; char++) { // A-Z
                frequencies[String.fromCharCode(char)] = 0;
            }
        }
        return frequencies;
    }

    // Function to calculate letter frequencies
    function calculateFrequency(text, caseSensitive) {
        let frequencies = initializeFrequencies(caseSensitive);
        text.split('').forEach(char => {
            if (char.match(/[a-zA-Z]/)) {
                char = caseSensitive ? char : char.toUpperCase();
                if (frequencies.hasOwnProperty(char)) {
                    frequencies[char] = (frequencies[char] || 0) + 1;
                }
            }
        });
        return frequencies;
    }

    // Format percentage values
    function formatPercentage(value) {
        return parseFloat(value.toFixed(2)).toString() + '%';
    }

    // Update character count to count only letters
    function updateCharacterCount(text) {
        const lettersCount = (text.match(/[a-zA-Z]/g) || []).length;
        characterCountDisplay.textContent = `Letters: ${lettersCount}`;
    }

    // Update the frequency table and total row
    function updateFrequencyTable(frequencies) {
        const totalChars = Object.values(frequencies).reduce((acc, count) => acc + count, 0);
        let rows = Object.entries(frequencies).map(([char, count]) => ({
            char: char,
            count,
            percentage: totalChars > 0 ? formatPercentage((count / totalChars * 100)) : "0%"
        }));

        rows = sortRows(rows, sortOptions.value);

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

        const totalRow = document.createElement('tr');
        totalRow.style.fontWeight = 'bold';
        totalRow.innerHTML = `<td>Total</td><td>${totalChars}</td><td>100%</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;
        }
    }

    // Export table data to CSV
    function exportToCsv() {
        downloadCsvButton.textContent = 'Preparing CSV...';
        downloadCsvButton.disabled = true;

        setTimeout(() => {
            let csvContent = "data:text/csv;charset=utf-8,Character,Occurrences,Percentage\n";
            const frequencies = calculateFrequency(textInput.value, caseSensitiveCheckbox.checked);
            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 += `${char},${count},${percentage}\n`;
                });
            }

            csvContent += "Total," + totalChars + ",100%";
            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "letter_frequency.csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            downloadCsvButton.textContent = 'Download as CSV';
            downloadCsvButton.disabled = false;
        }, 1000);
    }

    const debouncedUpdateFrequencyTable = debounce(() => {
        const frequencies = calculateFrequency(textInput.value, caseSensitiveCheckbox.checked);
        updateFrequencyTable(frequencies);
    }, 300);

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

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

    caseSensitiveCheckbox.addEventListener('change', () => {
        const frequencies = calculateFrequency(textInput.value, caseSensitiveCheckbox.checked);
        updateFrequencyTable(frequencies);
        updateCharacterCount(textInput.value); // Optionally re-count characters
    });

    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);

    // Initial setup
    const initialFrequencies = calculateFrequency('', false);
    updateFrequencyTable(initialFrequencies);
    updateCharacterCount('');
});































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









