// @vitest-environment jsdom
//
// `/dashboard/settings` — SSR page whose only behaviour is a "sign out" button
// that clears the demo cookie + hard-navigates to `/`. We assert the config
// exports and that clicking Sign out expires the SESSION_COOKIE.

import { afterEach, beforeEach, 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: Settings, meta, renderMode } = await import('./page')

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

let container: HTMLDivElement
let root: Root

// The page uses <T>, so wrap renders in the framework's <I18nProvider>.
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 }),
    )
  })
}

beforeEach(() => {
  // Seed a session cookie so we can observe it being cleared.
  document.cookie = 'demo_session=ok; path=/'
})

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

describe('settings — config', () => {
  test('is an SSR page titled Settings', () => {
    expect(renderMode).toBe('ssr')
    expect(meta({ locale: 'en' }).title).toBe('Settings')
  })
})

describe('settings — sign out', () => {
  test('expires the session cookie and hard-navigates home', () => {
    // jsdom's location.assign is a non-configurable no-op that throws "not
    // implemented"; replace the whole location object so we can observe the
    // hard-navigation target.
    const assign = vi.fn()
    vi.stubGlobal('location', { ...window.location, assign, href: '' })

    render(createElement(Settings))
    const btn = Array.from(container.querySelectorAll('button')).find(
      (b) => (b.textContent ?? '').includes('Sign out'),
    )!
    act(() => { btn.dispatchEvent(new MouseEvent('click', { bubbles: true })) })

    expect(document.cookie).not.toContain('demo_session=ok')
    expect(assign).toHaveBeenCalledWith('/')
  })
})
