/**
 * Screenshots de validación visual — Etapa 3 Sprint 1.5.
 *
 * Captura 8 vistas que demuestran la identidad InQ aplicada en el web app:
 *  1. e3-workspace.png           — topbar + CTAs naranjas bold
 *  2. e3-switch-on.png           — ActivityPanel switch ON (caja naranja)
 *  3. e3-report-tabs.png         — tab activo naranja en reporte
 *  4. e3-roi-kpi-hero.png        — KPI Hero con gradiente naranja→magenta
 *  5. e3-comparison-table.png    — tabla comparativa con header naranja
 *  6. e3-cumulative-chart.png    — gráfico acumulado con línea naranja
 *  7. e3-donut-chart.png         — donut directo/overhead (naranja/slate)
 *  8. e3-transparency.png        — TransparencySection con ROI > 1000%
 */
import { test } from '@playwright/test'
import { resolve } from 'path'
import { mkdirSync } from 'fs'
import { fileURLToPath } from 'url'

const __dirname = fileURLToPath(new URL('.', import.meta.url))
const BPMN_DIR = resolve(__dirname, '../../public/sample-processes')
const OUT_DIR = resolve(__dirname, '../screenshots/etapa-3')

test.beforeAll(() => { mkdirSync(OUT_DIR, { recursive: true }) })

// ─── Helpers ──────────────────────────────────────────────────────────────────

async function importBpmn(page: import('@playwright/test').Page, filename: string) {
  await page.goto('/')
  await page.locator('#bpmn-file-input').setInputFiles(resolve(BPMN_DIR, filename))
  await page.waitForURL(/\/workspace\//, { timeout: 15_000 })
  await page.waitForSelector('button:has-text("Simular")', { timeout: 10_000 })
  await page.waitForTimeout(800)
}

async function setActivityCosts(
  page: import('@playwright/test').Page,
  elementId: string,
  directCost: number,
  automatedCost: number
) {
  await page.locator(`[data-element-id="${elementId}"]`).first().click()
  await page.waitForTimeout(400)
  const toggle = page.getByRole('switch', { name: /automatizable/i })
  if (await toggle.getAttribute('aria-checked') === 'false') await toggle.click()
  await page.waitForTimeout(200)
  await page.getByLabel(/Costo directo fijo/i).fill(String(directCost))
  await page.getByLabel(/Costo automatizado/i).fill(String(automatedCost))
  await page.getByLabel(/Tiempo automatizado/i).fill('10')
  await page.getByRole('button', { name: /Guardar/i }).click()
  await page.waitForTimeout(400)
}

async function configureGlobal(page: import('@playwright/test').Page, freq: number, inv: number) {
  await page.getByRole('tab', { name: /Global/i }).click()
  await page.waitForTimeout(300)
  await page.getByLabel(/Frecuencia anual/i).fill(String(freq))
  await page.getByLabel(/Inversión en automatización/i).fill(String(inv))
  await page.getByRole('button', { name: /Guardar/i }).click()
  await page.waitForTimeout(400)
}

async function goToRoiTab(page: import('@playwright/test').Page) {
  const roiTab = page.getByRole('tab', { name: /Comparación/i })
  await roiTab.click()
  await page.waitForSelector('[data-testid="roi-kpi-card"]', { timeout: 10_000 })
  await page.waitForTimeout(600)
}

// ─── 1. Workspace — topbar + CTAs ─────────────────────────────────────────────

test('e3-1: workspace — CTAs naranjas bold', async ({ page }) => {
  await importBpmn(page, 'simple-linear.bpmn')
  await page.waitForTimeout(500)
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-workspace.png'), fullPage: false })
})

// ─── 2. Switch ON en ActivityPanel ────────────────────────────────────────────

test('e3-2: switch ON — caja automatización naranja', async ({ page }) => {
  await importBpmn(page, 'simple-linear.bpmn')
  await page.locator('[data-element-id="task1"]').first().click()
  await page.waitForTimeout(400)
  const toggle = page.getByRole('switch', { name: /automatizable/i })
  if (await toggle.getAttribute('aria-checked') === 'false') await toggle.click()
  await page.waitForTimeout(300)
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-switch-on.png'), fullPage: false })
})

// ─── 3-8. Setup realista para los screenshots del reporte ─────────────────────

test('e3-3-to-8: reporte — 6 screenshots del tab ROI', async ({ page }) => {
  await importBpmn(page, 'medium-with-gateways.bpmn')
  await setActivityCosts(page, 'task_recv', 200, 20)
  await setActivityCosts(page, 'task_score', 200, 20)
  await setActivityCosts(page, 'task_analisis', 200, 20)
  await configureGlobal(page, 5000, 80000)

  const simBtn = page.getByRole('button', { name: 'Simular' })
  await simBtn.click()
  await page.waitForURL(/\/report\//, { timeout: 20_000 })
  await page.waitForSelector('button:has-text("Exportar PDF")', { timeout: 15_000 })
  await page.waitForTimeout(800)

  // 3. Tabs
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-report-tabs.png'), fullPage: false })

  await goToRoiTab(page)

  // 4. KPI Hero
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-roi-kpi-hero.png'), fullPage: false })

  // 5. Comparison Table (scroll down)
  await page.evaluate(() => window.scrollBy(0, 420))
  await page.waitForTimeout(300)
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-comparison-table.png'), fullPage: false })

  // 6. Cumulative chart (scroll to charts section)
  await page.evaluate(() => window.scrollBy(0, 500))
  await page.waitForTimeout(400)
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-cumulative-chart.png'), fullPage: false })

  // 7. Donut chart (actual tab)
  await page.getByRole('tab', { name: 'Actual' }).click()
  await page.waitForTimeout(600)
  await page.evaluate(() => window.scrollTo(0, 0))
  await page.waitForTimeout(300)
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-donut-chart.png'), fullPage: false })

  // 8. Transparency section — ROI > 1000% (back to ROI tab, scroll to bottom)
  await goToRoiTab(page)
  await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight))
  await page.waitForTimeout(500)
  await page.screenshot({ path: resolve(OUT_DIR, 'e3-transparency.png'), fullPage: false })
})
