'use client'

// Export types
export * from './types'

// Export individual cards
export { IdleCard } from './idle-card'
export { LoadingCard } from './loading-card'
export { NetworkErrorCard } from './network-error-card'
export { ResponseBodyCard } from './response-body-card'

import { IdleCard } from './idle-card'
import { LoadingCard } from './loading-card'
import { NetworkErrorCard } from './network-error-card'
import { ResponseBodyCard } from './response-body-card'
import type { PlaygroundResponseState } from '@/lib/api-docs/playground/types'
import type { DebugContext } from '../response-viewer'

interface ResponseCardRendererProps {
  responseState: PlaygroundResponseState
  onDebugRequest?: (context: DebugContext) => void
  onExplainRequest?: (context: DebugContext) => void
}

/**
 * Renders the appropriate response card based on the response state.
 * This is the main entry point for response visualization.
 */
export function ResponseCardRenderer({ responseState, onDebugRequest, onExplainRequest }: ResponseCardRendererProps) {
  // Idle state
  if (responseState.type === 'idle') {
    return <IdleCard />
  }

  // Loading state (but not streaming)
  if (responseState.type === 'loading') {
    return <LoadingCard />
  }

  // Error state with no response (network error)
  if (responseState.type === 'error' && !responseState.response) {
    return <NetworkErrorCard errorMessage={responseState.error} />
  }

  // Get response for success, streaming, or error with response
  const response = responseState.response
  if (!response) {
    return null
  }

  const isStreaming = responseState.type === 'streaming'
  const isError = response.status >= 400
  
  // Get content type
  const contentType = response.headers['content-type'] || response.headers['Content-Type'] || null

  // Build context for AI
  const buildContext = () => ({
    status: response.status,
    statusText: response.statusText,
    responseBody: typeof response.body === 'string' ? response.body : '[Binary content]',
    errorMessage: response.error,
  })

  // Handle debug request (for errors)
  const handleDebug = onDebugRequest ? () => {
    onDebugRequest(buildContext())
  } : undefined

  // Handle explain request (for success)
  const handleExplain = onExplainRequest ? () => {
    onExplainRequest(buildContext())
  } : undefined

  return (
    <ResponseBodyCard
      meta={{
        status: response.status,
        statusText: response.statusText,
        responseTime: response.responseTime,
        size: response.size,
        isStreaming: isStreaming || response.isStreaming,
      }}
      body={typeof response.body === 'string' ? response.body : '[Binary content]'}
      headers={response.headers}
      contentType={contentType}
      isError={isError}
      errorMessage={response.error}
      onDebug={isError ? handleDebug : undefined}
      onExplain={!isError ? handleExplain : undefined}
    />
  )
}
