import { readFileSync } from 'node:fs'
import { join } from 'node:path'

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

import type { SpaApplicationPhaseData } from '@/spa/applicationPhase'
import { StatusSlider } from '@/spa/pages/Home'

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

vi.mock('next/navigation', () => ({
  usePathname: () => '/',
  useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}))

const applicationPhase = (headline: string): SpaApplicationPhaseData => ({
  activePhase: '0',
  noActionLabel: 'No action',
  successApplicationsLabel: 'Applications',
  successWinnersLabel: 'Winners',
  phases: [
    {
      num: '03',
      tag: 'Complete',
      phase: 'Award ceremony',
      headline,
      body: 'CMS body copy',
      accent: '#EFBF04',
      bg: '#111D55',
      meta: 'CMS meta copy',
      successApplications: '247',
      successWinners: '3',
    },
  ],
})

describe('homepage application-phase headline', () => {
  afterEach(() => cleanup())

  it('renders each explicit CMS newline as an intentional line break', () => {
    render(<StatusSlider data={applicationPhase('Ein weiteres\nerfolgreiches Jahr')} />)

    const headline = screen.getByTestId('phase-headline')
    expect(headline.textContent).toBe('Ein weitereserfolgreiches Jahr')
    expect(headline.querySelectorAll('br')).toHaveLength(1)
    expect(headline.childNodes[0]?.textContent).toBe('Ein weiteres')
    expect(headline.childNodes[2]?.textContent).toBe('erfolgreiches Jahr')
  })

  it('keeps arbitrary CMS-edited copy authoritative and naturally wrappable', () => {
    const editedHeadline =
      'Eine redaktionell geänderte Überschrift mit zusätzlichem Inhalt für schmale Ansichten'

    render(<StatusSlider data={applicationPhase(editedHeadline)} />)

    const headline = screen.getByTestId('phase-headline')
    expect(headline.textContent).toBe(editedHeadline)
    expect(headline.querySelector('br')).toBeNull()
    expect(headline.classList.contains('type-page-title')).toBe(true)
    expect(screen.getByTestId('phase-section').style.height).toBe('auto')
    expect(screen.getByTestId('phase-section').style.minHeight).toBe('480px')
  })

  it('keeps the requested copy out of the homepage component', () => {
    const source = readFileSync(join(process.cwd(), 'src/spa/pages/Home.tsx'), 'utf8')

    expect(source).not.toContain('Ein weiteres')
    expect(source).not.toContain('erfolgreiches Jahr')
  })
})
