import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import StudioGroupMembers from '../StudioGroupMembers'

const { routerMock } = vi.hoisted(() => ({
  routerMock: {
    post: vi.fn(),
    patch: vi.fn(),
    delete: vi.fn(),
  },
}))

let pageMock = { props: {} }

vi.mock('@inertiajs/react', () => ({
  usePage: () => pageMock,
  router: routerMock,
}))

vi.mock('../../../Layouts/StudioLayout', () => ({
  default: ({ children }) => <div>{children}</div>,
}))

describe('StudioGroupMembers permissions', () => {
  afterEach(() => {
    cleanup()
    vi.clearAllMocks()
  })

  it('shows management controls for owners and admins', () => {
    pageMock = {
      props: {
        title: 'Members',
        description: 'Manage members',
        canManageMembers: true,
        endpoints: {
          invite: '/studio/groups/warp/members',
          invitations: '/studio/groups/warp/invitations',
          updatePattern: '/studio/groups/warp/members/__MEMBER__',
          transferPattern: '/studio/groups/warp/members/__MEMBER__/transfer',
          deletePattern: '/studio/groups/warp/members/__MEMBER__',
        },
        members: [
          {
            id: 1,
            role: 'editor',
            role_label: 'editor',
            status: 'active',
            can_transfer: true,
            can_revoke: true,
            user: { name: 'Editor User', username: 'editor-user', avatar_url: null },
          },
        ],
      },
    }

    render(<StudioGroupMembers />)

    expect(screen.getByText('Invite member')).not.toBeNull()
    expect(screen.getByRole('link', { name: /manage invitations/i })).not.toBeNull()
    expect(screen.getByPlaceholderText(/name, username, or role/i)).not.toBeNull()
    expect(screen.getByRole('button', { name: /transfer/i })).not.toBeNull()
    expect(screen.getByRole('button', { name: /remove/i })).not.toBeNull()
  })

  it('hides management controls for non-managing members', () => {
    pageMock = {
      props: {
        title: 'Members',
        description: 'Manage members',
        canManageMembers: false,
        endpoints: null,
        members: [
          {
            id: 1,
            role: 'editor',
            role_label: 'editor',
            status: 'active',
            can_transfer: false,
            can_revoke: false,
            user: { name: 'Editor User', username: 'editor-user', avatar_url: null },
          },
        ],
      },
    }

    render(<StudioGroupMembers />)

    expect(screen.queryByText('Invite member')).toBeNull()
    expect(screen.queryByRole('link', { name: /manage invitations/i })).toBeNull()
    expect(screen.queryByRole('button', { name: /transfer/i })).toBeNull()
    expect(screen.queryByRole('button', { name: /remove/i })).toBeNull()
    expect(screen.getByText('editor')).not.toBeNull()
  })
})