/*
 * 会话列表模块：负责当前会话/所有用户分区、搜索和状态标签。
 * 作者: @ccfork
 */
import { apiGet } from './api.js';
import { els, state } from './state.js';
import { escapeHtml, formatTime, sessionLabel } from './utils.js';
import { updateCurrentSessionHeader } from './session-header.js';

function matchesKeyword(session, keyword) {
    const hasRemark = !!String(session.remark || '').trim();
    // 搜索池加入备注状态，支持直接搜“已备注/未备注”。
    const remarkState = hasRemark ? '已备注 有备注' : '未备注 无备注';
    const bag = `${session.id} ${session.user_id || ''} ${session.ip || ''} ${session.remark || ''} ${session.intro || ''} ${remarkState}`.toLowerCase();
    return !keyword || bag.includes(keyword);
}

function statusTags(session) {
    const tags = [];
    if (session.chat_is_typing) tags.push('<span class="unread-badge">输入中</span>');
    if (session.read_label) tags.push(`<span class="unread-badge">${escapeHtml(session.read_label)}</span>`);
    return tags.join('');
}

function renderCard(session) {
    const unread = Number(session.unread || 0);
    return `
        <div class="user-card${session.id === state.currentSessionId ? ' active' : ''}" data-session="${escapeHtml(session.id)}">
            <div class="user-avatar">${escapeHtml((sessionLabel(session)[0] || 'U').toUpperCase())}</div>
            <div class="user-main">
                <div class="user-name">${escapeHtml(sessionLabel(session))}</div>
                <div class="user-meta">ID ${escapeHtml(session.user_id || session.id)} · IP ${escapeHtml(session.ip || '-')}</div>
                <div class="user-preview">${escapeHtml(session.last_message || '新会话')}</div>
            </div>
            <div>
                <div class="user-time">${escapeHtml(formatTime(session.last_time))}</div>
                ${unread > 0 ? `<div class="unread-badge">${unread}</div>` : ''}
                ${statusTags(session)}
            </div>
        </div>
    `;
}

function renderGroup(title, sessions) {
    if (!sessions.length) return '';
    return `
        <section class="session-group">
            <div class="profile-section-title">${escapeHtml(title)}</div>
            ${sessions.map(renderCard).join('')}
        </section>
    `;
}

export function renderSessions() {
    const keyword = els.searchInput.value.trim().toLowerCase();
    const sessions = state.allSessions.filter((session) => matchesKeyword(session, keyword));
    if (!sessions.length) {
        els.usersList.innerHTML = '<div class="empty-state">暂无用户，小纸条来了会出现在这里～</div>';
        return;
    }
    const current = sessions.filter((session) => session.has_current_chat);
    const allUsers = sessions.filter((session) => !session.has_current_chat && session.visited_questionnaire);
    els.usersList.innerHTML = [
        renderGroup('当前会话', current),
        renderGroup('所有用户', allUsers)
    ].join('') || '<div class="empty-state">暂无用户～</div>';
}

export async function loadSessions() {
    try {
        const data = await apiGet('get_sessions');
        if (!data.success) return;
        state.allSessions = data.sessions || [];
        if (state.currentSessionId) {
            state.currentSession = state.allSessions.find((s) => s.id === state.currentSessionId) || state.currentSession;
            updateCurrentSessionHeader();
        }
        renderSessions();
    } catch (error) {
        console.error(error);
    }
}

export function bindSessionList(onSelectSession) {
    els.usersList.addEventListener('click', (event) => {
        const card = event.target.closest('.user-card');
        if (card) onSelectSession(card.dataset.session);
    });
    els.searchInput.addEventListener('input', renderSessions);
}
