import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fetchCollectorDigest } from '../../lib/collector-client'
import { MorningDigestBanner } from './MorningDigestBanner'

vi.mock('../../lib/collector-client', () => ({
  fetchCollectorDigest: vi.fn(),
}))

const mockFetch = vi.mocked(fetchCollectorDigest)

function renderBanner() {
  const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
  return render(
    <QueryClientProvider client={queryClient}>
      <MorningDigestBanner />
    </QueryClientProvider>,
  )
}

describe('MorningDigestBanner', () => {
  beforeEach(() => {
    localStorage.clear()
    mockFetch.mockReset()
  })

  // The collector's buildDigest returns { day, paragraph } only — never sections.
  it('renders the paragraph visibly when the collector omits sections', async () => {
    mockFetch.mockResolvedValue({
      day: '2026-07-28',
      paragraph: 'Overnight: 11 harness runs updated, 4 new CI failures.',
    })

    renderBanner()

    await waitFor(() => {
      expect(screen.getByTestId('morning-digest-banner')).toBeInTheDocument()
    })
    const paragraph = screen.getByText('Overnight: 11 harness runs updated, 4 new CI failures.')
    expect(paragraph).toBeInTheDocument()
    expect(paragraph).not.toHaveClass('sr-only')
  })

  it('renders section blocks when the collector supplies them', async () => {
    mockFetch.mockResolvedValue({
      day: '2026-07-28',
      paragraph: 'Overnight summary.',
      sections: [
        { id: 'runs', label: 'Harness runs', items: [{ title: 'plan-a', detail: 'succeeded' }] },
        { id: 'failures', label: 'CI failures', items: [] },
      ],
    })

    renderBanner()

    await waitFor(() => {
      expect(screen.getByText('Harness runs')).toBeInTheDocument()
    })
    expect(screen.getByText('plan-a')).toBeInTheDocument()
    expect(screen.getByText('CI failures')).toBeInTheDocument()
  })

  it('shows the banner once per local day', async () => {
    mockFetch.mockResolvedValue({ day: '2026-07-28', paragraph: 'Overnight summary.' })

    const first = renderBanner()
    await waitFor(() => {
      expect(screen.getByTestId('morning-digest-banner')).toBeInTheDocument()
    })
    first.unmount()

    renderBanner()
    await waitFor(() => {
      expect(screen.queryByTestId('morning-digest-banner')).not.toBeInTheDocument()
    })
  })
})
