"use client";

import { memo } from "react";
import type { Turn } from "@/lib/chat-store";
import { MarkdownText } from "./markdown-text";
import { ToolCallCard } from "./tool-call-card";

function TurnViewImpl({ turn }: { turn: Turn }) {
  return (
    <div className="space-y-3">
      <div className="flex justify-end">
        <div className="max-w-[80%] rounded-2xl bg-sky-600 px-4 py-2 text-sm text-white whitespace-pre-wrap">
          {turn.prompt}
        </div>
      </div>

      {turn.events.length > 0 && (
        <div className="space-y-2">
          {turn.events.map((ev, i) =>
            ev.kind === "text" ? (
              <MarkdownText key={i} text={ev.text} />
            ) : (
              <ToolCallCard key={i} ev={ev} />
            ),
          )}
        </div>
      )}

      {turn.status === "running" && (
        <div className="flex items-center gap-2 text-xs text-neutral-500">
          <span className="inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-sky-400" />
          思考中…
        </div>
      )}
      {turn.status === "error" && turn.error && (
        <div className="rounded border border-red-900 bg-red-950/30 px-3 py-2 text-xs text-red-200">
          错误：{turn.error}
        </div>
      )}
      {turn.status === "done" && turn.cost !== undefined && (
        <div className="text-[10px] text-neutral-600">
          本轮花费 ${turn.cost.toFixed(4)}
          {turn.sessionId ? ` · session ${turn.sessionId.slice(0, 8)}` : ""}
        </div>
      )}
    </div>
  );
}

// Memoized: chat-store ref-stable updates skip re-render when this turn's
// reference is unchanged (e.g. while a sibling turn is updating).
export const TurnView = memo(TurnViewImpl);
