import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ChatPanelProps } from '@/components/app/chat-panel'
import type { FinalVoiceTranscript } from '@/lib/voice/use-trip-voice'

const voice = vi.hoisted(() => ({ onTranscript: null as null | ((transcript: FinalVoiceTranscript) => void), onEvidence: null as null | ((id: string) => void) }))
vi.mock('@/lib/voice/use-trip-voice', () => ({ useTripVoice: (options: typeof voice) => {
  voice.onTranscript = options.onTranscript; voice.onEvidence = options.onEvidence
  return { status: 'listening', connected: true, toggle: vi.fn(), error: null }
} }))
import { ChatPanel } from '@/components/app/chat-panel'

const props: ChatPanelProps = { trip: { id: 'trip', status: 'active' } as ChatPanelProps['trip'], chat: [], permits: [], myRole: 'admin', myUserId: 'user', participants: [], scopedPermit: null, onExitScope: () => {} }
beforeEach(() => { voice.onTranscript = null; voice.onEvidence = null })
afterEach(() => vi.unstubAllGlobals())

describe('Workspace voice message flow', () => {
  it('buffers metadata arriving before speech, and never attaches it to a previous spoken turn', async () => {
    const transcripts: Record<string, unknown>[] = []
    const evidenceRequests: { message_ids: string[] }[] = []
    vi.stubGlobal('fetch', vi.fn(async (url: string, options: RequestInit) => {
      const body = JSON.parse(String(options.body))
      if (url.endsWith('/voice-evidence')) {
        evidenceRequests.push(body)
        return Response.json({ messages: [], unavailable: true })
      }
      transcripts.push(body)
      return Response.json({ message: { id: `00000000-0000-4000-8000-${String(transcripts.length).padStart(12, '0')}`, content: body.content, created_at: String(transcripts.length) } })
    }))
    renderToStaticMarkup(createElement(ChatPanel, props))
    voice.onTranscript!({ role: 'user', content: 'First question', segmentId: 'q1' })
    voice.onTranscript!({ role: 'assistant', content: 'Same answer', segmentId: 'a1' })
    await vi.waitFor(() => expect(transcripts).toHaveLength(2))
    voice.onTranscript!({ role: 'user', content: 'Second question', segmentId: 'q2' })
    voice.onEvidence!('22222222-2222-4222-8222-222222222222')
    expect(evidenceRequests).toEqual([])
    voice.onTranscript!({ role: 'assistant', content: 'Same answer', segmentId: 'a2' })
    await vi.waitFor(() => expect(evidenceRequests).toHaveLength(1))
    expect(transcripts.map(item => item.content)).toEqual(['First question', 'Same answer', 'Second question', 'Same answer'])
    expect(evidenceRequests[0].message_ids).toEqual(['00000000-0000-4000-8000-000000000004'])
  })
  it('keeps saving questions and answers while optional evidence lookup remains unresolved', async () => {
    const requests: Record<string, unknown>[] = []
    let finishEvidence: ((response: Response) => void) | undefined
    const fetch = vi.fn(async (url: string, options: RequestInit) => {
      if (url.endsWith('/voice-evidence')) return new Promise<Response>(resolve => { finishEvidence = resolve })
      const payload = JSON.parse(String(options.body)); requests.push(payload)
      return Response.json({ message: { id: `00000000-0000-4000-8000-${String(requests.length).padStart(12, '0')}`, content: payload.content, created_at: String(requests.length) } })
    })
    vi.stubGlobal('fetch', fetch)
    const html = renderToStaticMarkup(createElement(ChatPanel, props))
    expect(html).not.toContain('Retry saving reply')
    voice.onTranscript!({ role: 'user', content: 'First question', segmentId: 'q1' })
    voice.onTranscript!({ role: 'assistant', content: 'First answer', segmentId: 'a1' })
    await vi.waitFor(() => expect(requests).toHaveLength(2))
    voice.onEvidence!('22222222-2222-4222-8222-222222222222')
    await vi.waitFor(() => expect(finishEvidence).toBeDefined())
    voice.onTranscript!({ role: 'user', content: 'Second question', segmentId: 'q2' })
    voice.onTranscript!({ role: 'assistant', content: 'Second answer', segmentId: 'a2' })
    await vi.waitFor(() => expect(requests).toHaveLength(4))
    expect(requests.map(item => item.content)).toEqual(['First question', 'First answer', 'Second question', 'Second answer'])
    expect(requests[1].answer_to_message_id).toBe('00000000-0000-4000-8000-000000000001')
    expect(requests[3].answer_to_message_id).toBe('00000000-0000-4000-8000-000000000003')
    finishEvidence!(Response.json({ messages: [], unavailable: true }))
  })
})
