document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('vc-textInput');
    const vowelCountElement = document.getElementById('vc-vowelCount');
    const consonantCountElement = document.getElementById('vc-consonantCount');
    const letterCountElement = document.getElementById('vc-letterCount');
    const wordCountElement = document.getElementById('vc-wordCount');
    const copyButton = document.getElementById('vc-copyButton');

    const consonants = "bcdfghjklmnpqrstvwxyz".split('');
    const consonantElements = {};
    consonants.forEach(consonant => {
        consonantElements[consonant] = document.getElementById(`vc-consonant${consonant.toUpperCase()}`);
    });

    const maxCharacters = 1000000; // Adjusted for clarity

    function updateCounts() {
        const text = textInput.value.toLowerCase();
        const textLength = text.length;

        if (textLength > maxCharacters) {
            const message = '1,000,000 character limit exceeded.';
            vowelCountElement.textContent = message;
            consonantCountElement.textContent = message;
            letterCountElement.textContent = message;
            wordCountElement.textContent = message;

            // Clear individual consonant counts
            consonants.forEach(consonant => {
                if(consonantElements[consonant]) {
                    consonantElements[consonant].textContent = '';
                }
            });
            return; // Prevent further processing
        }

        const vowels = text.match(/[aeiou]/gi) || [];
        const allConsonants = text.match(/[bcdfghjklmnpqrstvwxyz]/gi) || [];
        const words = text.match(/\S+/g) || [];
        const letters = text.match(/[a-z]/gi) || [];

        vowelCountElement.textContent = vowels.length;
        consonantCountElement.textContent = allConsonants.length;
        letterCountElement.textContent = letters.length;
        wordCountElement.textContent = words.length;

        consonants.forEach(consonant => {
            const consonantCount = (text.match(new RegExp(consonant, "gi")) || []).length;
            if(consonantElements[consonant]) {
                consonantElements[consonant].textContent = consonantCount;
            }
        });
    }

    textInput.addEventListener('input', updateCounts);

    copyButton.addEventListener('click', async () => {
        if (navigator.clipboard) {
            try {
                await navigator.clipboard.writeText(textInput.value);
                copyButton.textContent = 'Copied!';
                setTimeout(() => {
                    copyButton.textContent = 'Copy Text';
                }, 2000);
            } catch (err) {
                console.error('Failed to copy:', err);
            }
        } else {
            textInput.select();
            document.execCommand('copy');
            copyButton.textContent = 'Copied!';
            setTimeout(() => {
                copyButton.textContent = 'Copy Text';
            }, 2000);
        }
    });

    // Initialize counts on page load
    updateCounts();
});

// Additional functionalities related to navigation and menu toggling
document.addEventListener('DOMContentLoaded', () => {
    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);

    const menuToggleIcon = selectElement('#menu-toggle-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);

    formCloseBtn.addEventListener('click', () => searchContainer.classList.remove('activated'));

    window.addEventListener('keyup', (event) => {
        if(event.key === 'Escape') searchContainer.classList.remove('activated');
    });
});
