import { html } from '../lib/preact.js';
import { getUserMessageBg } from '../utils/status.js';
import { MessageBubble, filterDisplayMessages } from './MessageBubble.js';

function getMessageKey(msg, index) {
  // Server-assigned ID (preferred)
  if (msg.id) return msg.id;
  // Fallback: role + timestamp + index (for legacy/edge cases)
  return `${msg.role}-${msg.timestamp || ''}-${index}`;
}

export function ChatMessages({ messages, status, limit = 20 }) {
  const userBgClass = getUserMessageBg(status);

  if (!messages || messages.length === 0) {
    return html`
      <div class="flex h-full items-center justify-center rounded-xl border border-dashed border-selection/70 bg-bg/30 px-4 text-center text-sm text-dim">
        No messages to show
      </div>
    `;
  }

  const allDisplayMessages = filterDisplayMessages(messages);
  const displayMessages = limit ? allDisplayMessages.slice(-limit) : allDisplayMessages;
  const offset = allDisplayMessages.length - displayMessages.length;

  return html`
    <div class="space-y-2.5">
      ${displayMessages.map((msg, i) => html`
        <${MessageBubble}
          key=${getMessageKey(msg, offset + i)}
          msg=${msg}
          userBg=${userBgClass}
          compact=${true}
        />
      `)}
    </div>
  `;
}
