// spec: e2e/plans/bugs-1.0.6-set01.plan.md §6

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

const CHILD_NAME = 'ScrollEditChild'
const CHORE_COUNT = 12
const REWARD_COUNT = 6
const CHORE_PREFIX = 'ScrollEditChore'
const REWARD_PREFIX = 'ScrollEditReward'
const NARROW_VIEWPORT = { width: 480, height: 800 }

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,
  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: 'chore' } })
  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: 'scroll test', cost } })
  const list = await request.get('/api/reward/list')
  return (await list.json()).rewards?.find((r: any) => r.name === name)?.id ?? ''
}

async function isInViewport(locator: Locator): Promise<boolean> {
  return locator.evaluate((el) => {
    const rect = el.getBoundingClientRect()
    return (
      rect.bottom > 0 &&
      rect.right > 0 &&
      rect.top < (window.innerHeight || document.documentElement.clientHeight) &&
      rect.left < (window.innerWidth || document.documentElement.clientWidth)
    )
  })
}

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

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

test.describe('Scroll to edited task after save', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  const choreIds: string[] = []
  const rewardIds: string[] = []

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)

    for (let i = 1; i <= CHORE_COUNT; i++) {
      choreIds.push(await createTask(request, `${CHORE_PREFIX}${i}`, 5 + i))
    }
    for (let i = 1; i <= REWARD_COUNT; i++) {
      rewardIds.push(await createReward(request, `${REWARD_PREFIX}${i}`, 10 + i))
    }

    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: choreIds, type: 'chore' },
    })
    await request.put(`/api/child/${childId}/set-rewards`, {
      data: { reward_ids: rewardIds },
    })
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
    for (const id of choreIds) await request.delete(`/api/task/${id}`)
    for (const id of rewardIds) await request.delete(`/api/reward/${id}`)
  })

  test('Edited chore card scrolls into viewport after override save', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto(`/parent/${childId}`)

    // Target the last chore — it should be scrolled off-screen in a narrow viewport
    const targetName = `${CHORE_PREFIX}${CHORE_COUNT}`
    const targetCard = choreSection(page).locator('.item-card').filter({ hasText: targetName })
    await choreSection(page).locator('.item-card').first().waitFor({ state: 'visible' })

    // Click the target chore to bring up the kebab menu (first click centers + shows menu)
    await targetCard.click()
    await expect(targetCard).toHaveClass(/item-ready/, { timeout: 3000 })

    // Open the kebab menu → "Edit Points"
    await targetCard.getByRole('button', { name: 'Options' }).click()
    await page.getByText('Edit Points').click()

    // Override modal should be visible with input
    const input = page.locator('#custom-value')
    await expect(input).toBeVisible()

    // Set a new value and save
    await input.fill('99')
    await page.getByRole('button', { name: 'Save' }).click()

    // After SSE override event → list refreshes → card scrolls into view
    // Use expect.poll to retry, allowing scroll animation to complete
    await expect(targetCard).toBeVisible({ timeout: 5000 })
    await expect.poll(() => isInViewport(targetCard), { timeout: 3000 }).toBe(true)
  })

  test('Edited reward card scrolls into viewport after override save', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto(`/parent/${childId}`)

    // Target the last reward
    const targetName = `${REWARD_PREFIX}${REWARD_COUNT}`
    const targetCard = rewardSection(page).locator('.item-card').filter({ hasText: targetName })
    await rewardSection(page).locator('.item-card').first().waitFor({ state: 'visible' })

    // Click the target reward to center it and show the edit button
    await targetCard.click()
    await expect(targetCard).toHaveClass(/item-ready/, { timeout: 3000 })

    // Click the Edit button
    await targetCard.locator('.edit-button').click()

    // Override modal should be visible
    const input = page.locator('#custom-value')
    await expect(input).toBeVisible()

    // Set a new value and save
    await input.fill('77')
    await page.getByRole('button', { name: 'Save' }).click()

    // After SSE override event → list refreshes → card scrolls into view
    // Use expect.poll to retry, allowing scroll animation to complete
    await expect(targetCard).toBeVisible({ timeout: 5000 })
    await expect.poll(() => isInViewport(targetCard), { timeout: 3000 }).toBe(true)
  })
})
