"use client";

import { Bot } from "lucide-react";
import { useState } from "react";
import { Persona, type PersonaState, type PersonaVariant } from "@/shared/ai-elements/persona";
import { cn } from "@/lib/utils";

type AgentPersonaProps = {
  className?: string;
  fallbackClassName?: string;
  state?: PersonaState;
  statusLabel?: string;
  streaming?: boolean;
  variant?: PersonaVariant;
};

export function AgentPersona({
  className,
  fallbackClassName,
  state,
  statusLabel,
  streaming = false,
  variant = "obsidian"
}: AgentPersonaProps) {
  const [failed, setFailed] = useState(false);
  const personaState = state ?? getAgentPersonaState(statusLabel, streaming);

  if (failed) {
    return (
      <span
        className={cn(
          "grid shrink-0 place-items-center rounded-xl bg-violet-100 text-violet-700",
          className,
          fallbackClassName
        )}
      >
        <Bot size={19} aria-hidden="true" />
      </span>
    );
  }

  return (
    <Persona
      className={cn("shrink-0", className)}
      onLoadError={() => setFailed(true)}
      state={personaState}
      variant={variant}
    />
  );
}

export function getAgentPersonaState(statusLabel = "", streaming = false): PersonaState {
  if (/失败|不可用|错误|降级/.test(statusLabel)) {
    return "asleep";
  }

  if (streaming || /请求|分析|生成|连接中|加载/.test(statusLabel)) {
    return "thinking";
  }

  return "idle";
}
