const csrfToken = () => document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

const setLikeButtonState = (form, liked) => {
    const button = form.querySelector('[data-community-like-button]');
    const methodInput = form.querySelector('input[name="_method"]');

    form.action = liked ? form.dataset.unlikeUrl : form.dataset.likeUrl;

    if (liked) {
        if (! methodInput) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = '_method';
            input.value = 'DELETE';
            form.appendChild(input);
        } else {
            methodInput.value = 'DELETE';
        }
    } else if (methodInput) {
        methodInput.remove();
    }

    if (! button) {
        return;
    }

    button.textContent = liked ? 'Unlike' : 'Like';
    button.className = liked
        ? 'rounded-lg bg-blue-100 px-4 py-2 text-sm font-black text-blue-700 transition dark:bg-blue-950 dark:text-blue-200'
        : 'rounded-lg bg-blue-600 px-4 py-2 text-sm font-black text-white transition hover:bg-blue-700';
};

document.addEventListener('submit', async (event) => {
    const likeForm = event.target.closest('[data-community-like-form]');

    if (likeForm && window.fetch) {
        event.preventDefault();

        const button = likeForm.querySelector('[data-community-like-button]');
        const originalText = button?.textContent;

        if (button) {
            button.disabled = true;
            button.textContent = 'Saving...';
        }

        try {
            const response = await fetch(likeForm.action, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': csrfToken(),
                },
                body: new FormData(likeForm),
            });

            const data = await response.json();

            if (! response.ok || ! data.success) {
                throw new Error(data.message || 'Unable to update like.');
            }

            const post = likeForm.closest('[data-community-post]');
            const count = post?.querySelector('[data-community-like-count]');

            if (count) {
                count.textContent = data.likes_count;
            }

            setLikeButtonState(likeForm, data.liked);
        } catch (error) {
            alert(error.message || 'Unable to update like right now.');
            if (button && originalText) {
                button.textContent = originalText;
            }
        } finally {
            if (button) {
                button.disabled = false;
            }
        }

        return;
    }

    const commentForm = event.target.closest('[data-community-comment-form]');

    if (commentForm && window.fetch) {
        event.preventDefault();

        const button = commentForm.querySelector('[data-community-comment-button]');
        const errorBox = commentForm.querySelector('[data-community-comment-error]');
        const originalText = button?.textContent;

        if (errorBox) {
            errorBox.classList.add('hidden');
            errorBox.textContent = '';
        }

        if (button) {
            button.disabled = true;
            button.textContent = 'Posting...';
        }

        try {
            const response = await fetch(commentForm.action, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': csrfToken(),
                },
                body: new FormData(commentForm),
            });

            const data = await response.json();

            if (! response.ok || ! data.success) {
                throw new Error(data.message || 'Unable to post comment.');
            }

            const target = document.querySelector('[data-community-comments-target]');
            const post = document.querySelector('[data-community-post]');
            const count = post?.querySelector('[data-community-comment-count]');

            if (target) {
                target.insertAdjacentHTML('afterbegin', data.comment_html);
            }

            if (count) {
                count.textContent = data.comments_count;
            }

            commentForm.reset();
        } catch (error) {
            if (errorBox) {
                errorBox.textContent = error.message || 'Unable to post comment right now.';
                errorBox.classList.remove('hidden');
            } else {
                alert(error.message || 'Unable to post comment right now.');
            }
        } finally {
            if (button) {
                button.disabled = false;
                button.textContent = originalText || 'Comment';
            }
        }
    }
});
