import type { ChatMessage } from '../../../api';
import { markdownToPlainText } from '../utils/copy';

function summarize(content: string) {
  const plain = markdownToPlainText(content);
  const firstLine = plain
    .split('\n')
    .map((s) => s.trim())
    .filter(Boolean)[0];
  const text = (firstLine || plain.trim()).replace(/\s+/g, ' ');
  if (text.length <= 44) return text;
  return text.slice(0, 44) + '…';
}

export default function ChatOutline(props: { messages: ChatMessage[]; onJump: (id: string) => void; activeId?: string | null }) {
  const { messages, onJump, activeId } = props;
  const items = messages.filter((m) => m.role === 'assistant');

  if (items.length === 0) return null;

  return (
    <aside className="chat-outline">
      <div className="chat-outline-title">聊天段落</div>
      <div className="chat-outline-list">
        {items.map((m, idx) => (
          <button
            key={m.id}
            type="button"
            className={`chat-outline-item${activeId === m.id ? ' active' : ''}`}
            onClick={() => onJump(m.id)}
            title={summarize(m.content)}
          >
            <span className="chat-outline-index">{idx + 1}</span>
            <span className="chat-outline-text">{summarize(m.content)}</span>
          </button>
        ))}
      </div>
    </aside>
  );
}

