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

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

const CHILD_NAME = 'ActivateChoreChild'
const CHORE_NAME = 'TriggerTestChore'
const KIND_NAME = 'TriggerChoreHelperKindness'
const CHORE_POINTS = 10

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 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' }),
  })
}

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

  let childId = ''
  let choreId = ''
  let kindId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    choreId = await createTask(request, CHORE_NAME, 'chore', CHORE_POINTS)
    kindId = await createTask(request, KIND_NAME, 'kindness', 5)
    // assign chore
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [choreId], type: 'chore' },
    })
    // assign kindness (set-tasks preserves other types)
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [kindId], type: 'kindness' },
    })
    // Add a schedule so COMPLETED status persists after trigger
    await request.put(`/api/child/${childId}/task/${choreId}/schedule`, {
      data: {
        mode: 'interval',
        interval_days: 1,
        anchor_date: new Date().toLocaleDateString('en-CA'),
        interval_has_deadline: false,
      },
    })
  })

  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}`)
  })

  test('Kebab button appears after first chore click', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Initially hidden
    await expect(card.getByRole('button', { name: 'Options' })).not.toBeVisible()

    // First click: item enters ready state, kebab becomes visible
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await expect(card.getByRole('button', { name: 'Options' })).toBeVisible()
  })

  test('Kebab button disappears when clicking a non-chore item', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    const kindCard = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await card.waitFor({ state: 'visible' })
    await kindCard.waitFor({ state: 'visible' })

    // Click chore — kebab appears
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await expect(card.getByRole('button', { name: 'Options' })).toBeVisible()

    // Click a kindness item — selectedChoreId resets to null, kebab gone
    await kindCard.click()
    await expect(card.getByRole('button', { name: 'Options' })).not.toBeVisible()
  })

  test('Cancel chore confirmation — no points awarded', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_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 chore activation — points awarded', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_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 + CHORE_POINTS))
  })

  test('Confirmed chore shows COMPLETED stamp', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })
    await expect(card.getByText('COMPLETED')).toBeVisible()
  })

  test('Clicking a completed chore does not open confirmation', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    const before = await getPoints(page)

    // Two-click completed chore
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.click()

    // No confirmation dialog should appear; points must remain unchanged
    await expect(page.locator('.points .value')).toHaveText(String(before))
    await expect(page.getByRole('button', { name: 'Yes' })).not.toBeVisible()
  })
})
