/**
 * Tests de renderizado condicional en LibraryPage según el rol del usuario.
 * Verifica que el botón "Importar BPMN" y el panel de grupos se muestran
 * solo para roles internos (platform_admin / member).
 */
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import React from 'react'

// ─── Referencias mutables para controlar el rol durante los tests ─────────────

const { authUserRef, libStoreRef } = vi.hoisted(() => {
  const authUserRef = {
    current: {
      id: 'user-1',
      email: 'test@test.com',
      name: 'Test User',
      platformRole: 'platform_admin' as string,
    },
    isProfileLoaded: true,
  }
  const sampleProcess = {
    id: 'proc-1',
    name: 'Proceso de prueba',
    ownerId: 'user-1',
    ownerName: 'Test User',
    updaterName: 'Test User',
    groupId: null,
    tags: [],
    updatedAt: Date.now(),
    bpmnXml: '',
    annualFrequency: 1,
    analysisHorizonYears: 3,
    automationInvestment: 0,
    currency: 'USD',
    clientName: null,
    overhead: 0,
    isShared: false,
    orgId: null,
  }
  const sampleGroup = {
    id: 'grp-1',
    processId: 'proc-1',
    name: 'Banca',
    createdAt: Date.now(),
    ownerId: 'user-1',
  }
  const libStoreRef = {
    groups: [sampleGroup],
    processes: [sampleProcess],
    settings: { groupLabel: 'Área', groupLabelPlural: 'Áreas', currency: 'USD' },
    isLoading: false,
    error: null,
    load: vi.fn(),
    createGroup: vi.fn(),
    getAllTags: vi.fn().mockReturnValue([]),
    getLatestSimulation: vi.fn().mockResolvedValue(null),
    deleteProcess: vi.fn(),
  }
  return { authUserRef, libStoreRef }
})

vi.mock('@/auth/AuthContext', () => ({
  useAuth: () => ({ user: authUserRef.current, isProfileLoaded: authUserRef.isProfileLoaded }),
}))

vi.mock('@/store/library-store', () => ({
  useLibraryStore: (selector?: (s: typeof libStoreRef) => unknown) =>
    selector ? selector(libStoreRef) : libStoreRef,
}))

vi.mock('@/components/AppHeader', () => ({ AppHeader: () => null }))

vi.mock('@tanstack/react-router', () => ({
  useNavigate: () => vi.fn(),
  useRouterState: () => ({ location: { search: '' } }),
  useLocation: () => ({ search: '' }),
  Link: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}))

vi.mock('@/components/ui/use-toast', () => ({
  useToast: () => ({ message: null, show: vi.fn() }),
}))

// Importar después de los mocks
import { LibraryPage } from '@/features/library/LibraryPage'

// ─── Tests ────────────────────────────────────────────────────────────────────

describe('LibraryPage — visibilidad de controles según rol', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    libStoreRef.load = vi.fn()
    libStoreRef.getAllTags = vi.fn().mockReturnValue([])
    libStoreRef.getLatestSimulation = vi.fn().mockResolvedValue(null)
    authUserRef.isProfileLoaded = true
  })

  describe('isProfileLoaded = false (sync en curso)', () => {
    beforeEach(() => {
      authUserRef.current = { ...authUserRef.current, platformRole: 'platform_admin' }
      authUserRef.isProfileLoaded = false
    })

    it('NO muestra el botón "Importar BPMN" mientras el perfil no está cargado', () => {
      render(<LibraryPage />)
      expect(screen.queryByText('Importar BPMN')).not.toBeInTheDocument()
    })

    it('NO muestra el panel de grupos mientras el perfil no está cargado', () => {
      render(<LibraryPage />)
      expect(screen.queryByTestId('groups-header')).not.toBeInTheDocument()
    })
  })

  describe('platform_admin', () => {
    beforeEach(() => {
      authUserRef.current = { ...authUserRef.current, platformRole: 'platform_admin' }
    })

    it('muestra el botón "Importar BPMN"', () => {
      render(<LibraryPage />)
      expect(screen.getByText('Importar BPMN')).toBeInTheDocument()
    })

    it('muestra el panel de grupos (header de sección)', () => {
      render(<LibraryPage />)
      expect(screen.getByTestId('groups-header')).toBeInTheDocument()
    })
  })

  describe('client_editor', () => {
    beforeEach(() => {
      authUserRef.current = { ...authUserRef.current, platformRole: 'client_editor' }
    })

    it('NO muestra el botón "Importar BPMN"', () => {
      render(<LibraryPage />)
      expect(screen.queryByText('Importar BPMN')).not.toBeInTheDocument()
    })

    it('NO muestra el panel de grupos', () => {
      render(<LibraryPage />)
      expect(screen.queryByTestId('groups-header')).not.toBeInTheDocument()
    })
  })

  describe('client_viewer', () => {
    beforeEach(() => {
      authUserRef.current = { ...authUserRef.current, platformRole: 'client_viewer' }
    })

    it('NO muestra el botón "Importar BPMN"', () => {
      render(<LibraryPage />)
      expect(screen.queryByText('Importar BPMN')).not.toBeInTheDocument()
    })

    it('NO muestra el panel de grupos', () => {
      render(<LibraryPage />)
      expect(screen.queryByTestId('groups-header')).not.toBeInTheDocument()
    })
  })
})
