'use client'

import * as React from 'react'
import { cn } from '../../lib/utils'
import { ChatMessage } from './ChatMessage'
import type { ChatMessageData } from './types'

export interface ChatThreadProps {
  messages: ChatMessageData[]
  /** Rendered when there are no messages. */
  emptyState?: React.ReactNode
  /** Custom message renderer; defaults to <ChatMessage>. */
  renderMessage?: (message: ChatMessageData) => React.ReactNode
  /** Auto-scroll to the newest message on change. Default true. */
  autoScroll?: boolean
  renderContent?: (content: string, message: ChatMessageData) => React.ReactNode
  /** Show an animated "working" indicator at the end (the agent is processing). */
  busy?: boolean
  /** Label shown next to the working indicator. Default "Working…". */
  busyLabel?: string
  className?: string
}

/** Animated three-dot "agent is working" row, aligned like an assistant message. */
function WorkingIndicator({ label = 'Working…' }: { label?: string }) {
  return (
    <div
      className="flex items-center gap-2 px-1 text-sm text-muted-foreground"
      role="status"
      aria-live="polite"
      data-testid="chat-working-indicator"
    >
      <span className="flex gap-1" aria-hidden="true">
        <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-current [animation-delay:-0.3s]" />
        <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-current [animation-delay:-0.15s]" />
        <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-current" />
      </span>
      {label}
    </div>
  )
}

/**
 * Scrollable, auto-scrolling list of chat messages. App-agnostic.
 */
export function ChatThread({
  messages,
  emptyState,
  renderMessage,
  autoScroll = true,
  renderContent,
  busy = false,
  busyLabel,
  className,
}: ChatThreadProps) {
  const anchorRef = React.useRef<HTMLDivElement>(null)

  React.useEffect(() => {
    if (autoScroll) anchorRef.current?.scrollIntoView({ block: 'end' })
  }, [messages, busy, autoScroll])

  // Empty thread + not working → the caller's empty state.
  if (messages.length === 0 && !busy && emptyState) {
    return (
      <div className={cn('flex h-full items-center justify-center p-6 text-center', className)}>
        {emptyState}
      </div>
    )
  }

  return (
    <div className={cn('flex h-full flex-col gap-3 overflow-y-auto p-4', className)} role="log" aria-live="polite">
      {messages.map((m) =>
        renderMessage ? (
          <React.Fragment key={m.id}>{renderMessage(m)}</React.Fragment>
        ) : (
          <ChatMessage key={m.id} message={m} renderContent={renderContent} />
        )
      )}
      {busy && <WorkingIndicator label={busyLabel} />}
      <div ref={anchorRef} data-testid="chat-thread-anchor" />
    </div>
  )
}
