(function () {
    var csrf = window.ZALOROX_CSRF_TOKEN || '';
    var currentUserId = Number(window.ZALOROX_USER_ID || 0);

    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) {
        data = data || {};
        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 formatTime(value) {
        if (!value) return '';
        var date = new Date(String(value).replace(' ', 'T'));
        return isNaN(date.getTime()) ? '' : date.toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' });
    }

    function renderConversation(item) {
        var title = item.other_display_name || item.other_username || 'Konusma';
        var body = item.last_is_deleted > 0 ? 'Bu mesaj silindi.' : (item.last_body || 'Henuz mesaj yok');
        var unread = Number(item.unread_count || 0);
        return '<button type="button" class="conversation-item" data-conversation-id="' + escapeHtml(item.id) + '" data-title="' + escapeHtml(title) + '">' +
            '<span class="avatar">' + (item.other_avatar ? '<img src="' + escapeHtml(item.other_avatar) + '" alt="">' : escapeHtml(title.charAt(0).toUpperCase())) + '</span>' +
            '<span><strong>' + escapeHtml(title) + '</strong><small>' + escapeHtml(body) + '</small></span>' +
            (unread > 0 ? '<em>' + unread + '</em>' : '') +
        '</button>';
    }

    function renderMessage(message) {
        var mine = Number(message.sender_id) === currentUserId;
        var status = message.status === 'pending_review' ? '<span class="message-status">Incelemede</span>' : '';
        var media = '';
        if (message.gif_url) media += '<img class="message-media" src="' + escapeHtml(message.gif_url) + '" alt="GIF">';
        if (message.attachment_path) media += '<img class="message-media" src="' + escapeHtml(message.attachment_path) + '" alt="">';
        if (message.link_url) media += '<a class="message-link" href="' + escapeHtml(message.link_url) + '" target="_blank" rel="noopener nofollow">' + escapeHtml(message.link_url) + '</a>';

        return '<article class="chat-message' + (mine ? ' mine' : '') + (message.is_deleted ? ' is-deleted' : '') + '" data-message-id="' + escapeHtml(message.id) + '">' +
            '<div class="message-bubble">' +
            '<p>' + escapeHtml(message.body || '').replace(/\n/g, '<br>') + '</p>' +
            media +
            '<footer><time>' + escapeHtml(formatTime(message.created_at)) + '</time>' + status + (mine && !message.is_deleted ? '<button type="button" data-message-delete>Sil</button>' : '') + '</footer>' +
            '</div>' +
        '</article>';
    }

    document.querySelectorAll('[data-chat-app]').forEach(function (app) {
        csrf = app.dataset.csrf || csrf;
        var list = app.querySelector('[data-conversation-list]');
        var messages = app.querySelector('[data-chat-messages]');
        var form = app.querySelector('[data-chat-form]');
        var conversationInput = app.querySelector('[data-chat-conversation]');
        var attachmentInput = app.querySelector('[data-chat-attachment]');
        var gifInput = app.querySelector('[data-chat-gif]');
        var bodyInput = form ? form.querySelector('input[name="body"]') : null;
        var title = app.querySelector('[data-chat-title]');
        var subtitle = app.querySelector('[data-chat-subtitle]');
        var params = new URLSearchParams(window.location.search);
        var targetUserId = params.get('user_id') || params.get('user') || '';

        if (targetUserId && subtitle) {
            subtitle.textContent = 'Yeni sohbet hazir. Ilk mesajini yaz.';
        }

        function loadConversations() {
            if (!list) return;
            fetch('/api/messages/conversations', { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(function (response) { return response.json(); })
                .then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Konusmalar yuklenemedi.');
                    list.innerHTML = json.conversations.length
                        ? json.conversations.map(renderConversation).join('')
                        : '<div class="chat-empty">Henuz konusma yok.</div>';

                    if (!conversationInput.value && json.conversations.length && !targetUserId) {
                        openThread(json.conversations[0].id, json.conversations[0].other_display_name || 'Konusma');
                    }
                })
                .catch(function (error) { toast(error.message || 'Konusmalar yuklenemedi.', 'error'); });
        }

        function openThread(conversationId, conversationTitle) {
            conversationInput.value = conversationId;
            targetUserId = '';
            if (title) title.textContent = conversationTitle || 'Konusma';
            if (subtitle) subtitle.textContent = 'Okundu bilgisi ve yaziyor gostergesi altyapisi hazir.';
            messages.innerHTML = '<div class="chat-empty">Mesajlar yukleniyor...</div>';

            fetch('/api/messages/thread/' + encodeURIComponent(conversationId), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(function (response) { return response.json(); })
                .then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Mesajlar yuklenemedi.');
                    messages.innerHTML = json.messages.length
                        ? json.messages.map(renderMessage).join('')
                        : '<div class="chat-empty">Bu konusmada henuz mesaj yok.</div>';
                    messages.scrollTop = messages.scrollHeight;
                    post('/api/messages/read', { conversation_id: conversationId }).catch(function () {});
                })
                .catch(function (error) { toast(error.message || 'Mesajlar yuklenemedi.', 'error'); });
        }

        if (list) {
            list.addEventListener('click', function (event) {
                var item = event.target.closest('[data-conversation-id]');
                if (!item) return;
                list.querySelectorAll('.conversation-item').forEach(function (button) { button.classList.remove('is-active'); });
                item.classList.add('is-active');
                openThread(item.dataset.conversationId, item.dataset.title);
            });
        }

        if (form) {
            form.addEventListener('submit', function (event) {
                event.preventDefault();
                var body = bodyInput ? bodyInput.value.trim() : '';
                var payload = {
                    conversation_id: conversationInput.value || '',
                    user_id: targetUserId,
                    body: body,
                    attachment_path: attachmentInput.value || '',
                    gif_url: gifInput.value || '',
                    message_type: gifInput.value ? 'gif' : (attachmentInput.value ? 'image' : 'text')
                };

                if (!payload.body && !payload.attachment_path && !payload.gif_url) {
                    toast('Bos mesaj gonderilemez.', 'warning');
                    return;
                }

                post('/api/messages/send', payload).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Mesaj gonderilemedi.');
                    conversationInput.value = json.conversation_id || conversationInput.value;
                    targetUserId = '';
                    if (messages.querySelector('.chat-empty')) messages.innerHTML = '';
                    messages.insertAdjacentHTML('beforeend', renderMessage(json.message_item));
                    messages.scrollTop = messages.scrollHeight;
                    form.reset();
                    if (attachmentInput) attachmentInput.value = '';
                    if (gifInput) gifInput.value = '';
                    loadConversations();
                    toast(json.message || 'Mesaj gonderildi.', json.status === 'pending_review' ? 'warning' : 'success');
                }).catch(function (error) {
                    toast(error.message || 'Mesaj gonderilemedi.', 'error');
                });
            });
        }

        app.addEventListener('click', function (event) {
            var deleteButton = event.target.closest('[data-message-delete]');
            if (!deleteButton) return;
            var message = deleteButton.closest('[data-message-id]');
            if (!message) return;

            var run = function () {
                post('/api/messages/delete', { message_id: message.dataset.messageId }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Mesaj silinemedi.');
                    message.classList.add('is-deleted');
                    var p = message.querySelector('p');
                    if (p) p.textContent = 'Bu mesaj silindi.';
                    deleteButton.remove();
                    toast('Mesaj silindi.', 'success');
                }).catch(function (error) { toast(error.message || 'Mesaj silinemedi.', 'error'); });
            };

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

        app.querySelectorAll('[data-emoji-picker] button').forEach(function (button) {
            button.addEventListener('click', function () {
                if (!bodyInput) return;
                bodyInput.value += button.textContent;
                bodyInput.focus();
            });
        });

        var emojiToggle = app.querySelector('[data-emoji-toggle]');
        var emojiPicker = app.querySelector('[data-emoji-picker]');
        if (emojiToggle && emojiPicker) {
            emojiToggle.addEventListener('click', function () { emojiPicker.hidden = !emojiPicker.hidden; });
        }

        var gifToggle = app.querySelector('[data-gif-toggle]');
        var gifPicker = app.querySelector('[data-gif-picker]');
        if (gifToggle && gifPicker) {
            gifToggle.addEventListener('click', function () {
                gifPicker.hidden = !gifPicker.hidden;
                if (gifPicker.dataset.loaded) return;
                fetch('/api/messages/gifs')
                    .then(function (response) { return response.json(); })
                    .then(function (json) {
                        gifPicker.dataset.loaded = '1';
                        gifPicker.innerHTML = (json.gifs || []).map(function (gif) {
                            return '<button type="button" data-gif-url="' + escapeHtml(gif.url) + '"><img src="' + escapeHtml(gif.url) + '" alt=""><span>' + escapeHtml(gif.title) + '</span></button>';
                        }).join('');
                    });
            });
            gifPicker.addEventListener('click', function (event) {
                var button = event.target.closest('[data-gif-url]');
                if (!button) return;
                gifInput.value = button.dataset.gifUrl || '';
                gifPicker.hidden = true;
                toast('GIF mesaja eklendi.', 'success');
            });
        }

        var upload = app.querySelector('[data-chat-upload]');
        if (upload) {
            upload.addEventListener('change', function () {
                if (!upload.files || !upload.files[0]) return;
                var data = new FormData();
                data.append('_csrf', csrf);
                data.append('file', upload.files[0]);
                fetch('/api/messages/upload', {
                    method: 'POST',
                    headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
                    body: data
                }).then(function (response) {
                    return response.json().then(function (json) {
                        json.httpStatus = response.status;
                        return json;
                    });
                }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Gorsel yuklenemedi.');
                    attachmentInput.value = json.path || '';
                    toast('Gorsel mesaja eklendi.', 'success');
                }).catch(function (error) {
                    toast(error.message || 'Gorsel yuklenemedi.', 'error');
                });
            });
        }

        loadConversations();
        window.setInterval(function () {
            if (conversationInput && conversationInput.value) {
                // TODO: WebSocket/SSE yerine MVP polling; daha sonra typing indicator ile genisletilecek.
                openThread(conversationInput.value, title ? title.textContent : 'Konusma');
            }
        }, 30000);
    });
})();
