// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'

/**
 * Render tests for the `?selected=<userId>` deep link written by the command
 * palette (`/users?selected=<id>`): once the member list loads, the matching
 * member's detail drawer opens. Unknown ids are tolerated — no drawer, no crash.
 */

const MEMBER = {
  id: 'u1',
  name: 'Priya Nair',
  email: 'priya@actuatemedia.com',
  initials: 'PN',
  role: 'EDITOR',
  roleName: 'Editor' as const,
  status: 'active' as const,
  mfaEnabled: true,
  externalDomain: false,
  lastLoginAt: null,
  lastActiveAt: null,
  acceptedInviteAt: new Date('2026-01-02').toISOString(),
  createdAt: new Date('2026-01-01').toISOString(),
  isCurrentUser: false,
}

const DETAIL = {
  ...MEMBER,
  avatarUrl: null,
  mfaRequired: false,
  passwordSet: true,
  forcePasswordReset: false,
  failedLoginCount: 0,
  lockedAt: null,
  suspendedAt: null,
  authProvider: null,
  oauthProviders: [],
  ssoOnly: false,
  emailVerified: true,
  invitedBy: null,
  contentOwnedCount: 4,
}

const STATS = {
  members: 1,
  pendingInvites: 0,
  admins: 0,
  seatsUsed: 1,
  seatLimit: null,
  seatsAvailable: null,
  emailConfigured: true,
}

const { cmsApi } = vi.hoisted(() => ({ cmsApi: vi.fn() }))
vi.mock('../../lib/api.js', () => ({ cmsApi }))

cmsApi.mockImplementation(async (endpoint?: string) => {
  if (!endpoint) return { data: null, status: 200 }
  if (endpoint === '/invites') return { data: [], status: 200 }
  if (endpoint === '/users/stats') return { data: STATS, status: 200 }
  if (endpoint === '/access-review') return { data: [], status: 200 }
  if (endpoint.startsWith('/users/u1')) return { data: DETAIL, status: 200 }
  if (endpoint === '/users' || endpoint.startsWith('/users?'))
    return { data: [MEMBER], status: 200 }
  return { data: null, status: 200 }
})

const { Users } = await import('../../views/Users.js')

describe('Users ?selected= deep link', () => {
  beforeEach(() => cmsApi.mockClear())

  it('opens the detail drawer for the selected member once the list loads', async () => {
    render(<Users currentPath="/users?selected=u1" />)

    // "Content owned" only renders inside the detail drawer's overview tab.
    expect(await screen.findByText('Content owned')).toBeTruthy()
    expect(cmsApi.mock.calls.some(([endpoint]) => String(endpoint).startsWith('/users/u1'))).toBe(
      true,
    )
  })

  it('ignores a selected id that matches no member', async () => {
    render(<Users currentPath="/users?selected=does-not-exist" />)

    // List renders normally…
    expect(await screen.findByText('priya@actuatemedia.com')).toBeTruthy()
    // …but no drawer opens and no detail fetch is issued.
    expect(screen.queryByText('Content owned')).toBeNull()
    expect(
      cmsApi.mock.calls.some(([endpoint]) => String(endpoint).includes('/users/does-not-exist')),
    ).toBe(false)
  })

  it('renders without a drawer when there is no query at all', async () => {
    render(<Users currentPath="/users" />)

    expect(await screen.findByText('priya@actuatemedia.com')).toBeTruthy()
    expect(screen.queryByText('Content owned')).toBeNull()
  })
})
