// spec: frontend/vue-app/e2e/plans/parent-rewards-management.plan.md
// seed: e2e/seed.spec.ts

import { test, expect } from '@playwright/test'

test.describe('Reward cancellation', () => {
  test.beforeEach(async ({ page }, testInfo) => {
    test.skip(testInfo.project.name === 'chromium-no-pin', 'Requires parent-authenticated mode')
  })

  test.describe.configure({ mode: 'serial' })

  test('Cancel reward creation', async ({ page }) => {
    const name = `CancelMe-${Date.now()}`
    // 1. Navigate and open create form
    await page.goto('/parent/rewards')
    await page.getByRole('button', { name: 'Create Reward' }).click()
    await expect(page.locator('text=Reward Name')).toBeVisible()

    // 2. Fill then cancel
    await page.evaluate((n) => {
      const setVal = (sel: string, val: string) => {
        const el = document.querySelector(sel) as HTMLInputElement | null
        if (el) {
          el.value = val
          el.dispatchEvent(new Event('input', { bubbles: true }))
          el.dispatchEvent(new Event('change', { bubbles: true }))
        }
      }
      setVal('#name', n)
      setVal('#cost', '5')
    }, name)
    await page.getByRole('button', { name: 'Cancel' }).click()

    // verify return to list and the cancelled item was not saved
    await expect(page.getByText(name, { exact: true })).toHaveCount(0)
  })

  test('Cancel reward edit', async ({ page }) => {
    // 1. Ensure Toy car exists and open edit
    const suffix = Date.now()
    const original = `Toy car ${suffix}`
    await page.goto('/parent/rewards')
    if (!(await page.locator(`text=${original}`).count())) {
      await page.getByRole('button', { name: 'Create Reward' }).click()
      await page.evaluate((name) => {
        const setVal = (sel: string, val: string) => {
          const el = document.querySelector(sel) as HTMLInputElement | null
          if (el) {
            el.value = val
            el.dispatchEvent(new Event('input', { bubbles: true }))
            el.dispatchEvent(new Event('change', { bubbles: true }))
          }
        }
        setVal('#name', name)
        setVal('#cost', '20')
      }, original)
      await page.getByRole('button', { name: 'Create' }).click()
    }
    await expect(page.locator(`text=${original}`)).toBeVisible()
    await page.click(`text=${original}`)
    await expect(page.locator('text=Reward Name')).toBeVisible()

    // 2. make a change then cancel
    await page.evaluate(() => {
      const el = document.querySelector('#name') as HTMLInputElement | null
      if (el) {
        el.value = 'Should not save'
        el.dispatchEvent(new Event('input', { bubbles: true }))
        el.dispatchEvent(new Event('change', { bubbles: true }))
      }
    })
    await page.getByRole('button', { name: 'Cancel' }).click()

    await expect(page.locator('text=Should not save')).toHaveCount(0)
    await expect(page.locator(`text=${original}`)).toBeVisible()
  })
})
