document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('vc-textInput');
    const wordCountElement = document.getElementById('vc-wordCount');
    const sentenceCountElement = document.getElementById('vc-sentenceCount');
    const copyButton = document.getElementById('vc-copyButton');
    const maxCharacters = 1000000; // Set your maximum character limit here

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

    if (textLength > maxCharacters) {
        displayMaxCharacterWarning();
        return; // Exit the function to prevent further counting
    }

    const sentences = separateSentences(text); // This returns an array of sentences
    runOnSentenceChecker(sentences); // Pass the sentences array directly

    // Update UI
    sentenceCountElement.textContent = sentences.length;
    logSentencesCommaSeparated(); // Log sentences as comma-separated list
}


    function displayMaxCharacterWarning() {
        const message = '1,000,000 character limit';
        wordCountElement.textContent = message;
        sentenceCountElement.textContent = message;
    }

    function sentenceCounter(string) {
        let sentences = separateSentences(string);
        return sentences.length + countOfEmdashQuotation(string);
    }

    function countOfEmdashQuotation(string) {
        let countQuote = (string.match(/—'\n/g) || []).length;
        let countDoubleQuote = (string.match(/—"\n/g) || []).length;
        return countQuote + countDoubleQuote;
    }

    function separateSentences(string) {
    const abbreviationsList = getAbbreviations();
    const stringWithoutSpecialCharacters = string.replaceAll(/[\n\t]+/g, ' ').replace(/[(){}\[\]''""‘’“”]/g, '');
    const words = stringWithoutSpecialCharacters.split(' ');
    let sentences = [];
    let currentSentence = '';

    words.forEach(word => {
        let lastCharacter = word.charAt(word.length - 1);
        // Check if the word ends with a sentence-ending punctuation
        if (['.', '!', '?'].includes(lastCharacter)) {
            if (!abbreviationsList.includes(word.toLowerCase())) {
                currentSentence += ' ' + word;
                // Trim leading and trailing whitespace before adding to the sentences array
                if (currentSentence.trim().length > 0) sentences.push(currentSentence.trim());
                currentSentence = '';
            } else {
                currentSentence += ' ' + word;
            }
        } else {
            currentSentence += ' ' + word;
        }
    });

    return sentences;
}


    function getAbbreviations() {
        const titles = ['Mrs.', 'Mr.', 'Ms.', 'Dr.', 'Prof.', 'Rev.', 'St.'];
        const suffixes = ['Sr.', 'Jr.', 'Gov.'];
        const addressAbbreviations = ['St.', 'Apt.', 'P.O.', 'BLDG.', 'Rm.', 'BLVD.', 'CT.', 'AVE.', 'LN.', 'TER.'];
        const commonAbbreviations = ['A.S.A.P.', 'R.S.V.P.', 'D.O.B', 'A.M.', 'P.M.', 'Dept.', 'L.L.C.', 'Ltd.'];
        return [...titles, ...suffixes, ...addressAbbreviations, ...commonAbbreviations].map(item => item.toLowerCase());
    }

    function logSentencesCommaSeparated() {
        const text = textInput.value;
        const sentences = separateSentences(text);
        const commaSeparatedSentences = sentences.join(", ");
        console.log(commaSeparatedSentences);
    }
    
    function runOnSentenceChecker(sentencesArray) {
    const coordinatingConjunctions = /\b(and|but|for|nor|or|so|yet)\b/g;
    let runOnSentences = sentencesArray.filter(sentence => {
        // Count the occurrences of coordinating conjunctions
        const conjunctionCount = (sentence.match(coordinatingConjunctions) || []).length;
        // Split the sentence into words to count them
        const wordCount = sentence.split(/\s+/).length;

        // Define thresholds for what constitutes a 'long' sentence and 'many' conjunctions
        const isLongSentence = wordCount > 20; // Example threshold
        const hasManyConjunctions = conjunctionCount > 2; // Example threshold

        // A sentence is flagged as a potential run-on if it's long and has many conjunctions
        return isLongSentence && hasManyConjunctions;
    });

    updateRunOnSentenceDisplay(runOnSentences);
}

function updateRunOnSentenceDisplay(runOnSentences) {
    const runOnSentencesDisplay = document.getElementById('runOnSentencesDisplay');
    runOnSentencesDisplay.innerHTML = ''; // Clear existing content

    if (runOnSentences.length > 0) {
        runOnSentences.forEach((sentence, index) => {
            // Create a container for each sentence that uses flexbox layout
            const sentenceContainer = document.createElement('div');
            sentenceContainer.classList.add('sentence-container');
            
            // Create and append the number element
            const numberElement = document.createElement('span');
            numberElement.innerHTML = `<strong>${index + 1}.</strong>`;
            sentenceContainer.appendChild(numberElement);
            
            // Create and append the sentence text element
            const textElement = document.createElement('span');
            textElement.textContent = sentence;
            textElement.classList.add('indented-text');
            sentenceContainer.appendChild(textElement);

            runOnSentencesDisplay.appendChild(sentenceContainer);
        });
    } else {
        const noRunOnMessage = document.createElement('p');
        noRunOnMessage.textContent = 'No run-on sentences detected.';
        runOnSentencesDisplay.appendChild(noRunOnMessage);
    }
    // Update the count display
    document.getElementById('vc-wordCount').textContent = runOnSentences.length;
}








// Ensure you call this function within your input event listener or wherever you update the text analysis


    // Clipboard functionality
    copyButton.addEventListener('click', async () => {
        try {
            await navigator.clipboard.writeText(textInput.value);
            copyButton.textContent = 'Copied!';
            setTimeout(() => copyButton.textContent = 'Copy Text', 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
            // Notify user if copy fails (e.g., due to browser support)
        }
    });

    // Debounced input listener to improve performance
    let debounceTimer;
    textInput.addEventListener('input', () => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            updateCounts();
        }, 300); // Adjust delay as necessary
    });

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




































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









