/**
 * (same auth-layout contract as application segment).
 */
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'

const mutateFn = jest.fn()

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

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

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

import TryoutLayout from '../layout'

describe('[locale]/(end-user)/.../tryout/layout.tsx (AuthLayout)', () => {
  const { useAuth } = jest.requireMock('@/providers/auth-provider') as {
    useAuth: jest.Mock
  }

  beforeEach(() => {
    mutateFn.mockClear()
    useAuth.mockReset()
  })

  describe('loading', () => {
    it('renders LoadingPage when isLoading', () => {
      useAuth.mockReturnValue({ isLoading: true, authInfo: null })
      render(
        <TryoutLayout>
          <div>child</div>
        </TryoutLayout>
      )
      expect(screen.getByTestId('loading-page')).toBeInTheDocument()
    })
  })

  describe('guest / incomplete session', () => {
    it('invokes mutate to resolve login URL when no role', async () => {
      useAuth.mockReturnValue({ isLoading: false, authInfo: null })
      render(
        <TryoutLayout>
          <span>c</span>
        </TryoutLayout>
      )
      expect(screen.getByText('c')).toBeInTheDocument()
      await waitFor(() => expect(mutateFn).toHaveBeenCalledTimes(1))
    })

    it('still invokes mutate when auth exists but lacks role', async () => {
      useAuth.mockReturnValue({ isLoading: false, authInfo: { token: 't' } })
      render(
        <TryoutLayout>
          <span>c</span>
        </TryoutLayout>
      )
      await waitFor(() => expect(mutateFn).toHaveBeenCalledTimes(1))
    })
  })

  describe('authenticated with role', () => {
    it('does not invoke mutate once role is populated', async () => {
      useAuth.mockReturnValue({
        isLoading: false,
        authInfo: { token: 't', role: 'user' },
      })
      render(
        <TryoutLayout>
          <span>c</span>
        </TryoutLayout>
      )
      expect(screen.getByText('c')).toBeInTheDocument()
      await waitFor(() => expect(mutateFn).not.toHaveBeenCalled())
    })
  })
})
