// spec: e2e/plans/task-activated.plan.md
// Tests for the "pending reward warning" dialog that appears when the parent tries to
// activate a chore, kindness act, penalty, or a different reward while one of the child's
// reward requests is in a pending state.

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

const CHILD_NAME = 'PendingRewardWarnChild'
const CHORE_NAME = 'PendingWarnChore'
const KIND_NAME = 'PendingWarnKindness'
const PEN_NAME = 'PendingWarnPenalty'
const PENDING_REWARD_NAME = 'PendingWarnReward'
const OTHER_REWARD_NAME = 'PendingWarnOtherReward'
const REWARD_COST = 10
const CHORE_POINTS = 5
const KIND_POINTS = 5
const PEN_POINTS = 5
const INITIAL_POINTS = 30 // must be >= REWARD_COST so the request-reward call succeeds

// ── helpers ───────────────────────────────────────────────────────────────────

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 createReward(
  request: APIRequestContext,
  name: string,
  cost: number,
): Promise<string> {
  const pre = await request.get('/api/reward/list')
  for (const r of (await pre.json()).rewards ?? []) {
    if (r.name === name) await request.delete(`/api/reward/${r.id}`)
  }
  await request.put('/api/reward/add', { data: { name, description: 'E2E pending-warn test', cost } })
  const list = await request.get('/api/reward/list')
  return (await list.json()).rewards?.find((r: any) => r.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 choreSection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Chores' }),
  })
}

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

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

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

// ── suite ─────────────────────────────────────────────────────────────────────

test.describe('Pending reward warning dialog', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let choreId = ''
  let kindId = ''
  let penId = ''
  let pendingRewardId = ''
  let otherRewardId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME, INITIAL_POINTS)
    choreId = await createTask(request, CHORE_NAME, 'chore', CHORE_POINTS)
    kindId = await createTask(request, KIND_NAME, 'kindness', KIND_POINTS)
    penId = await createTask(request, PEN_NAME, 'penalty', PEN_POINTS)
    pendingRewardId = await createReward(request, PENDING_REWARD_NAME, REWARD_COST)
    otherRewardId = await createReward(request, OTHER_REWARD_NAME, REWARD_COST)

    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [choreId], type: 'chore' },
    })
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [kindId], type: 'kindness' },
    })
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [penId], type: 'penalty' },
    })
    await request.put(`/api/child/${childId}/set-rewards`, {
      data: { reward_ids: [pendingRewardId, otherRewardId] },
    })
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
    if (choreId) await request.delete(`/api/task/${choreId}`)
    if (kindId) await request.delete(`/api/task/${kindId}`)
    if (penId) await request.delete(`/api/task/${penId}`)
    if (pendingRewardId) await request.delete(`/api/reward/${pendingRewardId}`)
    if (otherRewardId) await request.delete(`/api/reward/${otherRewardId}`)
  })

  // Ensure each test starts with the pending reward freshly requested
  test.beforeEach(async ({ request }) => {
    // Reset child points so the request-reward call always succeeds
    await request.put(`/api/child/${childId}/edit`, { data: { points: INITIAL_POINTS } })
    // Cancel any leftover request (404 if none — ignored)
    await request.post(`/api/child/${childId}/cancel-request-reward`, {
      data: { reward_id: pendingRewardId },
    })
    // Place a fresh pending request
    await request.post(`/api/child/${childId}/request-reward`, {
      data: { reward_id: pendingRewardId },
    })
  })

  // ── banner ────────────────────────────────────────────────────────────────

  test('Pending reward card shows PENDING banner', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = rewardSection(page)
      .locator('.item-card')
      .filter({ hasText: PENDING_REWARD_NAME })
    await card.waitFor({ state: 'visible' })
    await expect(card.locator('.pending')).toHaveText('PENDING')
  })

  // ── chore ─────────────────────────────────────────────────────────────────

  test('Chore activation — Cancel on pending dialog leaves state unchanged', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })
    const pointsBefore = await getPoints(page)

    await activateItem(card)

    // Pending reward warning dialog appears (has a "No" button)
    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'No', exact: true }).click()

    // Dialog dismissed; task confirmation dialog must NOT have appeared
    await expect(page.getByRole('button', { name: 'No', exact: true })).not.toBeVisible()
    await expect(page.getByRole('button', { name: 'Cancel' })).not.toBeVisible()
    // Points unchanged
    await expect(page.locator('.points .value')).toHaveText(String(pointsBefore))
    // PENDING banner still visible on the reward card
    const rewardCard = rewardSection(page)
      .locator('.item-card')
      .filter({ hasText: PENDING_REWARD_NAME })
    await expect(rewardCard.locator('.pending')).toHaveText('PENDING')
  })

  test('Chore activation — Confirm on pending dialog cancels pending reward and triggers chore', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })
    const pointsBefore = await getPoints(page)

    await activateItem(card)

    // Pending reward warning dialog
    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    // After confirming, the task confirmation dialog appears (has "Cancel" button)
    await expect(page.getByRole('button', { name: 'Cancel' })).toBeVisible({ timeout: 3000 })
    await page.getByRole('button', { name: 'Yes' }).click()

    // Chore points awarded — points changed from initial value
    await expect(page.locator('.points .value')).not.toHaveText(String(pointsBefore), {
      timeout: 3000,
    })
  })

  // ── kindness ──────────────────────────────────────────────────────────────

  test('Kindness activation — Cancel on pending dialog leaves state unchanged', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await card.waitFor({ state: 'visible' })
    const pointsBefore = await getPoints(page)

    await activateItem(card)

    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'No', exact: true }).click()

    await expect(page.getByRole('button', { name: 'No', exact: true })).not.toBeVisible()
    await expect(page.getByRole('button', { name: 'Cancel' })).not.toBeVisible()
    await expect(page.locator('.points .value')).toHaveText(String(pointsBefore))
  })

  test('Kindness activation — Confirm on pending dialog cancels pending reward and triggers kindness', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await card.waitFor({ state: 'visible' })
    const pointsBefore = await getPoints(page)

    await activateItem(card)

    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

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

    await expect(page.locator('.points .value')).not.toHaveText(String(pointsBefore), {
      timeout: 3000,
    })
  })

  // ── penalty ───────────────────────────────────────────────────────────────

  test('Penalty activation — Cancel on pending dialog leaves state unchanged', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })
    const pointsBefore = await getPoints(page)

    await activateItem(card)

    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'No', exact: true }).click()

    await expect(page.getByRole('button', { name: 'No', exact: true })).not.toBeVisible()
    await expect(page.getByRole('button', { name: 'Cancel' })).not.toBeVisible()
    await expect(page.locator('.points .value')).toHaveText(String(pointsBefore))
  })

  test('Penalty activation — Confirm on pending dialog cancels pending reward and triggers penalty', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })
    const pointsBefore = await getPoints(page)

    await activateItem(card)

    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

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

    // Penalty deducted points
    await expect(page.locator('.points .value')).not.toHaveText(String(pointsBefore), {
      timeout: 3000,
    })
  })

  // ── other reward ──────────────────────────────────────────────────────────

  test('Other reward activation — Cancel on pending dialog leaves state unchanged', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)

    // Both rewards should be ready (INITIAL_POINTS >= REWARD_COST)
    const pendingCard = rewardSection(page)
      .locator('.item-card')
      .filter({ hasText: PENDING_REWARD_NAME })
    const otherCard = rewardSection(page)
      .locator('.item-card')
      .filter({ hasText: OTHER_REWARD_NAME })
    await pendingCard.waitFor({ state: 'visible' })
    await otherCard.waitFor({ state: 'visible' })

    await expect(pendingCard.locator('.pending')).toHaveText('PENDING')
    await expect(otherCard.getByText('REWARD READY')).toBeVisible()

    const pointsBefore = await getPoints(page)
    await activateItem(otherCard)

    // Pending reward warning dialog appears when another reward has a pending request
    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'No', exact: true }).click()

    await expect(page.getByRole('button', { name: 'No', exact: true })).not.toBeVisible()
    await expect(page.getByRole('button', { name: 'Cancel' })).not.toBeVisible()
    await expect(page.locator('.points .value')).toHaveText(String(pointsBefore))
    // PENDING banner still visible — reward request was not cancelled
    await expect(pendingCard.locator('.pending')).toHaveText('PENDING')
  })

  test('Other reward activation — Confirm on pending dialog cancels the pending reward', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)

    const pendingCard = rewardSection(page)
      .locator('.item-card')
      .filter({ hasText: PENDING_REWARD_NAME })
    const otherCard = rewardSection(page)
      .locator('.item-card')
      .filter({ hasText: OTHER_REWARD_NAME })
    await pendingCard.waitFor({ state: 'visible' })
    await otherCard.waitFor({ state: 'visible' })

    await activateItem(otherCard)

    await expect(page.getByRole('button', { name: 'No', exact: true })).toBeVisible()
    await page.getByRole('button', { name: 'Yes' }).click()

    // Pending dialog closes; reward confirm does NOT auto-open (other reward must be re-clicked)
    await expect(page.getByRole('button', { name: 'No', exact: true })).not.toBeVisible()
    await expect(page.getByRole('button', { name: 'Cancel' })).not.toBeVisible()

    // The pending reward request was cancelled — PENDING banner should disappear
    await expect(pendingCard.locator('.pending')).not.toBeVisible({ timeout: 5000 })
  })
})
