// conversations_messages.js — Chat channels + messages (DMs only)
// Adapted from chats.html for the Conversations page Messages tab.

// ========== State ==========

var msgChannels = [];
var msgCurrentChannelId = null;

// ========== Data loading ==========

async function loadChatStats() {
    try {
        var res = await fetch('/api/chat-stats');
        var data = await res.json();
        var el = document.getElementById('msg-stats');
        if (el) el.innerHTML = data.total_channels + ' conversations &middot; ' + data.total_messages + ' messages';
    } catch (e) {
        var el = document.getElementById('msg-stats');
        if (el) el.textContent = 'Error loading stats';
    }
}

async function loadChatChannels() {
    try {
        var res = await fetch('/api/chat-channels?limit=500');
        var data = await res.json();
        msgChannels = data.channels || [];
        renderChatChannels();
    } catch (e) {
        var list = document.getElementById('msg-channel-list');
        if (list) list.innerHTML = '<p style="color:var(--color-error)">Error loading channels</p>';
    }
}

// ========== Channel rendering ==========

function renderChatChannels() {
    var search = '';
    var searchEl = document.getElementById('msg-search');
    if (searchEl) search = (searchEl.value || '').toLowerCase();

    var list = document.getElementById('msg-channel-list');
    if (!list) return;

    var filtered = msgChannels;

    if (search) {
        filtered = filtered.filter(function(ch) {
            var name = (ch.peer_full_name || ch.peer_name || ch.name || '').toLowerCase();
            var snippet = (ch.last_message_snippet || '').toLowerCase();
            return name.includes(search) || snippet.includes(search);
        });
    }

    if (!filtered.length) {
        list.innerHTML = '<p style="color:var(--color-text-secondary); padding:10px;">No conversations found</p>';
        return;
    }

    var html = '';
    for (var i = 0; i < filtered.length; i++) {
        var ch = filtered[i];
        var name = ch.peer_full_name || ch.peer_name || ch.name || ch.channel_id;
        var snippet = (ch.last_message_snippet || '').substring(0, 50);
        var lastAt = ch.last_message_at ? msgFormatRelativeTime(ch.last_message_at) : '';
        var activeClass = ch.channel_id === msgCurrentChannelId ? 'active' : '';
        var archived = (ch.archived === '1' || ch.archived === 1) ? ' [archived]' : '';

        var avatarHtml;
        if (ch.peer_id) {
            avatarHtml = '<img class="msg-channel-avatar" src="/api/image/' + ch.peer_id + '" onerror="this.outerHTML=\'<span class=\\\'msg-channel-avatar-fallback\\\'>?</span>\'">';
        } else {
            avatarHtml = '<span class="msg-channel-avatar-fallback">?</span>';
        }

        html += '<div class="msg-channel-item ' + activeClass + '" onclick="selectChatChannel(\'' + ch.channel_id + '\')">';
        html += '<div class="msg-channel-item__top">' + avatarHtml + '<span class="msg-channel-name">' + lib.escapeHtml(name) + '</span>' + archived + '<span class="msg-channel-time">' + lastAt + '</span></div>';
        html += '<div class="msg-channel-snippet">' + lib.escapeHtml(snippet) + '</div>';
        html += '</div>';
    }
    list.innerHTML = html;
}

// ========== Message display ==========

async function selectChatChannel(channelId) {
    msgCurrentChannelId = channelId;
    renderChatChannels();

    var ch = msgChannels.find(function(c) { return c.channel_id === channelId; });
    var headerName = ch ? (ch.peer_full_name || ch.peer_name || ch.name || channelId) : channelId;

    var header = document.getElementById('msg-header');
    if (header) {
        header.innerHTML = '<b>' + lib.escapeHtml(headerName) + '</b>';
    }

    var panel = document.getElementById('msg-messages');
    if (!panel) return;
    panel.innerHTML = '<p style="color:var(--color-text-secondary)">Loading messages...</p>';

    try {
        var res = await fetch('/api/chat-channels/' + channelId + '/messages?limit=500');
        var data = await res.json();
        var messages = data.messages || [];

        if (!messages.length) {
            panel.innerHTML = '<p style="color:var(--color-text-secondary)">No messages found</p>';
            return;
        }

        var html = '';
        var lastDate = '';
        for (var i = 0; i < messages.length; i++) {
            var m = messages[i];
            var msgDate = m.skool_created_at ? new Date(m.skool_created_at).toLocaleDateString() : '';
            if (msgDate && msgDate !== lastDate) {
                html += '<div class="msg-date-divider">' + msgDate + '</div>';
                lastDate = msgDate;
            }

            var time = m.skool_created_at ? new Date(m.skool_created_at).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'}) : '';
            var isDeleted = m.deleted === '1' || m.deleted === 1;
            var isEdited = m.edited_at && m.edited_at !== '';
            var body = isDeleted ? '<span class="msg-deleted">Message deleted</span>' : lib.escapeHtml(m.body || '');

            var attachmentsHtml = '';
            if (!isDeleted && m.attachments_json) {
                try {
                    var attachments = typeof m.attachments_json === 'string' ? JSON.parse(m.attachments_json) : m.attachments_json;
                    for (var a = 0; a < attachments.length; a++) {
                        var att = attachments[a];
                        var ct = (att.metadata && att.metadata.content_type) || '';
                        var url = (att.metadata && (att.metadata.read_url || att.metadata.src_read_url)) || '';
                        if (url && ct.startsWith('image/')) {
                            attachmentsHtml += '<img src="' + lib.escapeHtml(url) + '" style="max-width:300px; max-height:250px; border-radius:6px; margin-top:4px; display:block;" onerror="this.style.display=\'none\'">';
                        } else if (url) {
                            var fname = (att.metadata && att.metadata.file_name) || 'Attachment';
                            attachmentsHtml += '<a href="' + lib.escapeHtml(url) + '" target="_blank" style="color:var(--brand-primary); font-size:12px; display:block; margin-top:4px;">' + lib.escapeHtml(fname) + '</a>';
                        }
                    }
                } catch (e) {}
            }

            html += '<div class="msg-bubble">';
            html += '<div class="msg-sender">' + lib.escapeHtml(m.sender_name || m.sender_id) + '<span class="msg-time">' + time + '</span>' + (isEdited ? '<span class="msg-edited">(edited)</span>' : '') + '</div>';
            html += '<div class="msg-body">' + body + attachmentsHtml + '</div>';
            html += '</div>';
        }
        panel.innerHTML = html;
        panel.scrollTop = panel.scrollHeight;
    } catch (e) {
        panel.innerHTML = '<p style="color:var(--color-error)">Error: ' + e.message + '</p>';
    }
}

// ========== Helpers ==========

function msgFormatRelativeTime(isoStr) {
    try {
        var d = new Date(isoStr);
        var now = new Date();
        var diff = (now - d) / 1000;
        if (diff < 60) return 'now';
        if (diff < 3600) return Math.floor(diff / 60) + 'm';
        if (diff < 86400) return Math.floor(diff / 3600) + 'h';
        if (diff < 604800) return Math.floor(diff / 86400) + 'd';
        return d.toLocaleDateString();
    } catch (e) { return ''; }
}
