// spec: e2e/plans/task-modified.plan copy.md

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

const CHILD_NAME = 'ModifyResetChild'
const CHORE_NAME = 'ModifyResetChore'
const CHORE_POINTS = 10
const HELPER_KIND_NAME = 'ModifyResetKindnessHelper'

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')
  const { children } = (await list.json()) as { children: { name: string; id: string }[] }
  return children?.find((c) => 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')
  const { tasks } = (await list.json()) as { tasks: { name: string; id: string }[] }
  return tasks?.find((t) => t.name === name)?.id ?? ''
}

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

async function openChoreKebab(page: Page, card: Locator): Promise<void> {
  await card.click()
  await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
  await expect(card.getByRole('button', { name: 'Options' })).toBeVisible()
  await card.getByRole('button', { name: 'Options' }).click()
}

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

  let childId = ''
  let choreId = ''
  let helperKindId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    choreId = await createTask(request, CHORE_NAME, 'chore', CHORE_POINTS)
    helperKindId = await createTask(request, HELPER_KIND_NAME, 'kindness', 5)
    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: [helperKindId], 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 (helperKindId) await request.delete(`/api/task/${helperKindId}`)
  })

  test('"Reset" is absent from kebab menu when chore is not yet completed', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    await openChoreKebab(page, card)
    await expect(page.getByRole('button', { name: 'Reset' })).not.toBeVisible()
    await expect(page.getByRole('button', { name: 'Edit Points' })).toBeVisible()
  })

  test('Chore shows COMPLETED stamp after activation and confirmation', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

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

    await expect(card.getByText('COMPLETED')).toBeVisible()
  })

  test('"Reset" appears in kebab menu after chore is completed', 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()

    await openChoreKebab(page, card)
    await expect(page.getByRole('button', { name: 'Reset' })).toBeVisible()
  })

  test('Clicking "Reset" removes the 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()

    await openChoreKebab(page, card)
    await page.getByRole('button', { name: 'Reset' }).click()

    await expect(card.getByText('COMPLETED')).not.toBeVisible()
  })

  test('Chore is re-activatable after reset — returns to COMPLETED on confirm', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Chore is not completed after the previous test's reset
    await expect(card.getByText('COMPLETED')).not.toBeVisible()

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

    await expect(card.getByText('COMPLETED')).toBeVisible()
  })

  test('Reset → activate cycle is repeatable without error', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Reset the now-completed chore
    await openChoreKebab(page, card)
    await page.getByRole('button', { name: 'Reset' }).click()
    await expect(card.getByText('COMPLETED')).not.toBeVisible()

    // Navigate fresh so item-ready state is cleared before activating
    await page.goto(`/parent/${childId}`)
    await card.waitFor({ state: 'visible' })

    // Activate again — COMPLETED returns
    await activateItem(card)
    await page.getByRole('button', { name: 'Yes' }).click()
    await expect(card.getByText('COMPLETED')).toBeVisible()
  })
})
