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

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

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

  test('Cancel penalty creation', async ({ page }) => {
    await page.goto('/parent/tasks/chores')
    await page.click('text=Penalties')
    await page.getByRole('button', { name: 'Create Penalty' }).click()
    await page.evaluate(() => {
      const setVal = (sel, val) => {
        const el = document.querySelector(sel)
        if (el) {
          el.value = val
          el.dispatchEvent(new Event('input', { bubbles: true }))
          el.dispatchEvent(new Event('change', { bubbles: true }))
        }
      }
      setVal('#name', 'Should not save')
      setVal('#points', '10')
    })
    // cancel before submitting the form
    await page.getByRole('button', { name: 'Cancel' }).click()
    await expect(page.locator('text=Should not save')).toHaveCount(0)
  })

  test('Cancel penalty edit', async ({ page }) => {
    await page.goto('/parent/tasks/chores')
    await page.click('text=Penalties')
    if (!(await page.getByText('No screen time', { exact: true }).count())) {
      await page.getByRole('button', { name: 'Create Penalty' }).click()
      await page.locator('#name').fill('No screen time')
      await page.locator('#points').fill('10')
      await page.getByRole('button', { name: 'Create' }).click()
      await expect(page.getByText('No screen time', { exact: true })).toBeVisible()
    }
    // open edit by clicking row
    await page.getByText('No screen time', { exact: true }).click()
    await page.evaluate(() => {
      const el = document.querySelector('#name')
      if (el) {
        el.value = 'Never saved'
        el.dispatchEvent(new Event('input', { bubbles: true }))
        el.dispatchEvent(new Event('change', { bubbles: true }))
      }
    })
    await page.getByRole('button', { name: 'Cancel' }).click()
    await expect(page.getByText('No screen time', { exact: true })).toBeVisible()
  })
})
