import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { Loading } from '@nutui/nutui-react-taro'
import { RichText, View } from '@tarojs/components'
import { getByCode } from '@/api/cms/cmsArticle'
import { wxParse } from '@/utils/common'

const Agreement = () => {
  const [loading, setLoading] = useState(true)
  const [content, setContent] = useState<string>('')

  const reload = async () => {
    try {
      Taro.hideTabBar()
    } catch (_) {
      // ignore (e.g. H5 / unsupported env)
    }

    try {
      const article = await getByCode('xieyi')
      setContent(article?.content ? wxParse(article.content) : '<p>暂无协议内容</p>')
    } catch (e) {
      // Keep UI usable even if CMS/API fails.
      // eslint-disable-next-line no-console
      console.error('load agreement failed', e)
      setContent('<p>协议内容加载失败</p>')
      Taro.showToast({ title: '协议加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    reload()
  }, [])

  if (loading) {
    return <Loading className={'px-2'}>加载中</Loading>
  }

  return (
    <>
      <View className={'content text-gray-700 text-sm p-4'}>
        <RichText nodes={content} />
      </View>
    </>
  )
}
export default Agreement
