import { describe, it, expect, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import AlertCard from '@/components/alerts/AlertCard.vue'

const openAlert = {
  id: 'alert-1',
  alertType: 'SEPSIS_WARNING',
  severity: 'CRITICAL',
  status: 'OPEN',
  details: 'SIRS criteria met',
  triggeredAt: '2026-06-19T12:00:00Z',
}

const resolvedAlert = {
  ...openAlert,
  id: 'alert-2',
  status: 'RESOLVED',
}

describe('AlertCard', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
  })

  it('showsAlertTypeAndSeverity', () => {
    const wrapper = mount(AlertCard, { props: { alert: openAlert } })
    expect(wrapper.text()).toContain('CRITICAL')
    expect(wrapper.text()).toContain('Sepsis Warning (SIRS — Legacy)')
  })

  it('showsNarrativeSummaryWhenExplanationPresent', () => {
    const wrapper = mount(AlertCard, {
      props: {
        alert: {
          ...openAlert,
          explanation: {
            narrativeSummary: 'NEWS2 8 — respiratory rate (+3), SpO2 (+2).',
          },
        },
      },
    })
    expect(wrapper.text()).toContain('NEWS2 8 — respiratory rate (+3), SpO2 (+2).')
  })

  it('acknowledgeButtonEmitsEvent', async () => {
    const wrapper = mount(AlertCard, { props: { alert: openAlert } })
    const ackButton = wrapper.findAll('button').find(b => b.text() === 'Acknowledge')
    await ackButton.trigger('click')
    expect(wrapper.emitted('acknowledge')).toHaveLength(1)
  })

  it('showsAcknowledgedByWhenPresent', () => {
    const wrapper = mount(AlertCard, {
      props: {
        alert: {
          ...openAlert,
          status: 'ACKNOWLEDGED',
          acknowledgedBy: 'Demo Nurse (NURSE)',
          acknowledgedAt: '2026-06-19T12:30:00Z',
        },
      },
    })
    expect(wrapper.text()).toContain('Acknowledged by Demo Nurse (Nurse)')
  })

  it('resolvedAlertHidesActions', () => {
    const wrapper = mount(AlertCard, { props: { alert: resolvedAlert } })
    const actionButtons = wrapper.findAll('button').filter(b => ['Acknowledge', 'Resolve'].includes(b.text()))
    expect(actionButtons).toHaveLength(0)
    expect(wrapper.text()).toContain('Useful')
  })
})
