"use client";

import * as React from "react";
import { ChevronDown, Brain } from "lucide-react";
import { cn } from "@/lib/utils";

interface Props {
  thinking: string;
  durationSeconds?: number;
  defaultOpen?: boolean;
  streaming?: boolean;
}

export function ThinkingBlock({ thinking, durationSeconds, defaultOpen, streaming }: Props) {
  const [open, setOpen] = React.useState(defaultOpen ?? streaming ?? false);

  React.useEffect(() => {
    if (streaming) setOpen(true);
  }, [streaming]);

  if (!thinking && !streaming) return null;

  return (
    <div className="mb-3 rounded-xl border border-border bg-muted/40">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-xs font-medium text-muted-foreground hover:text-foreground"
      >
        <span className="flex items-center gap-1.5">
          <Brain className="h-3.5 w-3.5" />
          {streaming
            ? "Thinking…"
            : durationSeconds && durationSeconds > 0
            ? `Thought for ${durationSeconds}s`
            : "Thinking"}
        </span>
        <ChevronDown
          className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-180")}
        />
      </button>
      {open && (
        <div className="border-t border-border px-3 py-2 text-xs italic leading-relaxed text-muted-foreground whitespace-pre-wrap">
          {thinking || (streaming ? "…" : "")}
        </div>
      )}
    </div>
  );
}
