// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import React from 'react'
import { render, screen } from '@testing-library/react'

import { OfflineStatus, describeOfflineStatus } from '../../components/OfflineStatus.js'

describe('describeOfflineStatus', () => {
  it('error wins over everything', () => {
    expect(describeOfflineStatus('connected', 'error').tone).toBe('bad')
    expect(describeOfflineStatus('disconnected', 'error').tone).toBe('bad')
  })

  it('reports Synced when offline is unsupported but socket is connected', () => {
    const out = describeOfflineStatus('connected', 'unsupported')
    expect(out.tone).toBe('good')
    expect(out.label).toBe('Synced')
  })

  it('warns when offline is unsupported and socket is disconnected', () => {
    expect(describeOfflineStatus('disconnected', 'unsupported').tone).toBe('warn')
  })

  it('shows Connecting… when offline is unsupported and socket is connecting', () => {
    expect(describeOfflineStatus('connecting', 'unsupported').label).toBe('Connecting…')
  })

  it('reports Restoring local copy… while IndexedDB is loading', () => {
    expect(describeOfflineStatus('connecting', 'loading').label).toMatch(/Restoring/)
    expect(describeOfflineStatus('connecting', 'pending').label).toMatch(/Restoring/)
  })

  it('reports Saved & synced when both ready', () => {
    const out = describeOfflineStatus('connected', 'ready')
    expect(out.tone).toBe('good')
    expect(out.label).toBe('Saved & synced')
  })

  it('reports Saved locally when offline is ready but socket is disconnected', () => {
    const out = describeOfflineStatus('disconnected', 'ready')
    expect(out.tone).toBe('warn')
    expect(out.label).toMatch(/Saved locally/)
  })

  it('reports Saved locally — reconnecting… while reconnecting', () => {
    expect(describeOfflineStatus('connecting', 'ready').label).toMatch(/reconnecting/)
  })
})

describe('<OfflineStatus />', () => {
  it('renders the resolved label + tone', () => {
    render(<OfflineStatus connection="connected" offline="ready" />)
    const chip = screen.getByTestId('offline-status')
    expect(chip.textContent).toContain('Saved & synced')
    expect(chip.dataset.tone).toBe('good')
  })

  it('switches tone when conditions change', () => {
    const { rerender } = render(<OfflineStatus connection="connected" offline="ready" />)
    expect(screen.getByTestId('offline-status').dataset.tone).toBe('good')
    rerender(<OfflineStatus connection="disconnected" offline="ready" />)
    expect(screen.getByTestId('offline-status').dataset.tone).toBe('warn')
    rerender(<OfflineStatus connection="connected" offline="error" />)
    expect(screen.getByTestId('offline-status').dataset.tone).toBe('bad')
  })
})
