import { useState } from 'react'
import { useChat } from '../context/ChatContext'
import MessageList from './MessageList'
import ChatInput from './ChatInput'
import { AlertCircle, X } from 'lucide-react'

export default function ChatView() {
  const { envelope, isLive, isLoading, sendMessage, error, clearError } = useChat()
  const [input, setInput] = useState('')

  const handleSend = () => {
    if (!input.trim() || isLoading) return
    sendMessage(input.trim())
    setInput('')
  }

  return (
    <div className="flex-1 flex flex-col min-w-0">
      {/* 错误提示条 */}
      {error && (
        <div className="flex items-center gap-2 mx-3 mt-2 px-3 py-2 rounded-lg bg-red-50 border border-red-200 text-red-700 text-xs">
          <AlertCircle size={14} className="shrink-0" />
          <span className="flex-1">{error}</span>
          <button
            onClick={clearError}
            className="shrink-0 p-0.5 rounded hover:bg-red-100 transition-colors"
          >
            <X size={14} />
          </button>
        </div>
      )}

      <MessageList messages={envelope.messages} />

      <ChatInput
        value={input}
        onChange={setInput}
        disabled={!isLive}
        loading={isLoading}
        onSend={handleSend}
      />
    </div>
  )
}
