import { createTextElement, textValue } from '../../shared/dom.js';

export function createMessageElement(message, formatTimestamp) {
    const messageDiv = document.createElement('div');
    let messageClass = 'chat-bubble';

    if (message.type === 'system') {
        messageClass += ' message-system';
    } else if (message.isSelf) {
        messageClass += ' message-self';
    } else {
        messageClass += ' message-other';
    }

    messageDiv.className = messageClass;
    messageDiv.dataset.messageId = message.id;

    const header = document.createElement('div');
    header.className = 'message-header';

    const avatar = document.createElement('img');
    avatar.className = 'message-avatar';
    avatar.src = textValue(message.senderAvatar);
    avatar.alt = textValue(message.senderName, '\u7528\u6237');
    header.appendChild(avatar);

    const headerText = document.createElement('div');
    headerText.appendChild(createTextElement('span', 'message-sender', message.senderName));
    headerText.appendChild(createTextElement('span', 'message-time', formatTimestamp(message.timestamp)));
    header.appendChild(headerText);

    const content = document.createElement('div');
    content.className = 'message-content';
    const rawContent = textValue(message.content);

    if (message.type === 'file' && rawContent.startsWith('data:image/')) {
        const imageContainer = document.createElement('div');
        imageContainer.className = 'message-image-container';

        const image = document.createElement('img');
        image.src = rawContent;
        image.className = 'message-image';
        image.alt = textValue(message.fileName, '\u56fe\u7247');
        imageContainer.appendChild(image);

        if (message.fileName) {
            imageContainer.appendChild(createTextElement('div', 'message-image-name', message.fileName));
        }

        content.appendChild(imageContainer);
    } else {
        content.appendChild(createTextElement('div', 'message-text', rawContent));
    }

    messageDiv.appendChild(header);
    messageDiv.appendChild(content);

    return messageDiv;
}

export function renderChatMessagesInto(container, messages, formatTimestamp) {
    if (!container) return;

    container.innerHTML = '';

    const startTimeElement = document.createElement('div');
    startTimeElement.className = 'text-center text-xs text-gray-500 my-4';
    const startTime = messages[0]?.timestamp || new Date().toISOString();
    startTimeElement.textContent = `\u901a\u8bdd\u5f00\u59cb ${formatTimestamp(startTime)}`;
    container.appendChild(startTimeElement);

    messages.forEach(message => {
        container.appendChild(createMessageElement(message, formatTimestamp));
    });

    container.scrollTop = container.scrollHeight;
}
