import { html } from '../lib/preact.js';
import { renderContent, renderToolCalls, renderThinking } from '../lib/markdown.js';

/**
 * Single message bubble used by both the card chat view and modal view.
 * All message rendering logic lives here — card and modal only differ in
 * container layout, not in how individual messages are rendered.
 *
 * @param {object}  msg       - Message object: { role, content, thinking, tool_calls, timestamp }
 * @param {string}  userBg    - Tailwind classes for user message background
 * @param {boolean} compact   - true = card view (smaller), false = modal view (larger)
 * @param {function} formatTime - Optional timestamp formatter (modal only)
 */
export function MessageBubble({ msg, userBg, compact = false, formatTime }) {
  const isUser = msg.role === 'user';
  const pad = compact ? 'px-3 py-2.5' : 'px-4 py-3';
  const maxW = compact ? 'max-w-[92%]' : 'max-w-[86%]';

  return html`
    <div class="flex ${isUser ? 'justify-end' : 'justify-start'} ${compact ? '' : 'animate-fade-in-up'}">
      <div
        class="${maxW} rounded-2xl ${pad} ${
          isUser
            ? `${userBg} rounded-br-md shadow-[0_3px_8px_rgba(16,24,36,0.22)]`
            : 'border border-selection/75 bg-surface2/75 text-fg rounded-bl-md'
        }"
      >
        <div class="mb-1 font-mono text-micro uppercase tracking-[0.14em] text-dim">
          ${isUser ? 'Operator' : 'Agent'}
        </div>
        ${msg.thinking && renderThinking(msg.thinking)}
        <div class="whitespace-pre-wrap break-words text-ui font-chat">
          ${renderContent(msg.content)}
        </div>
        ${renderToolCalls(msg.tool_calls)}
        ${formatTime && msg.timestamp && html`
          <div class="mt-2 font-mono text-label text-dim">
            ${formatTime(msg.timestamp)}
          </div>
        `}
      </div>
    </div>
  `;
}

/**
 * Filter messages for display — removes empty assistant messages
 * (no content, thinking, or tool_calls) that would render as empty bubbles.
 */
export function filterDisplayMessages(messages) {
  return messages.filter(msg =>
    msg.content || msg.thinking || msg.tool_calls?.length || msg.role === 'user'
  );
}
