/**
 * Epic 1: Authentication & User Management
 * Component Test: Navigation
 * 
 * Tests the navigation component for proper display based on session state
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import Navigation from '@/components/Navigation'

// Mock the SessionProvider
vi.mock('@/components/SessionProvider', () => ({
  useSession: vi.fn(),
}))

// Mock the auth-client
vi.mock('@/lib/auth-client', () => ({
  authClient: {
    signOut: vi.fn(),
  },
}))

// Mock fetch for role API call
global.fetch = vi.fn()

import { useSession } from '@/components/SessionProvider'

describe('Epic 1: Navigation Component', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.mocked(global.fetch).mockImplementation(async (url) => {
      if (url?.toString().includes('/api/users/')) {
        return new Response(JSON.stringify({ role: 'player' }), {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        })
      }
      return new Response(JSON.stringify({}), { status: 200 })
    })
  })

  afterEach(() => {
    vi.restoreAllMocks()
  })

  it('renders the logo and basic links when not logged in', () => {
    vi.mocked(useSession).mockReturnValue({
      session: null,
      loading: false,
      refreshSession: vi.fn(),
    })

    render(<Navigation />)

    expect(screen.getByText('EuchreCamp')).toBeInTheDocument()
    expect(screen.getByText('Rankings')).toBeInTheDocument()
    expect(screen.getByText('Sign in')).toBeInTheDocument()
    expect(screen.getByText('Sign up')).toBeInTheDocument()
  })

  it('shows user menu when logged in', async () => {
    vi.mocked(useSession).mockReturnValue({
      session: {
        user: { 
          id: 'user-123',
          email: 'test@example.com', 
          name: 'Test User',
          role: 'player'
        },
        session: { token: 'abc123' },
      },
      loading: false,
      refreshSession: vi.fn(),
    })

    render(<Navigation />)

    await waitFor(() => {
      expect(screen.getByText('Test User')).toBeInTheDocument()
    })
    
    expect(screen.getByText('Sign out')).toBeInTheDocument()
    expect(screen.getByText('Tournaments')).toBeInTheDocument()
  })

  it('shows Tournaments link when logged in', async () => {
    vi.mocked(useSession).mockReturnValue({
      session: {
        user: { 
          id: 'user-123',
          email: 'test@example.com', 
          name: 'Test User',
          role: 'player'
        },
        session: { token: 'abc123' },
      },
      loading: false,
      refreshSession: vi.fn(),
    })

    render(<Navigation />)

    await waitFor(() => {
      expect(screen.getByText('Tournaments')).toBeInTheDocument()
    })
  })

  it('shows admin link for club_admin role', async () => {
    vi.mocked(useSession).mockReturnValue({
      session: {
        user: {
          id: 'admin-123',
          email: 'admin@example.com',
          name: 'Admin User',
          role: 'club_admin',
        },
        session: { token: 'abc123' },
      },
      loading: false,
      refreshSession: vi.fn(),
    })

    // Mock fetch to return club_admin role
    vi.mocked(global.fetch).mockImplementation(async (url) => {
      if (url?.toString().includes('/api/users/admin-123/role')) {
        return new Response(JSON.stringify({ role: 'club_admin' }), {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        })
      }
      return new Response(JSON.stringify({}), { status: 200 })
    })

    render(<Navigation />)

    await waitFor(() => {
      expect(screen.getByText('Admin')).toBeInTheDocument()
    }, { timeout: 3000 })
    expect(screen.getByText('Tournaments')).toBeInTheDocument()
  })

  it('hides admin link for non-admin users', async () => {
    vi.mocked(useSession).mockReturnValue({
      session: {
        user: {
          id: 'player-123',
          email: 'player@example.com',
          name: 'Player User',
          role: 'player',
        },
        session: { token: 'abc123' },
      },
      loading: false,
      refreshSession: vi.fn(),
    })

    // Mock fetch to return player role (already set in beforeEach, but explicit here)
    vi.mocked(global.fetch).mockImplementation(async (url) => {
      if (url?.toString().includes('/api/users/')) {
        return {
          json: () => Promise.resolve({ role: 'player' }),
        } as Response
      }
      return {
        json: () => Promise.resolve({}),
      } as Response
    })

    render(<Navigation />)

    await waitFor(() => {
      expect(screen.getByText('Tournaments')).toBeInTheDocument()
    })
    expect(screen.queryByText('Admin')).not.toBeInTheDocument()
  })

  it('shows loading state', () => {
    vi.mocked(useSession).mockReturnValue({
      session: null,
      loading: true,
      refreshSession: vi.fn(),
    })

    render(<Navigation />)

    expect(screen.getByText('Loading...')).toBeInTheDocument()
  })
})
