import { test, expect } from '@playwright/test'

test.describe('Routes (/routes)', () => {
  test('renders KPI cards, route table, and charts', async ({ page }) => {
    await page.goto('/routes')

    // KPI cards
    await expect(page.getByText('Total Throughput')).toBeVisible()
    await expect(page.getByText('System Error Rate')).toBeVisible()
    await expect(page.getByText('Latency Percentiles')).toBeVisible()
    await expect(page.getByText('Active Routes')).toBeVisible()
    await expect(page.getByText('In-Flight Exchanges')).toBeVisible()

    // Route performance table
    await expect(page.getByText('Per-Route Performance')).toBeVisible()
    await expect(page.getByRole('columnheader', { name: 'Route' })).toBeVisible()
    await expect(page.getByRole('columnheader', { name: 'Exchanges' })).toBeVisible()
    await expect(page.getByRole('columnheader', { name: 'Success %' })).toBeVisible()

    const rows = page.locator('table tbody tr')
    expect(await rows.count()).toBeGreaterThan(0)

    // Charts render
    await expect(page.getByText('Throughput (msg/s)').first()).toBeVisible()
    await expect(page.getByText('Latency (ms)')).toBeVisible()
    await expect(page.getByText('Errors by Route')).toBeVisible()
    await expect(page.getByText('Message Volume (msg/min)')).toBeVisible()

    // Auto-refresh indicator
    await expect(page.getByText('Auto-refresh: 30s')).toBeVisible()
  })

  test('clicking a route row navigates to route detail', async ({ page }) => {
    await page.goto('/routes')

    // Click first route row
    const firstRow = page.locator('table tbody tr').first()
    await firstRow.click()

    // Should navigate to route detail
    await expect(page).toHaveURL(/\/routes\/[^/]+\/[^/]+/)

    // Route detail view: processor performance table
    await expect(page.getByText('Processor Performance')).toBeVisible()
    await expect(page.getByRole('columnheader', { name: 'Processor' })).toBeVisible()
    await expect(page.getByRole('columnheader', { name: 'Type' })).toBeVisible()
    await expect(page.getByRole('columnheader', { name: 'Invocations' })).toBeVisible()

    // Route Flow diagram
    await expect(page.getByText('Route Flow')).toBeVisible()
  })

  test('app-scoped routes view filters data', async ({ page }) => {
    await page.goto('/routes/order-service')

    // Breadcrumb shows scope
    await expect(page.getByRole('link', { name: 'Routes' })).toBeVisible()
    await expect(page.getByLabel('Breadcrumb').getByText('order-service')).toBeVisible()

    // Table still renders
    await expect(page.getByText('Per-Route Performance')).toBeVisible()
  })
})
