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

import { ApplicationFormSection } from '@/spa/components/forms/ApplicationFormSection'

const viewport = vi.hoisted(() => ({ mobile: false }))
const cms = vi.hoisted(() => ({ activePhase: '0' }))

vi.mock('@/spa/hooks/useIsMobile', () => ({
  useIsMobile: () => viewport.mobile,
}))

vi.mock('@/spa/cmsRoute', () => ({
  useApplicationForm: () => undefined,
  useApplicationPhase: () => ({ activePhase: cms.activePhase }),
  useNewsletterForm: () => undefined,
}))

vi.mock('@/spa/components/forms/BewerbungsForm', () => ({
  default: () => <div>Application form</div>,
}))

vi.mock('@/spa/components/forms/NewsletterInterestForm', () => ({
  NewsletterInterestForm: () => <div>Newsletter form</div>,
}))

vi.mock('@/spa/components/ui/UnoptimizedImage', () => ({
  default: ({ alt }: { alt: string }) => <div role="img" aria-label={alt} />,
}))

describe('shared application form layout', () => {
  beforeEach(() => {
    viewport.mobile = false
    cms.activePhase = '0'
  })

  afterEach(() => cleanup())

  it('widens only the homepage blue panel to a five-to-seven desktop split', () => {
    render(<ApplicationFormSection source="homepage" />)

    const layout = screen.getByTestId('application-form-layout')
    expect(layout.getAttribute('data-source')).toBe('homepage')
    expect(layout.style.gridTemplateColumns).toBe('5fr 1px 7fr')
  })

  it('keeps the Teilnahme desktop split unchanged', () => {
    render(<ApplicationFormSection source="participation" />)

    const layout = screen.getByTestId('application-form-layout')
    expect(layout.getAttribute('data-source')).toBe('participation')
    expect(layout.style.gridTemplateColumns).toBe('4fr 1px 8fr')
  })

  it('preserves the shared mobile stack for both sources', () => {
    viewport.mobile = true

    const { rerender } = render(<ApplicationFormSection source="homepage" />)
    expect(screen.getByTestId('application-form-layout').style.gridTemplateColumns).toBe('1fr')

    rerender(<ApplicationFormSection source="participation" />)
    expect(screen.getByTestId('application-form-layout').style.gridTemplateColumns).toBe('1fr')
  })

  it('keeps the homepage ratio across application and newsletter phases', () => {
    const { rerender } = render(<ApplicationFormSection source="homepage" />)
    expect(screen.getByText('Application form')).toBeTruthy()
    expect(screen.getByTestId('application-form-layout').style.gridTemplateColumns).toBe(
      '5fr 1px 7fr',
    )

    cms.activePhase = '1'
    rerender(<ApplicationFormSection source="homepage" />)

    expect(screen.getByText('Newsletter form')).toBeTruthy()
    expect(screen.getByTestId('application-form-layout').style.gridTemplateColumns).toBe(
      '5fr 1px 7fr',
    )
  })
})
