const likeComment = id => {
    const comment = document.querySelector(`.comments__item[data-comment-id="${id}"]`);
    const like = comment?.querySelector('.comments__action--like');

    if (!like) return;

    const likesNumber = Number(comment.querySelector('.comments__likes').innerText);

    like.innerText = 'Dislike';
    like.setAttribute('liked', '');
    comment.querySelector('.comments__likes').innerText = likesNumber + 1;
};

const unlikeComment = id => {
    const comment = document.querySelector(`.comments__item[data-comment-id="${id}"]`);
    const like = comment?.querySelector('.comments__action--like');

    if (!like) return;

    const likesNumber = Number(comment.querySelector('.comments__likes').innerText);

    like.innerText = 'Like';
    like.removeAttribute('liked');
    comment.querySelector('.comments__likes').innerText = likesNumber - 1;
};

const setupComments = () => {
    const storedLikesComments = localStorage.likedComments || '[]';
    let likedComments = JSON.parse(storedLikesComments);

    likedComments.forEach(id => {
        likeComment(id);
    });

    document.querySelectorAll('.comments__action--like').forEach(like => {
        like.addEventListener('click', function () {
            const liked = this.innerText === 'Like';
            const likedId = this.closest('.comments__item').getAttribute('data-comment-id');

            if (liked) {
                likeComment(likedId);
                likedComments.push(likedId);
            } else {
                unlikeComment(likedId);
                likedComments = likedComments.filter(id => id !== likedId);
            }

            localStorage.likedComments = JSON.stringify(likedComments);
        });
    });
};

const updateDate = () => {
    const dateElement = document.querySelector('#date');

    // The date must be in the user browser format (e.g. 07/23/2025)
    const date = new Date().toLocaleDateString();
    dateElement.innerText = date;
};

document.addEventListener('DOMContentLoaded', () => {
    setupComments();
    updateDate();

    const backToTop = document.querySelector('.btn_footer');
    backToTop.addEventListener('click', e => {
        e.preventDefault();

        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
});
