"use strict";

/** @type {HTMLElement} */
let menuElement = null;

/** @type {HTMLElement} */
let paragraphElement = null;

const copyMenu = function() {
    paragraphElement.textContent += menuElement.textContent;
}

const changeCss = function() {
    const randomColor = Math.floor(Math.random() * (0xffffff + 1));
    const complementaryColor = 0xffffff - randomColor;
    document.styleSheets.item(0).cssRules[2].style.color = `#${randomColor.toString(16)}`;
    document.styleSheets.item(0).cssRules[2].style.backgroundColor = `#${complementaryColor.toString(16)}`;
}

const doSearch = function(event) {
    Array.from(menuElement.children).forEach(element => {
        element.innerHTML = element.innerText;
    });
    const searchTerm = event.target.value;
    if (searchTerm !== "") {
        Array.from(menuElement.children).forEach(element => {
            element.innerHTML = element.innerText.replace(new RegExp(searchTerm, "ig"), '<span class="highlighted">$&</span>');
        });
    }
}


const init = function() {
    menuElement = document.getElementById("menu");
    paragraphElement = document.getElementById("paragraph");

    document.getElementById("btn-copy-menu").addEventListener("click", copyMenu);
    document.getElementById("btn-change-css").addEventListener("click", changeCss);
    document.getElementById("search-bar").addEventListener("input", doSearch);
}

document.addEventListener("DOMContentLoaded", () => init());