// Global variables

let userInput;
let charLength;
let wordCount;
let spaceCount;
let letterCount;
let nonSpaceCount;
let pageCount;
let paragraphCount;
let sentenceCount;





function callFunction() {
    userInput = getUserInput();
    charLength = getCharLength();
    wordCount = getWordCount();
    spaceCount = getSpaceCount();
    letterCount = getLetterCount();
    nonSpaceCount = getNonSpaceCount();
    pageCount = getPageCount();
    paragraphCount = getParagraphCount();
    sentenceCount = sentenceCounter(userInput);
    
    document.getElementById("characterOutput").innerHTML =  charLength;
    document.getElementById("wordOutput").innerHTML = wordCount;
    document.getElementById("spaceOutput").innerHTML = spaceCount;
    document.getElementById("letterOutput").innerHTML = letterCount;
    
    document.getElementById("nonSpaceOutput").innerHTML = nonSpaceCount;
    document.getElementById("sentenceOutput").innerHTML = sentenceCount;
    document.getElementById("paragraphOutput").innerHTML = paragraphCount;
    document.getElementById("pageOutput").innerHTML = pageCount;
    
} 



// Get user input from textarea
function getUserInput() {
    
    // Assign user input to variable
    const userInput = document.getElementById("userWord").value;
    return userInput;
}

// Get count of characters in textarea
function getCharLength() {

    return userInput.length;
}

// Get count of words in textarea
function getWordCount(){
    if(!userInput.match(/\S+/g)){
        return 0;
    }
    else {
        return userInput.match(/\S+/g).length;
    }
}

// Get count of whitespace characters
function getSpaceCount() {
    if (!userInput.match(/\s/g)){
        return 0;
    }
    else {
        return userInput.match(/\s/g).length;
    }
}

// Get count of letters
function getLetterCount() {
    if (!userInput.match(/[a-z]/gi)){
        return 0;
    }
    else {
        return userInput.match(/[a-z]/gi).length;
    }
}

// Get count of non-space characters in textarea
function getNonSpaceCount() {
    if (!userInput.match(/\S/g)){
        return 0;
    }
    else {
        return userInput.match(/\S/g).length;
    }
}

// Get count of pages
function getPageCount() {
    
    if (wordCount < 1) {
        return 0;
    }
    
    let result = Math.round((wordCount / 250) * 10) / 10;
    
    return result;
}

// Get count of paragraphs
function getParagraphCount(){
    let count = 0;
    let wsRegex = /^\s+|\s+$/g;
    let result = userInput.replace(wsRegex, "");
    
    // If there are no NewLine characters and no non-whitespace
    // characters then return 0

    if (!result.match(/\n+/g) && !result.match(/\S/gi)){
        return 0;
    }
    
    // If there are no NewLine characters but there is a non-whitespace
    // character then return 1
    
    else if (!result.match(/\n+/g) && result.match(/\S/gi)){
        
        return 1;
    }
    
    // If there is a NewLine character followed by a space and a non-space
    // character or NewLine character followed by a non-space character
    // then return number of NewLine characters + 1
    
    else{
        return result.match(/\n+(\s+\S|\S)/g).length + 1;
    }
}

const sentenceCounter = (string) => {
    let sentenceCount = separateSentences(string).length;
    return sentenceCount + countOfEmdashQuotation(string);
}

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



// Helper methods
const sentenceWordCount = (string) => {
    let wordCount = string.split(' ').length;
    return wordCount;
}

const sentenceCharacterCount = (string) => {
    let characterCount = string.split('').length;
    return characterCount;
}

const createSentenceInfoObject = (string) => {
    const sentenceInfo = {
        sentence: string,
        wordCount: sentenceWordCount(string),
        characterCount: sentenceCharacterCount(string)
    }

    return sentenceInfo;
}

const createSentenceInfoObjectArray = (separatedSentences) => {
    let sentenceInfoObjects = [];

    for (let i = 0; i < separatedSentences.length; i++) {
        sentenceInfoObjects.push(createSentenceInfoObject(separatedSentences[i]));
    }

    return sentenceInfoObjects;
}

const separateSentences = (string) => {
    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.'];

    // These should always have an uppercase name following them and shouldn't be the end of a sentence
    const prefixAbbreviations = titles.map(item => item.toLowerCase())
    // These can come anywhere in the sentence so we should check the word after them for new sentences
    const abbreviatons = [...suffixes, ...addressAbbreviations, ...commonAbbreviations].map(item => item.toLowerCase())
    
    // New code to remove Carriage Returns, quotations and parenthesis
    const stringWithoutCarriageReturnsQuotationsAndParenthesis = string.replaceAll(/\\n/g, ' ').replaceAll(/\n/g, ' ').replaceAll(/\t/g, ' ').replaceAll(/[(){}\[\]''""‘’“”]/g, '');
    const words = stringWithoutCarriageReturnsQuotationsAndParenthesis.split(' ');

    let sentences = [];
    let currentSentence = '';

    for (let i = 0; i < words.length; i++) {
        let lastCharacter = words[i].charAt(words[i].length - 1);

        if (lastCharacter === '.' || lastCharacter === '!' || lastCharacter === '?') {
            if (!abbreviatons.includes(words[i].toLowerCase()) && !prefixAbbreviations.includes(words[i].toLowerCase())) {
                currentSentence += (' ' + words[i]);
                sentences.push(currentSentence.trim());
                currentSentence = '';
            } else if (abbreviatons.includes(words[i].toLowerCase()) && firstLetterUppercase(words[i + 1])) {
                currentSentence += (' ' + words[i]);
                sentences.push(currentSentence.trim());
                currentSentence = '';
            } else {
                currentSentence += (' ' + words[i]);
            } 
        } else {
			//if ellipsis (…) followed by an uppercase letter it to count as a sentence
			if (lastCharacter === '…' && firstLetterUppercase(words[i + 1])) {
				currentSentence += (' ' + words[i]);
                sentences.push(currentSentence.trim());
                currentSentence = '';
			} else { 
				currentSentence += (' ' + words[i]);
			}
        }
    }

    return sentences
}

const firstLetterUppercase = (word) => {
    const firstLetter = word.charAt(0);
    return firstLetter === firstLetter.toUpperCase();
}





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

// Switch theme/add to local storage
const body = document.body;
const themeToggleBtn = selectElement('#theme-toggle-btn');
const currentTheme = localStorage.getItem('currentTheme');

// Check to see if there is a theme preference in local Storage, if so add the ligt theme to the body
if (currentTheme) {
    body.classList.add('light-theme');
}

themeToggleBtn.addEventListener('click', function () {
    // Add light theme on click
    body.classList.toggle('light-theme');

    // If the body has the class of light theme then add it to local Storage, if not remove it
    if (body.classList.contains('light-theme')) {
        localStorage.setItem('currentTheme', 'themeActive');
    } else {
        localStorage.removeItem('currentTheme');
    }
});

// Swiper
const swiper = new Swiper(".swiper", {
    // How many slides to show
    slidesPerView: 1,
    // How much space between slides
    spaceBetween: 20,
    // Make the next and previous buttons work
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
    // Make the pagination indicators work
    pagination: {
        el: '.swiper-pagination'
    },
    //Responsive breakpoints for how many slides to show at that view
    breakpoints: {
        // 700px and up shoes 2 slides
        700: {
          slidesPerView: 2
        },
        // 1200px and up shoes 3 slides
        1200: {
            slidesPerView: 3
        }
    }   
});


// Copy text in textarea with button click
function copy() {
    
    if (getCharLength() > 0){
      let copyText = document.getElementById("userWord");
      copyText.select();
      copyText.setSelectionRange(0, 99999);
      document.execCommand("copy");
      
      let x = document.getElementById("snackbar");
      x.className = "show";
      setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
    }
    
    else{
      let x = document.getElementById("snackbarFail");
      x.className = "show";
      setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
    }
}

// Clear text in textarea with button click
function clearContent() {
    document.getElementById("userWord").value='';
    callFunction();
}






