(function () {
    function toast(message, type) {
        if (window.ZaloroxToast) {
            window.ZaloroxToast.show(message, type || 'info');
        }
    }

    function escapeHtml(value) {
        return String(value || '').replace(/[&<>"']/g, function (char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[char];
        });
    }

    function post(endpoint, data) {
        var csrf = window.ZALOROX_CSRF_TOKEN || data._csrf || '';
        data._csrf = data._csrf || csrf;

        return fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-TOKEN': csrf,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new URLSearchParams(data)
        }).then(function (response) {
            return response.json().then(function (json) {
                json.httpStatus = response.status;
                return json;
            });
        });
    }

    function renderComment(comment) {
        var display = comment.display_name || comment.username || 'User';
        var initial = display.charAt(0).toUpperCase() || 'U';
        var date = comment.created_at ? new Date(comment.created_at.replace(' ', 'T')) : new Date();
        var dateText = isNaN(date.getTime()) ? '' : date.toLocaleDateString('tr-TR') + ' ' + date.toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' });
        var avatar = comment.avatar
            ? '<img src="' + escapeHtml(comment.avatar) + '" alt="">'
            : escapeHtml(initial);
        var replyClass = comment.parent_id ? ' is-reply' : '';

        return '<article class="comment' + replyClass + '" data-comment-id="' + escapeHtml(comment.id) + '" data-parent-id="' + escapeHtml(comment.parent_id || '') + '">' +
            '<span class="avatar">' + avatar + '</span>' +
            '<div><header><strong>' + escapeHtml(display) + '</strong><time>' + escapeHtml(dateText) + '</time></header>' +
            '<p data-comment-body>' + escapeHtml(comment.content).replace(/\n/g, '<br>') + '</p>' +
            '<div class="comment-actions">' +
            '<button type="button" data-comment-reply>Yanitla</button>' +
            '<button type="button" data-comment-like>Begen <span>' + escapeHtml(comment.like_count || 0) + '</span></button>' +
            '<button type="button" data-comment-edit>Duzenle</button>' +
            '<button type="button" data-comment-delete>Sil</button>' +
            '</div></div></article>';
    }

    function renderList(container, comments) {
        var list = container.querySelector('[data-comment-list]');
        if (!list) return;

        list.innerHTML = comments.length
            ? comments.map(renderComment).join('')
            : '<div class="empty-state small" data-comment-empty><strong>Henuz yorum yok</strong><p>Ilk yorumu giris yapmis bir kullanici birakabilir.</p></div>';
    }

    document.querySelectorAll('[data-comments]').forEach(function (container) {
        var endpoint = container.dataset.listEndpoint;
        if (!endpoint) return;

        fetch(endpoint, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function (response) { return response.json(); })
            .then(function (json) {
                if (json.ok && Array.isArray(json.comments)) {
                    renderList(container, json.comments);
                }
            })
            .catch(function () {});
    });

    document.querySelectorAll('[data-comment-form]').forEach(function (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            var button = form.querySelector('button[type="submit"]');
            var container = form.closest('[data-comments]');
            var list = container ? container.querySelector('[data-comment-list]') : document.querySelector('[data-comment-list]');
            var formData = new FormData(form);
            var csrf = window.ZALOROX_CSRF_TOKEN || formData.get('_csrf') || '';
            var data = {};
            formData.forEach(function (value, key) { data[key] = value; });

            if (button) button.disabled = true;

            post(form.action || '/api/comments/create', data).then(function (json) {
                if (!json.ok) {
                    toast(json.message || 'Yorum kaydedilemedi.', json.status === 'blocked' ? 'error' : 'warning');
                    return;
                }

                if (json.status === 'pending_review') {
                    toast(json.message || 'Yorum incelemeye alindi.', 'warning');
                    form.reset();
                    return;
                }

                if (json.comment && list) {
                    var empty = list.querySelector('[data-comment-empty]');
                    if (empty) empty.remove();
                    list.insertAdjacentHTML(json.comment.parent_id ? 'beforeend' : 'afterbegin', renderComment(json.comment));
                }

                toast(json.message || 'Yorum yayinlandi.', 'success');
                form.reset();
                form.querySelector('[name="parent_id"]').value = '';
                form.querySelector('textarea').placeholder = 'Yorum yaz...';
            }).catch(function () {
                toast('Yorum kaydedilemedi.', 'error');
            }).finally(function () {
                if (button) button.disabled = false;
            });
        });
    });

    document.addEventListener('click', function (event) {
        var emoji = event.target.closest('[data-comment-emoji] button');
        if (emoji) {
            var form = emoji.closest('form');
            var textarea = form ? form.querySelector('textarea') : null;
            if (textarea) {
                textarea.value += emoji.textContent;
                textarea.focus();
            }
            return;
        }

        var reply = event.target.closest('[data-comment-reply]');
        if (reply) {
            var comment = reply.closest('[data-comment-id]');
            var container = reply.closest('[data-comments]');
            var form = container ? container.querySelector('[data-comment-form]') : null;
            if (!comment || !form) return;

            form.querySelector('[name="parent_id"]').value = comment.dataset.commentId || '';
            form.querySelector('textarea').placeholder = 'Yanit yaz...';
            form.querySelector('textarea').focus();
            toast('Yanit modu aktif.', 'info');
            return;
        }

        var like = event.target.closest('[data-comment-like]');
        if (like) {
            var likedComment = like.closest('[data-comment-id]');
            if (!likedComment) return;

            post('/api/comments/like', { comment_id: likedComment.dataset.commentId }).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Begeni kaydedilemedi.');
                var count = like.querySelector('span');
                if (count) count.textContent = json.like_count || 0;
                like.classList.toggle('is-active', json.liked === true);
            }).catch(function (error) { toast(error.message || 'Begeni kaydedilemedi.', 'error'); });
            return;
        }

        var edit = event.target.closest('[data-comment-edit]');
        if (edit) {
            var editable = edit.closest('[data-comment-id]');
            var body = editable ? editable.querySelector('[data-comment-body]') : null;
            if (!editable || !body || editable.querySelector('[data-comment-edit-form]')) return;

            var original = body.textContent || '';
            body.insertAdjacentHTML('afterend',
                '<form class="comment-edit-form" data-comment-edit-form>' +
                '<textarea maxlength="3000">' + escapeHtml(original) + '</textarea>' +
                '<div><button class="pill primary" type="submit">Kaydet</button><button class="pill" type="button" data-comment-edit-cancel>Vazgec</button></div>' +
                '</form>');
            body.hidden = true;
            return;
        }

        var cancel = event.target.closest('[data-comment-edit-cancel]');
        if (cancel) {
            var editForm = cancel.closest('[data-comment-edit-form]');
            var editComment = editForm ? editForm.closest('[data-comment-id]') : null;
            var editBody = editComment ? editComment.querySelector('[data-comment-body]') : null;
            if (editBody) editBody.hidden = false;
            if (editForm) editForm.remove();
            return;
        }

        var del = event.target.closest('[data-comment-delete]');
        if (del) {
            var deletedComment = del.closest('[data-comment-id]');
            if (!deletedComment) return;

            var runDelete = function () {
                post('/api/comments/delete', { comment_id: deletedComment.dataset.commentId }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Yorum silinemedi.');
                    deletedComment.remove();
                    toast('Yorum silindi.', 'success');
                }).catch(function (error) { toast(error.message || 'Yorum silinemedi.', 'error'); });
            };

            if (window.ZaloroxModal) {
                window.ZaloroxModal.confirm('Yorumu silmek istiyor musun?', { confirmLabel: 'Sil', cancelLabel: 'Vazgec', danger: true }).then(function (ok) {
                    if (ok) runDelete();
                });
            } else {
                runDelete();
            }
        }
    });

    document.addEventListener('submit', function (event) {
        var form = event.target.closest('[data-comment-edit-form]');
        if (!form) return;

        event.preventDefault();
        var comment = form.closest('[data-comment-id]');
        var textarea = form.querySelector('textarea');
        var content = textarea ? textarea.value.trim() : '';

        post('/api/comments/update', { comment_id: comment.dataset.commentId, content: content }).then(function (json) {
            if (!json.ok) throw new Error(json.message || 'Yorum guncellenemedi.');
            var body = comment.querySelector('[data-comment-body]');
            if (body) {
                body.innerHTML = escapeHtml(json.comment.content || content).replace(/\n/g, '<br>');
                body.hidden = false;
            }
            form.remove();
            toast(json.message || 'Yorum guncellendi.', json.status === 'pending_review' ? 'warning' : 'success');
        }).catch(function (error) {
            toast(error.message || 'Yorum guncellenemedi.', 'error');
        });
    });
})();
