// APID-02 CE cross-boundary guard — a FormItem inside a Form (both custom
// elements) must receive its validation error from the parent Form's engine
// across the defineCustomElement boundary. This is the permanent, real-browser
// proof of the engine-on-host + closest('tvu-form') + explicit-subscribe design
// (the Stage 0 spike proved the mechanism; this guards it against regression,
// like the INFRA-F54 named-slot guard). See src/canonical/composables/useFormContext.ts.
//
// Guard: vitest also globs *.spec.ts — skip under VITEST so pre-commit `vitest run`
// doesn't run this Playwright test in jsdom (mirrors named-slot-projection.spec.ts).
import { collectVisibleText } from '../parity/lib/collect-visible'

if (process.env.VITEST) {
  const { test } = await import('vitest')
  test.skip('APID-02 form CE validation runs via playwright.render-verification-react.config.ts', () => {})
} else {
  const { test, expect } = await import('@playwright/test')

  test('FormItem surfaces the Form engine error across the CE boundary', async ({ page }) => {
    await page.goto('/?f54=form-validate&theme=dark')
    await page.locator('[data-f54-case="form-validate"]').waitFor({ state: 'attached' })
    // Let the React wrapper's useEffect push model/rules onto the CE host + the
    // child FormItem register with the engine before we validate (property set is
    // async — same settle wait the named-slot guard uses).
    await page.waitForTimeout(300)
    // Drive validation via the defineExpose'd validate() on the <tvu-form> host —
    // the real consumer path (formRef.validate()). This exercises the full cross-CE
    // chain: engine.validate() → subscribe notify → child FormItem re-render.
    await page.locator('tvu-form').evaluate(
      (el) => (el as unknown as { validate?: () => Promise<unknown> }).validate?.(),
    )
    await page.waitForTimeout(200)
    const visibleText = await page.evaluate(collectVisibleText)
    expect(
      visibleText.includes('FORM_EMAIL_REQUIRED'),
      `expected the engine error to render in the child FormItem — got: ${visibleText}`,
    ).toBe(true)
  })
}
