// @vitest-environment jsdom
//
// Render smokes for the /admin subtree's scoped fallbacks: error.tsx (message +
// reset), loading.tsx (skeleton), not-found.tsx (message + back link). Pure
// presentational components, no framework hooks.

import { afterEach, describe, expect, test, vi } from 'vitest'
import { act, createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { I18nProvider } from '@voltro/i18n'
import enCatalog from '../../locales/en'

const { default: AdminError } = await import('./error')
const { default: AdminLoading } = await import('./loading')
const { default: AdminNotFound } = await import('./not-found')

;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true

let container: HTMLDivElement
let root: Root

// error.tsx / not-found.tsx use <T>, so wrap renders in the framework's
// <I18nProvider> (auto-wired in the running app).
const render = (node: ReactNode): void => {
  container = document.createElement('div')
  document.body.appendChild(container)
  act(() => {
    root = createRoot(container)
    root.render(
      createElement(I18nProvider, { locale: 'en', messages: enCatalog, defaultLocale: 'en', children: node }),
    )
  })
}

afterEach(() => {
  if (root) act(() => root.unmount())
  container?.remove()
  document.body.innerHTML = ''
})

describe('admin error boundary', () => {
  test('renders the error text and calls reset when Try again is clicked', () => {
    const reset = vi.fn()
    render(createElement(AdminError, { error: new Error('kaboom'), reset }))
    expect(container.textContent).toContain('kaboom')
    const btn = container.querySelector('button')!
    act(() => { btn.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
    expect(reset).toHaveBeenCalledTimes(1)
  })
})

describe('admin loading', () => {
  test('renders skeleton placeholders', () => {
    render(createElement(AdminLoading))
    expect(container.querySelectorAll('.skeleton').length).toBeGreaterThan(0)
  })
})

describe('admin not-found', () => {
  test('renders the not-found message and a link back to the overview', () => {
    render(createElement(AdminNotFound))
    expect(container.textContent).toContain('Not found')
    const back = Array.from(container.querySelectorAll('a')).find(
      (a) => a.getAttribute('href') === '/admin',
    )
    expect(back).toBeTruthy()
  })
})
