import { nounSet } from './nouns.js';


document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('vc-textInput');
    const characterCountElement = document.getElementById('vc-characterCount');
    const nounCountElement = document.getElementById('vc-nounCount');
    const nounListElement = document.getElementById('vc-nounList');
    const copyButton = document.getElementById('vc-copyButton');

    

    const excludedWords = new Set([
        'Mr.', 'Mrs.', 'Ms.', 'A.M.', 'P.M.', 'Dr.'
    ]);

    const properNouns = new Set([
        'chicago', 'america', 'london',
    ]);

    // Debounce function
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    }

    const updateNounCountAndList = (words, amount) => {
        nounCountElement.textContent = amount;
        if (words.length > 0) {
            nounListElement.textContent = words.join(', ');
        } else {
            nounListElement.textContent = '';
        }
    };

    const updateCharacterCount = () => {
        const characterCount = textInput.value.length;
        characterCountElement.textContent = "Characters: " + characterCount;
    };

    const checkInput = (text, nounSet, properNouns) => {
        if (!text || text.trim() === "") {
            return "Please provide some text";
        }
        let words = [];
        let inputTextWithoutExcludedWords = replaceExcludedWordsWithPattern(text, excludedWords, '<r>');
        let amount = 0;
        let sentences = inputTextWithoutExcludedWords.split(".");
        sentences.forEach(sentence => {
            if (sentence !== "") {
                let wordsFound = countWordsWithinSentence(sentence, nounSet, properNouns);
                wordsFound.forEach(word => {
                    words.push(word);
                    amount++;
                });
            }
        });

        updateNounCountAndList(words, amount);
    };

    const countWordsWithinSentence = (sentence, nounSet, properNouns) => {
        let words = [];
        let splitSentence = sentence.trim().split(" ");
        splitSentence.forEach((word, index) => {
            if (word.trim() === '' || !/^[a-zA-Z]+.*$/.test(word)) {
                return;
            }
            if (isWordPresentIn(word.toLowerCase(), nounSet) || (isWordPresentIn(word.toLowerCase(), properNouns))) {
                words.push(word);
                return;
            }
            if (index !== 0 && isCapitalLetterWord(word)) {
                words.push(word);
            }
        });
        return words;
    };

    const isCapitalLetterWord = (word) => {
        if (word === "I") {
            return false;
        }
        const firstLetter = word.charAt(0);
        return firstLetter === firstLetter.toUpperCase();
    };

    const replaceExcludedWordsWithPattern = (sentence, excludedWords, replacement) => {
        let wordsArr = sentence.replace(/[?!]/g, '.').replace(/['"]/g, "").split(" ");
        let replacedArr = wordsArr.map(word => isWordPresentIn(word, excludedWords) ? replacement : word);
        return replacedArr.join(" ");
    };

    const isWordPresentIn = (word, words) => {
        return words.has(word);
    };

    // Debounced function for checking input and updating noun list
    const debouncedCheckInput = debounce(function(text) {
        checkInput(text, nounSet, properNouns);
    }, 250); // 250 milliseconds

    textInput.addEventListener('input', function() {
        const text = this.value;
        debouncedCheckInput(text); // Apply debouncing for noun list update
        updateCharacterCount(); // Update character count in real-time
    });

    copyButton.addEventListener('click', function() {
        navigator.clipboard.writeText(textInput.value).then(() => {
            const originalButtonText = copyButton.textContent; 
            copyButton.textContent = "Copied!";
            setTimeout(() => {
                copyButton.textContent = originalButtonText;
            }, 2000); 
        }).catch(err => {
            console.error('Failed to copy text: ', err);
        });
    });
});



















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

const scrollHeader = () => {
    const navbarElement = selectElement('#header');
    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');
});









