/**
 * Initialisiert die Kommentarfunktion.
 *
 * Kommentare werden per AJAX gespeichert,
 * ohne dass die Seite neu geladen werden muss.
 */
document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById("comment-form");
    const commentsList = document.getElementById("comments-list");
    const commentContent = document.getElementById("comment-content");
    const parentCommentInput = document.getElementById("parent-comment-id");
    const replyInfo = document.getElementById("reply-info");

    if (!form || !commentsList || !commentContent || !parentCommentInput || !replyInfo) {
        return;
    }

    /**
     * Aktiviert einen einzelnen Antworten-Button.
     *
     * @param {HTMLButtonElement} button Antworten-Button
     */
    function registerReplyButton(button) {
        button.addEventListener("click", function () {
            parentCommentInput.value = button.dataset.commentId;
            replyInfo.textContent = "Antwort auf " + button.dataset.author;
            replyInfo.style.display = "block";
            commentContent.focus();
        });
    }

    /**
     * Registriert alle bereits vorhandenen Antwort-Buttons.
     */
    document.querySelectorAll(".reply-button").forEach(function (button) {
        registerReplyButton(button);
    });

    /**
     * Sendet Kommentare per AJAX an den Server.
     */
    form.addEventListener("submit", function (event) {
        event.preventDefault();

        const formData = new FormData(form);
        const parentCommentId = parentCommentInput.value;

        fetch("php/ajax/add-comment.php", {
            method: "POST",
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    alert(data.message);
                    return;
                }

                const emptyMessage = commentsList.querySelector(".no-comments-message");

                if (emptyMessage) {
                    emptyMessage.remove();
                }

                const commentElement = document.createElement("div");
                commentElement.classList.add("comment-item");

                if (parentCommentId) {
                    commentElement.classList.add("comment-reply");

                    commentElement.innerHTML = `
                        <p>
                            <strong>${escapeHtml(data.author)}</strong>
                            <span>${escapeHtml(data.created)}</span>
                        </p>
                        <p>${escapeHtml(data.content).replace(/\n/g, "<br>")}</p>
                    `;

                    const parentReplies = document.querySelector(
                        `.comment-item[data-comment-id="${parentCommentId}"] .comment-replies`
                    );

                    if (parentReplies) {
                        parentReplies.appendChild(commentElement);
                    }

                } else {
                    commentElement.dataset.commentId = data.commentId;

                    commentElement.innerHTML = `
                        <p>
                            <strong>${escapeHtml(data.author)}</strong>
                            <span>${escapeHtml(data.created)}</span>
                        </p>
                        <p>${escapeHtml(data.content).replace(/\n/g, "<br>")}</p>

                        <button type="button"
                                class="reply-button"
                                data-comment-id="${escapeHtml(data.commentId)}"
                                data-author="${escapeHtml(data.author)}">
                            Antworten
                        </button>

                        <div class="comment-replies"></div>
                    `;

                    commentsList.prepend(commentElement);

                    const newReplyButton = commentElement.querySelector(".reply-button");

                    if (newReplyButton) {
                        registerReplyButton(newReplyButton);
                    }
                }

                commentContent.value = "";
                parentCommentInput.value = "";
                replyInfo.textContent = "";
                replyInfo.style.display = "none";
            })
            .catch(() => {
                alert("Kommentar konnte nicht gesendet werden.");
            });
    });

    /**
     * Entfernt HTML-Sonderzeichen aus Nutzereingaben.
     *
     * @param {string} text Zu bereinigender Text
     * @returns {string} Sicherer Text
     */
    function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
    }
});