// spec: e2e/plans/task-activated.plan.md

import { test, expect, type APIRequestContext, type Locator, type Page } from '@playwright/test'

const CHILD_NAME = 'ActivatePenaltyChild'
const PEN_NAME = 'TriggerTestPenalty'
const PEN_HELPER_NAME = 'TriggerPenaltyHelper'
const PEN_POINTS = 20
const INITIAL_POINTS = 50

async function createChild(
  request: APIRequestContext,
  name: string,
  points: number,
): Promise<string> {
  const pre = await request.get('/api/child/list')
  for (const c of (await pre.json()).children ?? []) {
    if (c.name === name) await request.delete(`/api/child/${c.id}`)
  }
  await request.put('/api/child/add', { data: { name, age: 8 } })
  const list = await request.get('/api/child/list')
  const id = (await list.json()).children?.find((c: any) => c.name === name)?.id ?? ''
  if (points > 0) await request.put(`/api/child/${id}/edit`, { data: { points } })
  return id
}

async function createTask(
  request: APIRequestContext,
  name: string,
  type: 'chore' | 'kindness' | 'penalty',
  points: number,
): Promise<string> {
  const pre = await request.get('/api/task/list')
  for (const t of (await pre.json()).tasks ?? []) {
    if (t.name === name) await request.delete(`/api/task/${t.id}`)
  }
  await request.put('/api/task/add', { data: { name, points, type } })
  const list = await request.get('/api/task/list')
  return (await list.json()).tasks?.find((t: any) => t.name === name)?.id ?? ''
}

async function getPoints(page: Page): Promise<number> {
  const text = await page.locator('.points .value').textContent()
  return parseInt(text?.trim() ?? '0', 10)
}

async function activateItem(itemCard: Locator): Promise<void> {
  await itemCard.click()
  await expect(itemCard).toHaveClass(/item-ready/, { timeout: 3000 })
  await itemCard.click()
}

function penaltySection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Penalties' }),
  })
}

test.describe('Penalty activation', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let penId = ''
  let penHelperId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME, INITIAL_POINTS)
    penId = await createTask(request, PEN_NAME, 'penalty', PEN_POINTS)
    penHelperId = await createTask(request, PEN_HELPER_NAME, 'penalty', PEN_POINTS)
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [penId, penHelperId], type: 'penalty' },
    })
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
    if (penId) await request.delete(`/api/task/${penId}`)
    if (penHelperId) await request.delete(`/api/task/${penHelperId}`)
  })

  test('Edit button appears on first penalty click', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    // Initially hidden
    await expect(card.getByTitle('Edit custom value')).not.toBeVisible()

    // First click: item enters ready state, edit button becomes visible
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await expect(card.getByTitle('Edit custom value')).toBeVisible()
  })

  test('Edit button disappears when clicking a different penalty card', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const section = penaltySection(page)
    const card = section.locator('.item-card').filter({ hasText: PEN_NAME })
    const helperCard = section.locator('.item-card').filter({ hasText: PEN_HELPER_NAME })
    await card.waitFor({ state: 'visible' })
    await helperCard.waitFor({ state: 'visible' })

    // First click on target card — edit button appears
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await expect(card.getByTitle('Edit custom value')).toBeVisible()

    // Click on a different card — target's edit button disappears
    await helperCard.click()
    await expect(card.getByTitle('Edit custom value')).not.toBeVisible()
  })

  test('Cancel penalty confirmation — no points deducted', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    const before = await getPoints(page)

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Cancel' }).click()

    await expect(page.getByRole('button', { name: 'Yes' })).not.toBeVisible()
    await expect(page.locator('.points .value')).toHaveText(String(before))
  })

  test('Confirm penalty activation — points deducted', async ({ page }) => {
    // Starts at INITIAL_POINTS (50)
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    const before = await getPoints(page)

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    // 50 - 20 = 30
    await expect(page.locator('.points .value')).toHaveText(String(before - PEN_POINTS))
  })

  test('Penalty can be activated multiple times — points deducted again', async ({ page }) => {
    // Starts at 30 after previous test
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    const before = await getPoints(page)

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    // 30 - 20 = 10
    await expect(page.locator('.points .value')).toHaveText(String(before - PEN_POINTS))
  })

  test('Points floor at 0 — penalty cannot make points negative', async ({ page }) => {
    // Starts at 10 after previous test; penalty is 20 pts
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    // 10 - 20 would be -10; app floors at 0
    await expect(page.locator('.points .value')).toHaveText('0')
  })
})
