import { useI18n } from '@/locales/client'
import { News } from '@/payload-types'

type RichTextNode = {
  text?: string
  children?: RichTextNode[]
  [key: string]: any
}

export const getReadingTime = (contents: News['contents'], t: ReturnType<typeof useI18n>): string => {
  if (!contents || contents.length === 0) return '1 ' + t('blog.readingTime')

  function extractText(nodes: RichTextNode[]): string {
    return nodes
      .map((node) => {
        const childrenText = node.children ? extractText(node.children) : ''
        return (node.text || '') + childrenText
      })
      .join(' ')
  }

  const allText = contents
    .map((item) => {
      const children = item?.content?.root?.children ?? []
      return extractText(children)
    })
    .join(' ')

  const wordCount = allText.trim().split(/\s+/).filter(Boolean).length
  const readingMinutes = Math.max(1, Math.ceil(wordCount / 200))

  return `${readingMinutes} ${readingMinutes === 1 ? t('blog.readingTime') : t('blog.readingTimePlural')}`
}
