// @vitest-environment jsdom
import React from 'react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { Session } from './Session.jsx'
import { api, postJson } from './api.js'
import { useRecorder } from './useRecorder.js'
const mocks = vi.hoisted(() => ({ flush: vi.fn(), adopt: vi.fn() }))
vi.mock('./api.js', () => ({ api: vi.fn(), postJson: vi.fn() }))
vi.mock('./useRecorder.js', () => ({ useRecorder: vi.fn() }))
vi.mock('./useDraft.js', () => ({ initialDraft: row => row.draft, useDraft: () => ({ status: 'Saved on this computer', error: '', flush: mocks.flush, adopt: mocks.adopt, getRevision: () => 0 }) }))
const passage = { id: 'en-practice-test', language: 'en', split: 'practice', title: 'A book', category: 'Daily life', text: 'Anna reads a book.', exercise: { question: 'Who reads?', options: ['Anna', 'Sam', 'Leo'] } }
const saved = { id: 'session-1', revision: 0, status: 'active', draft: { step: 0, transcript: '', source: 'manual', compared: false, dismissed: [] } }
const assigned = { ...saved, revision: 1, exercise: passage.exercise, decision: { policy: 'fixed' }, draft: { ...saved.draft, step: 2 } }
beforeEach(() => {
mocks.flush.mockResolvedValue(undefined)
useRecorder.mockReturnValue({ blob: null, url: '', recording: false, pending: false, seconds: 0, error: '', notice: '', start: vi.fn(), stop: vi.fn(), chooseFile: vi.fn() })
api.mockImplementation(path => Promise.resolve(path.endsWith('/exercise') ? assigned : path.endsWith('/finish') ? { ...assigned, status: 'completed' } : { saved: true }))
postJson.mockResolvedValue({ correct: true, answer: 0, explanation: 'Anna reads.' })
})
afterEach(() => { cleanup(); vi.resetAllMocks() })
it('completes a manual session using persisted assignment and completion', async () => {
const onFinish = vi.fn()
render()
fireEvent.click(screen.getByRole('button', { name: 'Continue without transcription' }))
fireEvent.click(screen.getByRole('button', { name: 'Continue without word comparison' }))
await screen.findByText('A quick exercise')
expect(mocks.flush).toHaveBeenCalled()
fireEvent.click(screen.getByLabelText('Anna'))
fireEvent.click(screen.getByRole('button', { name: 'Check answer' }))
await screen.findByText('That’s right.')
fireEvent.click(screen.getByRole('button', { name: 'Finish session' }))
await screen.findByText('Reading complete.')
expect(onFinish).toHaveBeenCalledTimes(1)
expect(postJson).toHaveBeenCalledWith('/sessions/session-1/answer', { choice: 0 }, expect.anything())
})
it('restores a saved exercise answer without asking or scoring again', async () => {
render()
expect(screen.getByText('Let’s check the passage.')).toBeTruthy()
expect(screen.queryByRole('button', { name: 'Check answer' })).toBeNull()
expect(postJson).not.toHaveBeenCalled()
})
it('keeps the finish button available after a failed save and retries once', async () => {
const onFinish = vi.fn()
api.mockRejectedValueOnce(new Error('Database busy')).mockResolvedValueOnce({ ...assigned, status: 'completed' })
render()
fireEvent.click(screen.getByRole('button', { name: 'Finish session' }))
await screen.findByText('Database busy')
expect(onFinish).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Finish session' }))
await screen.findByText('Reading complete.')
expect(onFinish).toHaveBeenCalledTimes(1)
})
it('restores a Greek transcript and permits correction and dismissal', async () => {
postJson.mockResolvedValue({ differences: [{ id: '2', kind: 'skipped', expected: 'ένα', heard: '', reference_index: 2 }], word_difference_rate: .25 })
render()
await screen.findByText('Possibly skipped')
fireEvent.click(screen.getByLabelText('Dismiss suggestion'))
expect(screen.getByText(/0 suggestions kept/)).toBeTruthy()
fireEvent.change(screen.getByLabelText('Your transcript'), { target: { value: 'Η Άννα διαβάζει ένα βιβλίο.' } })
expect(screen.queryByText('Possibly skipped')).toBeNull()
expect(screen.getByLabelText('Your transcript').getAttribute('lang')).toBe('el')
})
it('does not proceed to an exercise when the draft save fails', async () => {
mocks.flush.mockRejectedValue(new Error('Save failed'))
render()
fireEvent.click(screen.getByRole('button', { name: 'Continue without transcription' }))
fireEvent.click(screen.getByRole('button', { name: 'Continue without word comparison' }))
await screen.findByText('Save failed')
expect(screen.queryByText('A quick exercise')).toBeNull()
expect(api).not.toHaveBeenCalled()
})
it('restores saved audio without erasing its transcript', async () => {
api.mockResolvedValue(new Blob(['audio'], { type: 'audio/webm' }))
render()
await waitFor(() => expect(useRecorder().chooseFile).toHaveBeenCalled())
expect(screen.getByLabelText('Your transcript').value).toBe('Anna reads.')
})
it('requires transcript review and resets that confirmation after an edit', async () => {
postJson.mockResolvedValue({ differences: [], notice: 'Possible text differences only.' })
render()
expect(screen.getByRole('button', { name: 'Compare words' }).disabled).toBe(true)
fireEvent.click(screen.getByLabelText(/I checked the transcript/))
fireEvent.click(screen.getByRole('button', { name: 'Compare words' }))
await screen.findByText('No word differences found')
expect(postJson).toHaveBeenCalledWith('/compare', expect.objectContaining({ source: 'speech', transcript_reviewed: true }), expect.anything())
fireEvent.change(screen.getByLabelText('Your transcript'), { target: { value: 'Anna reads a book.' } })
expect(screen.getByLabelText(/I checked the transcript/).checked).toBe(false)
expect(screen.getByRole('button', { name: 'Compare words' }).disabled).toBe(true)
expect(screen.getByRole('button', { name: 'Continue without word comparison' }).disabled).toBe(false)
})