import { Avatar } from '@heroui/react'
import { motion } from 'framer-motion'
import AvatarBot from '@/assets/avatarBot.png'
import AIIcon from '@/assets/ai-icon.png'
import { findToolRowBySessionToolId, readToolListFromSessionStorage } from '@/lib/toolRoleRecordTypes'

interface ChatWelcomeProps {
  toolName?: string
  welcomeText?: string
}

export const ChatWelcome: React.FC<ChatWelcomeProps> = ({ toolName: _toolName, welcomeText }) => {
  const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'

  const getWelcomeText = () => {
    if (welcomeText) {
      return welcomeText
    }

    const currentToolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : ''
    const list = readToolListFromSessionStorage()
    const row = findToolRowBySessionToolId(list, currentToolId || '')
    const name = row?.toolName?.trim()

    try {
      const stored = typeof window !== 'undefined' ? sessionStorage.getItem('toolStreamWelcomeText') : null
      if (stored && stored.trim() && currentToolId?.trim()) {
        return stored
      }
    }
    catch {
      // 读取失败时回退
    }

    if (name) {
      return `Hi，我是${name}，请问有什么可以帮您？`
    }

    return 'Hi，我是您的智能助手，请问有什么可以帮您？'
  }

  return (
    <div className="chatWelcomeContainer w-full">
      <div className="h-[20px] sm:h-[32px] w-full"></div>
      <div className="flex items-start">
        <Avatar className="mr-[12px] flex-shrink-0" src={viteOutputObj === 'inner' ? AIIcon : AvatarBot} />
        <motion.div
          className="rounded-[20px] box-border px-[16px] py-[16px] sm:px-[24px] sm:py-[20px]"
          style={{ background: '#F7FAFD' }}
        >
          <div className="content">
            <p
              className="font-medium text-[#333]"
              style={{ fontSize: '16px' }}
            >
              {getWelcomeText()}
            </p>
          </div>
        </motion.div>
      </div>
      <div className="h-[20px] sm:h-[32px] w-full"></div>
    </div>
  )
}
