// spec: e2e/plans/parent-notifications.plan.md §6

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

const CHILD_NAME = 'DeepLinkChild'
const CHORE_PREFIX = 'DeepLinkChore'
const CHORE_COUNT = 10
const REWARD_NAME = 'DeepLinkReward'
const REWARD_COST = 20
const INITIAL_POINTS = 100
const NARROW_VIEWPORT = { width: 480, height: 800 }

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: 'deep link 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): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Chores' }),
  })
}

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

test.describe('ParentView Deep-Link Navigation', () => {
  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_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] },
    })

    // Target the last chore (most likely off-screen)
    targetChoreId = choreIds[CHORE_COUNT - 1]

    await request.post(`/api/child/${childId}/confirm-chore`, {
      data: { task_id: targetChoreId },
    })

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

  // 6.1 Deep link to chore — correct card is scrolled into viewport
  test('Deep link to chore scrolls correct card into viewport', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto(`/parent/${childId}?scrollTo=${targetChoreId}&entityType=chore`)
    const card = choreSection(page)
      .locator('.item-card')
      .filter({ hasText: `${CHORE_PREFIX}${CHORE_COUNT}` })
    await expect(card).toBeVisible({ timeout: 5000 })
    await page.waitForTimeout(800)
    expect(await isInViewport(card)).toBe(true)
  })

  // 6.2 Deep link to reward — correct card is scrolled into viewport
  test('Deep link to reward scrolls correct card into viewport', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto(`/parent/${childId}?scrollTo=${rewardId}&entityType=reward`)
    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await page.waitForTimeout(800)
    expect(await isInViewport(card)).toBe(true)
  })

  // 6.3 Deep link with unknown entityType — page loads without JS error
  test('Deep link with unknown entityType loads without JS error', async ({ page }) => {
    const errors: string[] = []
    page.on('pageerror', (err) => errors.push(err.message))
    await page.goto(`/parent/${childId}?scrollTo=${targetChoreId}&entityType=unknown`)
    await page.waitForTimeout(500)
    expect(errors).toHaveLength(0)
    await expect(page.locator('h3', { hasText: 'Chores' })).toBeVisible()
  })

  // 6.4 Deep link with missing scrollTo — page loads normally
  test('Deep link with missing scrollTo loads normally', async ({ page }) => {
    await page.goto(`/parent/${childId}?entityType=chore`)
    await expect(page.locator('h3', { hasText: 'Chores' })).toBeVisible({ timeout: 5000 })
  })

  // 6.5 Deep link with no query params — page loads normally
  test('Deep link with no query params loads normally', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    await expect(page.locator('h3', { hasText: 'Chores' })).toBeVisible({ timeout: 5000 })
    await expect(page.locator('h3', { hasText: 'Rewards' })).toBeVisible()
  })

  // 6.6 Clicking a chore notification produces the correct deep link
  test('Clicking a chore notification produces correct deep link', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: `${CHORE_PREFIX}${CHORE_COUNT}` })
    await expect(item).toBeVisible({ timeout: 5000 })
    await item.click()
    await page.waitForURL(new RegExp(`/parent/${childId}\\?scrollTo=.*&entityType=chore`), {
      timeout: 5000,
    })
    expect(page.url()).toContain(`scrollTo=${targetChoreId}`)
    expect(page.url()).toContain('entityType=chore')
    const card = choreSection(page)
      .locator('.item-card')
      .filter({ hasText: `${CHORE_PREFIX}${CHORE_COUNT}` })
    await expect(card).toBeVisible({ timeout: 5000 })
    await page.waitForTimeout(800)
    expect(await isInViewport(card)).toBe(true)
  })

  // 6.7 Clicking a reward notification produces the correct deep link
  test('Clicking a reward notification produces correct deep link', async ({ page }) => {
    await page.setViewportSize(NARROW_VIEWPORT)
    await page.goto('/parent/notifications')
    const item = page.locator('.list-item').filter({ hasText: REWARD_NAME })
    await expect(item).toBeVisible({ timeout: 5000 })
    await item.click()
    await page.waitForURL(new RegExp(`/parent/${childId}\\?scrollTo=.*&entityType=reward`), {
      timeout: 5000,
    })
    expect(page.url()).toContain(`scrollTo=${rewardId}`)
    expect(page.url()).toContain('entityType=reward')
    const card = rewardSection(page).locator('.item-card').filter({ hasText: REWARD_NAME })
    await expect(card).toBeVisible({ timeout: 5000 })
    await page.waitForTimeout(800)
    expect(await isInViewport(card)).toBe(true)
  })
})
