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

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

const CHILD_NAME = 'ActivateKindnessChild'
const KIND_NAME = 'TriggerTestKindness'
const KIND_HELPER_NAME = 'TriggerKindnessHelper'
const KIND_POINTS = 5

async function createChild(request: APIRequestContext, name: string): 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')
  return (await list.json()).children?.find((c: any) => c.name === name)?.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 kindnessSection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Kindness Acts' }),
  })
}

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

  let childId = ''
  let kindId = ''
  let kindHelperId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    kindId = await createTask(request, KIND_NAME, 'kindness', KIND_POINTS)
    kindHelperId = await createTask(request, KIND_HELPER_NAME, 'kindness', KIND_POINTS)
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [kindId, kindHelperId], type: 'kindness' },
    })
  })

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

  test('Edit button appears on first kindness act click', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_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 kindness card', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const section = kindnessSection(page)
    const card = section.locator('.item-card').filter({ hasText: KIND_NAME })
    const helperCard = section.locator('.item-card').filter({ hasText: KIND_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 kindness act confirmation — no points awarded', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_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 kindness act activation — points awarded', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_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()

    await expect(page.locator('.points .value')).toHaveText(String(before + KIND_POINTS))
  })

  test('Kindness act can be activated a second time — points awarded again', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await card.waitFor({ state: 'visible' })

    const before = await getPoints(page)

    // Second activation of the same kindness act
    await activateItem(card)
    await expect(page.getByRole('button', { name: 'Yes' })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    await expect(page.locator('.points .value')).toHaveText(String(before + KIND_POINTS))
  })
})
