/**
 * (auth-layout: loading, login URL mutate when !role, skip mutate when role set).
 * Source: `@/share/components/full-page/auth-layout`.
 */
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'

const mockMutate = jest.fn()

jest.mock('next-intl', () => ({
  useLocale: () => 'vi',
}))

const mockUseAuth = jest.fn()
jest.mock('@/providers/auth-provider', () => ({
  useAuth: () => mockUseAuth(),
}))

jest.mock('@/share/components/full-page/loading', () => ({
  __esModule: true,
  default: () => <div data-testid="loading-page">LoadingPage</div>,
}))

jest.mock('@/share/layout/end-user/header/hook', () => ({
  useGetUrlLoginMutation: () => ({
    mutate: mockMutate,
  }),
}))

describe('[locale]/(end-user)/api-products/[id]/application/layout.tsx (AuthLayout)', () => {
  const CHILD_TEXT = 'Application children'

  beforeEach(() => {
    jest.clearAllMocks()
  })

  describe('loading branch', () => {
    it('renders LoadingPage only', async () => {
      mockUseAuth.mockReturnValue({ isLoading: true, authInfo: null })
      const { default: ApplicationLayout } = await import('../layout')

      render(
        <ApplicationLayout>
          <div>{CHILD_TEXT}</div>
        </ApplicationLayout>
      )

      expect(screen.getByTestId('loading-page')).toBeInTheDocument()
      expect(screen.queryByText(CHILD_TEXT)).not.toBeInTheDocument()
    })
  })

  describe('mutate login URL when !authInfo?.role', () => {
    it('calls mutate once for guest (no authInfo)', async () => {
      mockUseAuth.mockReturnValue({ isLoading: false, authInfo: null })
      const { default: ApplicationLayout } = await import('../layout')

      render(
        <ApplicationLayout>
          <div>{CHILD_TEXT}</div>
        </ApplicationLayout>
      )

      expect(screen.getByText(CHILD_TEXT)).toBeInTheDocument()
      await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1))
    })

    it('calls mutate when auth exists but role is missing', async () => {
      mockUseAuth.mockReturnValue({
        isLoading: false,
        authInfo: { token: 't' },
      })
      const { default: ApplicationLayout } = await import('../layout')

      render(
        <ApplicationLayout>
          <div>{CHILD_TEXT}</div>
        </ApplicationLayout>
      )

      await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1))
    })
  })

  describe('authenticated with role', () => {
    it('does not call mutate when authInfo.role is set', async () => {
      mockUseAuth.mockReturnValue({
        isLoading: false,
        authInfo: { role: 'user', token: 't' },
      })
      const { default: ApplicationLayout } = await import('../layout')

      render(
        <ApplicationLayout>
          <div>{CHILD_TEXT}</div>
        </ApplicationLayout>
      )

      expect(screen.getByText(CHILD_TEXT)).toBeInTheDocument()
      await waitFor(() =>
        expect(mockMutate).not.toHaveBeenCalled()
      )
    })
  })
})
