/**
 * Document Generator E2E Test
 *
 * Prueft: Template-Library, Empfehlungen, Kategorie-Filter, Template-Auswahl
 */

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

const BASE = process.env.PLAYWRIGHT_BASE_URL || 'https://macmini:3007'

test.describe('Document Generator', () => {
  test('Template Library loads with templates', async ({ page }) => {
    await page.goto(`${BASE}/sdk/document-generator`)
    await page.waitForLoadState('networkidle')

    // Wait for templates to load
    await page.waitForTimeout(2000)

    // Check that template count is shown
    const body = await page.textContent('body')
    expect(body).toContain('Vorlagen gesamt')

    await page.screenshot({ path: 'e2e/test-results/generator-library.png', fullPage: true })
  })

  test('Category filter works', async ({ page }) => {
    await page.goto(`${BASE}/sdk/document-generator`)
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Click on "Datenschutz" category if it exists
    const datenschutzButton = page.locator('button', { hasText: 'Datenschutz' })
    if (await datenschutzButton.isVisible()) {
      await datenschutzButton.click()
      await page.waitForTimeout(500)
      await page.screenshot({ path: 'e2e/test-results/generator-filter-datenschutz.png' })
    }

    // Click "Alle" to reset
    const alleButton = page.locator('button', { hasText: 'Alle' })
    if (await alleButton.isVisible()) {
      await alleButton.click()
      await page.waitForTimeout(500)
    }
  })

  test('Recommendation section visible when scope is set', async ({ page }) => {
    await page.goto(`${BASE}/sdk/document-generator`)
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Check for recommendation section (may or may not be visible depending on scope state)
    const recSection = page.locator('text=Empfohlene Dokumente')
    const isVisible = await recSection.isVisible().catch(() => false)

    if (isVisible) {
      await page.screenshot({ path: 'e2e/test-results/generator-recommendations.png' })

      // Check for Pflicht/Empfohlen sections
      const pflicht = page.locator('text=Pflicht')
      expect(await pflicht.isVisible()).toBeTruthy()
    }
  })

  test('New template categories are present', async ({ page }) => {
    await page.goto(`${BASE}/sdk/document-generator`)
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    const body = await page.textContent('body')

    // Check that new categories exist
    const expectedCategories = ['TOM', 'Whistleblower', 'HR-Datenschutz', 'Drittlandtransfer']
    for (const cat of expectedCategories) {
      const button = page.locator('button', { hasText: cat })
      if (await button.isVisible()) {
        await button.click()
        await page.waitForTimeout(300)
        await page.screenshot({ path: `e2e/test-results/generator-category-${cat.toLowerCase().replace(/[^a-z]/g, '')}.png` })
      }
    }
  })
})
