/**
 * Script de capture d'écran pour le Manuel Utilisateur Tenant.
 *
 * Usage :
 *   ACX_BASE_URL=https://acx.example.com \
 *   ACX_DOC_USER=admin \
 *   ACX_DOC_PASSWORD=motdepasse \
 *   npx playwright test --config=playwright.docs.config.ts
 *
 * Les captures sont sauvegardées dans docs/screenshots/tenant/
 */

import { test, Page } from "@playwright/test"
import * as path from "path"
import * as fs from "fs"

// ─── Config ──────────────────────────────────────────────────────────────────
const BASE   = process.env.ACX_BASE_URL     || "http://localhost:3000"
const USER   = process.env.ACX_DOC_USER     || ""
const PASS   = process.env.ACX_DOC_PASSWORD || ""
const LOCALE = process.env.ACX_DOC_LOCALE   || "fr"
const OUT    = path.resolve(__dirname, "../screenshots/tenant")

if (!USER || !PASS) {
  throw new Error(
    "Variables manquantes : ACX_DOC_USER et ACX_DOC_PASSWORD sont obligatoires.\n" +
    "Exemple : ACX_DOC_USER=admin ACX_DOC_PASSWORD=secret npx playwright test ..."
  )
}

// ─── Helpers ─────────────────────────────────────────────────────────────────
async function shot(page: Page, name: string, opts: { fullPage?: boolean; clip?: { x: number; y: number; width: number; height: number } } = {}) {
  fs.mkdirSync(OUT, { recursive: true })
  const file = path.join(OUT, `${name}.png`)
  await page.screenshot({ path: file, fullPage: opts.fullPage ?? false, clip: opts.clip })
  console.log(`  ✓ ${name}.png`)
  return file
}

async function waitReady(page: Page) {
  await page.waitForLoadState("networkidle", { timeout: 15_000 }).catch(() => {})
  await page.waitForTimeout(800)   // laisse les animations se terminer
}

async function goto(page: Page, path: string) {
  await page.goto(`${BASE}/${LOCALE}${path}`, { waitUntil: "domcontentloaded" })
  await waitReady(page)
}

// ─── Auth ────────────────────────────────────────────────────────────────────
async function login(page: Page) {
  await page.goto(`${BASE}/${LOCALE}/login`, { waitUntil: "domcontentloaded" })
  await waitReady(page)
  await shot(page, "00-login")

  // Remplit le formulaire de connexion
  await page.fill('input[name="username"], input[type="text"]', USER)
  await page.fill('input[name="password"], input[type="password"]', PASS)
  await page.click('button[type="submit"]')
  await page.waitForURL(/\/(fr|en)\//, { timeout: 15_000 })
  await waitReady(page)
}

// ─── Sélection du tenant (si multi-tenant) ───────────────────────────────────
async function selectTenant(page: Page) {
  const url = page.url()
  if (url.includes("/select") || url.includes("/workspace")) {
    await shot(page, "01-select-org")
    // Clique sur le premier tenant disponible
    const firstCard = page.locator('[data-testid="tenant-card"], .tenant-card, button').first()
    if (await firstCard.isVisible({ timeout: 3000 })) {
      await firstCard.click()
      await waitReady(page)
    }
  }
}

// ─────────────────────────────────────────────────────────────────────────────
//  CAPTURES
// ─────────────────────────────────────────────────────────────────────────────

test.describe("Manuel Tenant — Captures d'écran", () => {

  test.beforeAll(async ({ browser }) => {
    console.log(`\n📸 Démarrage des captures — ${BASE}`)
    console.log(`   Sortie : ${OUT}\n`)
  })

  test("01 – Connexion & sélection d'organisation", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await shot(page, "02-dashboard")
  })

  test("02 – Tableau de bord", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/")
    await shot(page, "03-dashboard-full", { fullPage: false })
  })

  test("03 – Liste des dossiers", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/cases")
    await shot(page, "04-cases-list")
    // Filtre visible
    await page.locator('input[type="search"], input[placeholder*="Rechercher"], input[placeholder*="Search"]').first().click().catch(() => {})
    await shot(page, "04b-cases-filters")
  })

  test("04 – Création d'un dossier", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/cases/new")
    await shot(page, "05-case-new", { fullPage: true })
  })

  test("05 – Détail d'un dossier", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/cases")
    await waitReady(page)
    // Ouvre le premier dossier disponible
    const firstRow = page.locator("table tbody tr, [data-testid='case-row']").first()
    if (await firstRow.isVisible({ timeout: 5000 })) {
      await firstRow.click()
      await waitReady(page)
      await shot(page, "06-case-detail")
      // Onglets
      for (const [tabLabel, suffix] of [
        ["Actions", "actions"], ["Paiements", "payments"],
        ["Notes", "notes"], ["Documents", "documents"],
      ]) {
        const tab = page.locator(`[role="tab"]:has-text("${tabLabel}"), button:has-text("${tabLabel}")`)
        if (await tab.isVisible({ timeout: 2000 })) {
          await tab.click()
          await waitReady(page)
          await shot(page, `06-case-detail-${suffix}`)
        }
      }
    }
  })

  test("06 – Portefeuilles", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/portfolios")
    await shot(page, "07-portfolios")
  })

  test("07 – Clients", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/customers")
    await shot(page, "08-customers")
  })

  test("08 – Créanciers", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/creditors")
    await shot(page, "09-creditors")
    // Modal création
    const btn = page.locator('button:has-text("Nouveau créancier"), button:has-text("New creditor")')
    if (await btn.isVisible({ timeout: 3000 })) {
      await btn.click()
      await waitReady(page)
      await shot(page, "09b-creditor-form")
      await page.keyboard.press("Escape")
    }
  })

  test("09 – Débiteurs", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/debtors")
    await shot(page, "10-debtors")
  })

  test("10 – Équipe", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/team")
    await shot(page, "11-team")
  })

  test("11 – Boîte mail entrante", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/mail-inbox")
    await shot(page, "12-mail-inbox")
  })

  test("12 – Communications", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/communications")
    await shot(page, "13-communications")
  })

  test("13 – Rapports", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/reports")
    await shot(page, "14-reports")
  })

  test("14 – Paramètres", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/settings")
    await shot(page, "15-settings")
    // Sous-onglet mail entrant
    const mailTab = page.locator('a:has-text("Mail"), button:has-text("Mail")')
    if (await mailTab.isVisible({ timeout: 3000 })) {
      await mailTab.click()
      await waitReady(page)
      await shot(page, "15b-settings-mail")
    }
  })

  test("15 – Support", async ({ page }) => {
    await login(page)
    await selectTenant(page)
    await goto(page, "/support")
    await shot(page, "16-support")
    // Modal nouveau ticket
    const btn = page.locator('button:has-text("Nouveau ticket"), button:has-text("New ticket")')
    if (await btn.isVisible({ timeout: 3000 })) {
      await btn.click()
      await waitReady(page)
      await shot(page, "16b-support-new-ticket")
      await page.keyboard.press("Escape")
    }
  })

  test.afterAll(async () => {
    console.log(`\n✅ Captures terminées — dossier : ${OUT}`)
    console.log("   Lancez maintenant : npm run docs:generate\n")
  })
})
