document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('vc-textInput');
    const prepositionCountElement = document.getElementById('vc-prepositionCount');
    const characterCountElement = document.getElementById('vc-characterCount');
    const prepositionListElement = document.getElementById('vc-prepositionList');
    const copyButton = document.getElementById('vc-copyButton');
    
    const oneWordPreposition = [
        
        'aboard', 
        'about', 
        'above', 
        'abreast', 
        'abroad', 
        'absent', 
        'across', 
        'adrift', 
        'aft', 
        'after', 
        'afterward', 
        'against', 
        'ahead', 
        'aloft', 
        'along', 
        'alongside', 
        'amid', 
        'among', 
        'anti', 
        'apart', 
        'apropos', 
        'around', 
        'as', 
        'ashore', 
        'aside', 
        'aslant', 
        'astride', 
        'at', 
        'atop', 
        'away', 
        'back', 
        'backwards', 
        'bar', 
        'barring', 
        'before', 
        'beforehand', 
        'behind', 
        'below', 
        'beneath', 
        'beside', 
        'besides', 
        'between', 
        'beyond', 
        'but', 
        'by', 
        'chez', 
        'circa', 
        'come', 
        'concerning', 
        'contra', 
        'counting', 
        'despite', 
        'down', 
        'downhill', 
        'downstage', 
        'downstairs', 
        'downstream', 
        'downwards', 
        'downwind', 
        'during', 
        'east', 
        'eastwards', 
        'effective', 
        'ere', 
        'except', 
        'excepting', 
        'excluding', 
        'failing', 
        'following', 
        'for', 
        'forth', 
        'forward', 
        'from', 
        'heavenward', 
        'hence', 
        'henceforth', 
        'here', 
        'hereby', 
        'herein', 
        'hereof', 
        'hereto', 
        'herewith', 
        //'home', 
        'homewards', 
        'in', 
        'including', 
        'indoors', 
        'inside', 
        'into', 
        'inwards', 
        'leftwards', 
        'less', 
        'like', 
        'minus', 
        'modulo', 
        'near', 
        'next', 
        'north', 
        'northeast', 
        'northwest', 
        'notwithstanding', 
        //'now', 
        'of', 
        'offshore', 
        'on', 
        'onto', 
        'onwards', 
        'opposite', 
        'out', 
        'outdoors', 
        'outside', 
        'outwards', 
        'over', 
        'overboard', 
        'overhead', 
        'overland', 
        'overseas', 
        'pace', 
        'past', 
        'pending', 
        'per', 
        'plus', 
        'post', 
        'pre', 
        'pro', 
        'qua', 
        're', 
        'regarding', 
        'respecting', 
        'rightwards', 
        'sans', 
        'save', 
        'saving', 
        'seawards', 
        'short', 
        'since', 
        'skywards', 
        'south', 
        'southeast', 
        'southwards', 
        'southwest', 
        'sub', 
        'than', 
        'then', 
        'thence', 
        'thenceforth', 
        'there', 
        'thereby', 
        'therein', 
        'thereof', 
        'thereto', 
        'therewith', 
        'through', 
        'throughout', 
        'till', 
        'times', 
        'to', 
        'together', 
        'touching', 
        'towards', 
        'under', 
        'underfoot', 
        'underground', 
        'underneath', 
        'unlike', 
        'until', 
        'unto', 
        'up', 
        'uphill', 
        'upon', 
        'upstage', 
        'upstairs', 
        'upstream', 
        'upwards', 
        'upwind', 
        'versus', 
        'via', 
        'vice', 
        'vis-à-vis', 
        'wanting', 
        'west', 
        'westwards', 
        'when', 
        'whence', 
        'where', 
        'whereby', 
        'wherein', 
        'whereto', 
        'wherewith', 
        'with', 
        'within', 
        'without' 
   
    ];
    
    
    const multipleWordPreposition = [
        
        'à la', 
        'according to', 
        'across from', 
        'ahead of', 
        'along with', 
        'apart from', 
        'as for', 
        'as from', 
        'as of', 
        'as per', 
        'as regards', 
        'as to', 
        'as well as', 
        'aside from', 
        'away from', 
        'back to', 
        'because of', 
        'but for', 
        'by means of', 
        'close to', 
        'contrary to', 
        'counter to', 
        'depending on', 
        'due to', 
        'except for', 
        'forward of', 
        'further to', 
        'in addition to', 
        'in between', 
        'in case of', 
        'in face of', 
        'in favor of', 
        'in front of', 
        'in lieu of', 
        'in spite of', 
        'in view of', 
        'instead of', 
        'near to', 
        'next to', 
        'on account of', 
        'on behalf of', 
        'on board', 
        'on to', 
        'on top of', 
        'opposite of', 
        'opposite to', 
        'other than', 
        'out from', 
        'out of', 
        'outside of', 
        'owing to', 
        'pertaining to', 
        'prior to', 
        'regardless of', 
        'round about', 
        'save for', 
        'thanks to', 
        'together with', 
        'up against', 
        'up to', 
        'up until', 
        'with reference to', 
        'with regard to' 
        
    ];
    
    function updateCharacterCount() {
        const characters = textInput.value.length;
        characterCountElement.textContent = `Characters: ${characters}`;
    }

    function updatePrepositionCountAndHighlight() {
    let text = textInput.value; // Original user input
    let highlightedText = text; // Copy of the text for highlighting prepositions
    let prepositionsCount = 0; // To keep track of the count of prepositions found and highlighted

    // Handling multiple-word prepositions first
    multipleWordPreposition.forEach(preposition => {
        const regex = new RegExp(`\\b${preposition}\\b`, 'gi');
        highlightedText = highlightedText.replace(regex, (match) => {
            prepositionsCount++; // Increment count for each match found
            return `<span class="highlight">${match}</span>`;
        });
    });

    // Then handle single-word prepositions
    oneWordPreposition.forEach(preposition => {
        // This regular expression looks for the preposition that is not already highlighted
        const regex = new RegExp(`(?<!<span class="highlight">)\\b${preposition}\\b(?!<\/span>)`, 'gi');
        highlightedText = highlightedText.replace(regex, (match) => {
            prepositionsCount++; // Increment count for each match found
            return `<span class="highlight">${match}</span>`;
        });
    });

    // Update the UI with the total count of unique prepositions found
    prepositionCountElement.textContent = `${prepositionsCount}`;
    // Display the highlighted text
    prepositionListElement.innerHTML = highlightedText;
}



    // Debounce function to limit how often a function is executed
    function debounce(func, timeout = 300) {
        let timer;
        return (...args) => {
            clearTimeout(timer);
            timer = setTimeout(() => { func.apply(this, args); }, timeout);
        };
    }

    const debounceUpdatePrepositionCountAndHighlight = debounce(updatePrepositionCountAndHighlight, 300);

    // Event listener for input to update character count and prepositions
    textInput.addEventListener('input', function() {
        updateCharacterCount();
        debounceUpdatePrepositionCountAndHighlight();
    });

    // Event listener for the copy button
    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 {
            // Fallback for browsers without clipboard API support
            textInput.select();
            document.execCommand('copy');
            copyButton.textContent = 'Copied!';
            setTimeout(() => {
                copyButton.textContent = 'Copy Text';
            }, 2000);
        }
    });

    // Initial update for character count and prepositions highlighting
    updateCharacterCount();
    updatePrepositionCountAndHighlight();
});










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









