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

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

const CHILD_NAME = 'ModifyActivateChild'
const CHORE_NAME = 'ModifyActChore'
const KIND_NAME = 'ModifyActKindness'
const PEN_NAME = 'ModifyActPenalty'
const REWARD_NAME = 'ModifyActReward'

const CHORE_POINTS = 10
const KIND_POINTS = 10
const PEN_POINTS = 10
const REWARD_COST = 100

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 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 test reward', cost } })
  const list = await request.get('/api/reward/list')
  const { rewards } = (await list.json()) as { rewards: { name: string; id: string }[] }
  return rewards?.find((r) => 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' }),
  })
}

async function openChoreOverrideModal(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()
  await page.getByRole('button', { name: 'Edit Points' }).click()
  await expect(page.getByRole('button', { name: 'Save' })).toBeVisible()
}

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

test.describe('Modified points take effect on activation', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let choreId = ''
  let kindId = ''
  let penId = ''
  let rewardId = ''

  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', KIND_POINTS)
    penId = await createTask(request, PEN_NAME, 'penalty', PEN_POINTS)
    rewardId = await createReward(request, 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: [rewardId] },
    })
  })

  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 (rewardId) await request.delete(`/api/reward/${rewardId}`)
  })

  test('Modified chore points are awarded on activation (override 25, default 10)', async ({
    page,
  }) => {
    // Edit override to 25 via kebab → Edit Points
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })
    await openChoreOverrideModal(page, card)
    await page.locator('#custom-value').fill('25')
    await page.getByRole('button', { name: 'Save' }).click()
    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()

    // Fresh navigation — activate chore and verify points awarded at override rate
    await page.goto(`/parent/${childId}`)
    const choreCard = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await choreCard.waitFor({ state: 'visible' })
    const before = await getPoints(page)

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

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

  test('Modified kindness points are awarded on activation (override 8, default 10)', async ({
    page,
  }) => {
    // Edit override to 8 via edit button
    await page.goto(`/parent/${childId}`)
    const card = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await card.waitFor({ state: 'visible' })
    await openEditModal(page, card)
    await page.locator('#custom-value').fill('8')
    await page.getByRole('button', { name: 'Save' }).click()
    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()

    // Fresh navigation — activate and verify points use override value
    await page.goto(`/parent/${childId}`)
    const kindCard = kindnessSection(page).locator('.item-card').filter({ hasText: KIND_NAME })
    await kindCard.waitFor({ state: 'visible' })
    const before = await getPoints(page)

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

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

  test('Modified penalty points are deducted at override rate (override 3, default 10)', async ({
    page,
  }) => {
    // Edit penalty override to 3 via edit button
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })
    await openEditModal(page, card)
    await page.locator('#custom-value').fill('3')
    await page.getByRole('button', { name: 'Save' }).click()
    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()

    // Fresh navigation — activate penalty and verify deduction uses override value
    await page.goto(`/parent/${childId}`)
    const penCard = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await penCard.waitFor({ state: 'visible' })
    const before = await getPoints(page)

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

    await expect(page.locator('.points .value')).toHaveText(String(before - 3))
  })

  test('Modified reward cost is reflected in points needed display (override 30)', async ({
    page,
  }) => {
    // Edit reward override to 30 via edit button
    // Child currently has 25 + 8 - 3 = 30 points from previous tests
    await page.goto(`/parent/${childId}`)
    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await card.waitFor({ state: 'visible' })
    await openEditModal(page, card)
    await page.locator('#custom-value').fill('30')
    await page.getByRole('button', { name: 'Save' }).click()
    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()

    // Fresh navigation — verify reward shows "REWARD READY" (30pts held, 30 cost override)
    await page.goto(`/parent/${childId}`)
    const rewardCard = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await rewardCard.waitFor({ state: 'visible' })
    await expect(rewardCard.getByText('REWARD READY')).toBeVisible()
  })
})
