/**
 * (loading vs ready shell, session contract).
 */
import React from 'react'
import { render, screen } from '@testing-library/react'

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('@/providers/auth-session-provider', () => ({
  AuthSessionProvider: ({
    children,
    authSession,
  }: {
    children: React.ReactNode
    authSession: unknown
  }) => (
    <div
      data-testid="auth-session-provider"
      data-auth-session={JSON.stringify(authSession)}
    >
      {children}
    </div>
  ),
}))

jest.mock('@/share/layout/end-user/header', () => ({
  __esModule: true,
  default: () => <div data-testid="eu-header">EUHeader</div>,
}))

jest.mock('@/share/layout/end-user/footer', () => ({
  __esModule: true,
  default: () => <div data-testid="eu-footer">EUFooter</div>,
}))

describe('[locale]/(end-user)/layout.tsx — EndUserLayout', () => {
  const CHILD_TEXT = 'End user children'

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

  describe('loading branch', () => {
    it('shows LoadingPage only (no header/footer shell)', async () => {
      mockUseAuth.mockReturnValue({ isLoading: true, authInfo: null })
      const { default: EndUserLayout } = await import('../layout')

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

      expect(screen.getByTestId('loading-page')).toBeInTheDocument()
      expect(screen.queryByTestId('eu-header')).not.toBeInTheDocument()
      expect(screen.queryByTestId('eu-footer')).not.toBeInTheDocument()
      expect(screen.queryByText(CHILD_TEXT)).not.toBeInTheDocument()
    })
  })

  describe('ready branch', () => {
    it.each([
      {
        label: 'minimal auth payload',
        authInfo: { userId: 'user-1' },
      },
      {
        label: 'null guest (still renders shell for public EU routes)',
        authInfo: null,
      },
    ])('wraps children + header/footer when not loading ($label)', async ({
      authInfo,
    }) => {
      mockUseAuth.mockReturnValue({ isLoading: false, authInfo })
      const { default: EndUserLayout } = await import('../layout')

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

      const provider = screen.getByTestId('auth-session-provider')
      expect(provider).toHaveAttribute(
        'data-auth-session',
        JSON.stringify(authInfo)
      )

      expect(screen.getByTestId('eu-header')).toBeInTheDocument()
      expect(screen.getByTestId('eu-footer')).toBeInTheDocument()
      expect(screen.getByText(CHILD_TEXT)).toBeInTheDocument()
    })
  })
})
