'use client'
import React, { useEffect, useRef, useState } from 'react'
import { Text } from '@/components/ui'
import { Lottie } from 'lottie-react'
import backgroundAnimation from '@/app/assets/Image/Hero_BG_Animation_1.json'
import { motion } from 'motion/react'
const TITLE_TYPING_SPEED_MS = 60
interface HeroSectionProps {
  title: string
  description: string
}
const TypingTitle = ({ html }: { html: string }) => {
  const plain = html.replace(/<[^>]*>/g, '')
  const [index, setIndex] = useState(0)
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  useEffect(() => {
    if (index >= plain.length) return
    timerRef.current = setTimeout(() => setIndex((currentIndex) => currentIndex + 1), TITLE_TYPING_SPEED_MS)
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current)
    }
  }, [index, plain.length])
  if (index >= plain.length) return <span dangerouslySetInnerHTML={{ __html: html }} />
  return (
    <span>
      {plain.slice(0, index)}
      <span className='animate-pulse opacity-70'>|</span>
    </span>
  )
}
const TypingTitleWrapper = ({ html }: { html: string }) => {
  const [key, setKey] = useState(0)
  useEffect(() => {
    const restartTyping = () => setKey((currentKey) => currentKey + 1)
    restartTyping()
    window.addEventListener('pageshow', restartTyping)
    return () => {
      window.removeEventListener('pageshow', restartTyping)
    }
  }, [html])
  return <TypingTitle key={key} html={html} />
}
export const HeroSection = ({ title, description, }: HeroSectionProps) => {
  return (
    <div className=' sticky top-0'>
      <div className='flex-center  isolate bg-primary px-5 lg:px-[50px] overflow-hidden py-20 lg:py-0 h-[calc(100vh-70px)]'>
        <div aria-hidden='true' className='pointer-events-none absolute left-0 right-0 -top-50 -z-10 h-full w-full overflow-hidden'>
          <Lottie src={backgroundAnimation} autoplay loop className='h-full w-full' />
        </div>
        <div className='space-y-5 lg:space-y-[30px]'>
          <Text size='h1' className='leading-[50px] text-white max-w-[65rem] text-center mx-auto  2xl:leading-[90px] uppercase'>
            <TypingTitleWrapper html={title.replace('<span>', '<span class="gradient-text">')} />
          </Text>
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.7, ease: 'easeOut', delay: 0.3 }}
          >
            <Text size='normal' className='text-white max-w-[47rem] min-[1900px]:max-w-[63rem] text-center mx-auto ' textKey={description} />
          </motion.div>
        </div>
      </div>
    </div>
  )
}
