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

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

const CHILD_NAME = 'ModifyChoreChild'
const CHORE_NAME = 'ModifyTestChore'
const CHORE_POINTS = 10
const HELPER_KIND_NAME = 'ModifyChoreHelperKindness'

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 ?? ''
}

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

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

test.describe('Chore edit points', () => {
  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' },
    })
  })

  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('Kebab button is hidden initially, visible after first click, hidden after deselect', 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 (v-show=false while selectedChoreId != item.id)
    await expect(card.getByRole('button', { name: 'Options' })).toBeHidden()

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

    // Clicking a kindness card resets selectedChoreId to null → kebab hidden
    const kindCard = kindnessSection(page)
      .locator('.item-card')
      .filter({ hasText: HELPER_KIND_NAME })
    await kindCard.click()
    await expect(card.getByRole('button', { name: 'Options' })).toBeHidden()
  })

  test('Kebab menu contains "Edit Points" and "Schedule"', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

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

  test('"Edit Points" opens override modal pre-populated with current points', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    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.locator('.modal-title')).toHaveText(CHORE_NAME)
    await expect(page.locator('#custom-value')).toHaveValue(String(CHORE_POINTS))
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Clicking outside the modal does not close it', async ({ page }) => {
    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)

    // Click the backdrop area far from the modal dialog
    await page.locator('.modal-backdrop').click({ position: { x: 5, y: 5 }, force: true })

    // Modal must still be visible
    await expect(page.getByRole('button', { name: 'Save' })).toBeVisible()
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Cancel does not save — card still shows original points, no ⭐ badge', async ({ page }) => {
    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('99')
    await page.getByRole('button', { name: 'Cancel' }).click()

    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()
    await expect(card.locator('.item-points')).toContainText(`${CHORE_POINTS} Points`)
    await expect(card.locator('.override-badge')).not.toBeVisible()
  })

  test('Saving a valid new value updates the displayed points on the card', async ({ page }) => {
    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('50')
    await page.getByRole('button', { name: 'Save' }).click()

    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()
    await expect(card.locator('.item-points')).toContainText('50 Points')
  })

  test('⭐ override badge appears on the card after saving a custom value', async ({ page }) => {
    // Badge state persists server-side; verify on a fresh page load
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })
    await expect(card.locator('.override-badge')).toBeVisible()
  })

  test('⭐ badge persists after changing value back to the original default', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = choreSection(page).locator('.item-card').filter({ hasText: CHORE_NAME })
    await card.waitFor({ state: 'visible' })

    // Change override back to original value — badge stays until item is unassigned/reassigned
    await openChoreOverrideModal(page, card)
    await page.locator('#custom-value').fill(String(CHORE_POINTS))
    await page.getByRole('button', { name: 'Save' }).click()

    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()
    await expect(card.locator('.item-points')).toContainText(`${CHORE_POINTS} Points`)
    await expect(card.locator('.override-badge')).toBeVisible()
  })

  test('Negative value disables the Save button', async ({ page }) => {
    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('-1')
    await expect(page.getByRole('button', { name: 'Save' })).toBeDisabled()
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Value above 10000 disables Save; exactly 10000 enables it', async ({ page }) => {
    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('10001')
    await expect(page.getByRole('button', { name: 'Save' })).toBeDisabled()
    await page.locator('#custom-value').fill('10000')
    await expect(page.getByRole('button', { name: 'Save' })).toBeEnabled()
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Zero is a valid value — card shows "0 Points" with ⭐ badge', async ({ page }) => {
    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('0')
    await expect(page.getByRole('button', { name: 'Save' })).toBeEnabled()
    await page.getByRole('button', { name: 'Save' }).click()

    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()
    await expect(card.locator('.item-points')).toContainText('0 Points')
    await expect(card.locator('.override-badge')).toBeVisible()
  })
})
