import React, { isValidElement } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const preferenceState = vi.hoisted(() => ({ language: 'en' as 'en' | 'fr' | 'ar' }))

vi.mock('@/components/CarplaceShell', () => ({
  useCarplacePreferences: () => ({ language: preferenceState.language, theme: 'light' }),
}))

import FooterContentPage from './FooterContentPage'

function collectText(node: unknown): string[] {
  if (node === null || node === undefined || typeof node === 'boolean') return []
  if (typeof node === 'string' || typeof node === 'number') return [String(node)]
  if (Array.isArray(node)) return node.flatMap(collectText)
  if (isValidElement<{ children?: React.ReactNode }>(node)) return collectText(node.props.children)
  return []
}

function collectElements(node: unknown): React.ReactElement<Record<string, unknown>>[] {
  if (node === null || node === undefined || typeof node === 'boolean') return []
  if (Array.isArray(node)) return node.flatMap(collectElements)
  if (!isValidElement<{ children?: React.ReactNode }>(node)) return []
  return [node, ...collectElements(node.props.children)]
}

describe('FooterContentPage', () => {
  beforeEach(() => {
    preferenceState.language = 'en'
  })

  it('uses the current carplace language when no forced language is provided', () => {
    preferenceState.language = 'fr'
    const page = FooterContentPage({ slug: 'contact-sales' })
    const text = collectText(page).join(' ')

    expect(text).toContain('Informations du pied de page')
    expect(text).toContain('Besoin de plus de détails')
  })

  it('lets static app policy pages force their own locale', () => {
    preferenceState.language = 'en'
    const page = FooterContentPage({ slug: 'terms-of-service', forcedLanguage: 'fr' })
    const text = collectText(page).join(' ')

    expect(text).toContain('Informations du pied de page')
    expect(text).not.toContain('Footer information')
  })

  it('marks Arabic content as right-aligned', () => {
    const page = FooterContentPage({ slug: 'privacy-policy', forcedLanguage: 'ar' })
    const elements = collectElements(page)

    expect(elements.some((element) => String(element.props.className ?? '').includes('text-right'))).toBe(true)
  })

  it('turns plain URLs embedded in policy paragraphs into safe anchors', () => {
    const page = FooterContentPage({ slug: 'privacy-policy', forcedLanguage: 'en' })
    const links = collectElements(page).filter((element) => element.type === 'a')

    expect(links.some((link) => String(link.props.href).startsWith('https://'))).toBe(true)
    expect(links.every((link) => link.props.href === collectText(link).join(''))).toBe(true)
  })
})
