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

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

const CHILD_NAME = 'NotifScrollChild'
const CHORE_COUNT = 10
const CHORE_PREFIX = 'NotifScrollChore'
const TARGET_CHORE_IDX = CHORE_COUNT // last chore, likely off-screen
const REWARD_NAME = 'NotifScrollReward'
const REWARD_COST = 10
const INITIAL_CHILD_POINTS = 50
const NARROW_VIEWPORT = { width: 480, height: 800 }

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

async function createChild(
  request: APIRequestContext,
  name: string,
  points: number,
): 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 id = (await list.json()).children?.find((c: any) => c.name === name)?.id ?? ''
  if (points > 0) await request.put(`/api/child/${id}/edit`, { data: { points } })
  return 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: 'notif test', cost } })
  const list = await request.get('/api/reward/list')
  return (await list.json()).rewards?.find((r: any) => r.name === name)?.id ?? ''
}

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('Notification click navigates and scrolls to task', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  const choreIds: string[] = []
  let targetChoreId = ''
  let rewardId = ''

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

    for (let i = 1; i <= CHORE_COUNT; i++) {
      choreIds.push(await createTask(request, `${CHORE_PREFIX}${i}`, 5))
    }
    rewardId = await createReward(request, REWARD_NAME, REWARD_COST)

    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: [rewardId] },
    })

    // The target chore is the last one — most likely off-screen
    targetChoreId = choreIds[TARGET_CHORE_IDX - 1]

    // Confirm the target chore → creates pending notification
    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: targetChoreId },
    })

    // Request the reward → creates pending notification
    await request.post(`/api/child/${childId}/request-reward`, {
      data: { reward_id: rewardId },
    })
  })

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

  test('Clicking a chore notification navigates and scrolls to the chore card', async ({
    page,
  }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto('/parent/notifications')

    const targetChoreName = `${CHORE_PREFIX}${TARGET_CHORE_IDX}`
    const notifItem = page.locator('.list-item').filter({ hasText: targetChoreName })
    await expect(notifItem).toBeVisible({ timeout: 5000 })

    await notifItem.click()

    // Verify navigation to parent child view with scrollTo query param
    await page.waitForURL(new RegExp(`/parent/${childId}\\?scrollTo=.*&entityType=chore`), {
      timeout: 5000,
    })

    // Verify the target chore card is scrolled into viewport
    const targetCard = choreSection(page).locator('.item-card').filter({ hasText: targetChoreName })
    await expect(targetCard).toBeVisible({ timeout: 5000 })
    await page.waitForTimeout(1000)
    expect(await isInViewport(targetCard)).toBe(true)
  })

  test('Clicking a reward notification scrolls reward card into viewport', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto('/parent/notifications')

    const notifItem = page.locator('.list-item').filter({ hasText: REWARD_NAME })
    await expect(notifItem).toBeVisible({ timeout: 5000 })

    await notifItem.click()

    await page.waitForURL(new RegExp(`/parent/${childId}\\?scrollTo=.*&entityType=reward`), {
      timeout: 5000,
    })

    const targetCard = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await expect(targetCard).toBeVisible({ timeout: 5000 })
    await page.waitForTimeout(1000)
    expect(await isInViewport(targetCard)).toBe(true)
  })
})
