import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import SimulationRunPanel from '@/components/simulation/SimulationRunPanel.vue'

const RouterLinkStub = {
  props: ['to'],
  template: '<a :href="typeof to === \'string\' ? to : \'\'"><slot /></a>',
}

const activeRun = {
  runId: 'run-1',
  scenarioId: 'uti-sepsis-elderly-01',
  scenarioName: 'UTI Sepsis Elderly',
  status: 'RUNNING',
  speed: 60,
  encounterId: 'enc-99',
  patientDisplayName: 'Mary Chen',
  startedAt: '2026-08-05T10:00:00Z',
  elapsedRealSeconds: 125,
  lastOffsetMinutes: 200,
  totalOffsetMinutes: 480,
  progressPercent: 41.6,
  observationsSent: 40,
  medicationsSent: 2,
  ordersPlaced: 1,
  failureReason: null,
}

function mountPanel(props) {
  return mount(SimulationRunPanel, {
    props,
    global: { stubs: { RouterLink: RouterLinkStub } },
  })
}

describe('SimulationRunPanel', () => {
  it('showsProgressAndSimClock', () => {
    const wrapper = mountPanel({ activeRuns: [activeRun], recentRuns: [] })
    expect(wrapper.text()).toContain('03:20 of 08:00 elapsed')
    expect(wrapper.text()).toContain('42%')
    expect(wrapper.text()).toContain('60×')
    expect(wrapper.find('[role="progressbar"]').attributes('aria-valuenow')).toBe('42')
  })

  it('linksToPatientEncounter', () => {
    const wrapper = mountPanel({ activeRuns: [activeRun], recentRuns: [] })
    const link = wrapper.find('a[href="/patients/enc-99"]')
    expect(link.exists()).toBe(true)
    expect(link.text()).toContain('Mary Chen')
  })

  it('requiresStopConfirmBeforeEmitting', async () => {
    const wrapper = mountPanel({ activeRuns: [activeRun], recentRuns: [] })

    await wrapper.findAll('button').find(b => b.text() === 'Stop').trigger('click')
    expect(wrapper.emitted('stop')).toBeUndefined()
    expect(wrapper.text()).toContain('Stopping leaves the patient on the ward')

    await wrapper.findAll('button').find(b => b.text() === 'Confirm stop').trigger('click')
    expect(wrapper.emitted('stop')).toEqual([['run-1']])
  })

  it('showsFailureReasonForFailedRecentRun', () => {
    const wrapper = mountPanel({
      activeRuns: [],
      recentRuns: [{
        ...activeRun,
        status: 'FAILED',
        failureReason: 'Loopback authentication failed',
      }],
    })
    expect(wrapper.text()).toContain('Failed')
    expect(wrapper.text()).toContain('Loopback authentication failed')
  })
})
