import { describe, it, expect, vi, afterEach } from 'vitest'
import { render, screen } from '@testing-library/react'

import { BrowserBehaviorView } from '../BrowserBehaviorView'

function mockFetch(getBody: unknown) {
  return vi.fn(async () => ({
    ok: true, status: 200, json: async () => getBody,
  })) as unknown as typeof fetch
}

describe('BrowserBehaviorView', () => {
  afterEach(() => { vi.restoreAllMocks() })

  it('zeigt den Start-Button, wenn noch keine Matrix existiert', async () => {
    vi.stubGlobal('fetch', mockFetch({ browser_matrix: null }))
    render(<BrowserBehaviorView snapshotId="abc" />)
    expect(await screen.findByText('Browser-Test starten')).toBeInTheDocument()
    expect(screen.getByText('Browser-Verhalten testen')).toBeInTheDocument()
  })

  it('rendert die Per-Browser-Tabelle + Befund der schlechtesten Engine', async () => {
    const matrix = {
      browser_matrix: {
        browser_matrix: [
          {
            profile_id: 'chromium-headed-de', label: 'Chromium', engine: 'blink', score: 92,
            summary: {
              cookies_before_consent: 0, cookies_after_reject: 0, reject_respected: true,
              surface: { has_impressum_link: true, has_dse_link: true, banner_text_issues: 0 },
              banner_findings: [],
            },
          },
          {
            profile_id: 'firefox-headed-de', label: 'Firefox', engine: 'gecko', score: 40,
            summary: {
              cookies_before_consent: 3, cookies_after_reject: 2, reject_respected: false,
              surface: { has_impressum_link: false, has_dse_link: true, banner_text_issues: 2 },
              banner_findings: [{ text: 'Ablehnen weniger prominent', severity: 'HIGH', legal_ref: '§ 25 TDDDG' }],
            },
          },
        ],
        aggregate: { profiles_run: 2, worst_score: 40, best_score: 92 },
        scanned_at: '2026-06-12T01:00:00Z',
      },
    }
    vi.stubGlobal('fetch', mockFetch(matrix))
    render(<BrowserBehaviorView snapshotId="abc" />)
    expect(await screen.findByText('Chromium')).toBeInTheDocument()
    // Firefox steht in der Tabellenzeile UND als Kopf des Engine-Details
    // (schlechteste Engine ist vorausgewählt) → mehrfach erwartet.
    expect(screen.getAllByText('Firefox').length).toBeGreaterThanOrEqual(1)
    expect(screen.getByText('Erneut testen')).toBeInTheDocument()
    // Schlechteste Engine (Firefox, Score 40) ist vorausgewählt → Befund sichtbar.
    expect(await screen.findByText(/Ablehnen weniger prominent/)).toBeInTheDocument()
  })
})
