'use client'

import Image from 'next/image'
import { Text } from '@/components/ui'
import type { SolutionsFields } from '@/types/solutions'
import backgroundAnimation from '@/app/assets/Image/Hero_BG_Animation_1.json'
import { Lottie } from 'lottie-react'
import { motion } from 'motion/react'
import { useEffect, useRef, useState } from 'react'

const TITLE_TYPING_SPEED_MS = 60

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(i => i + 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='opacity-70 animate-pulse'>|</span>
        </span>
    )
}

const TypingTitleWrapper = ({ html }: { html: string }) => {
    const [key, setKey] = useState(0)

    useEffect(() => {
        const restartTyping = () => setKey(k => k + 1)

        // Force remount after hydration and browser page restore so typing starts from 0.
        restartTyping()
        window.addEventListener('pageshow', restartTyping)

        return () => {
            window.removeEventListener('pageshow', restartTyping)
        }
    }, [html])

    return <TypingTitle key={key} html={html} />
}

export const HeroSection = ({ fields }: { fields: SolutionsFields }) => {
    return (
        <div className='sticky top-0'>
            <div className='flex-center relative isolate bg-primary px-5 lg:px-[50px] overflow-hidden py-30 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>
                    {fields.banner_cards_image.url && (
                        <motion.div
                            className='absolute left-0 top-0 '
                            animate={{ y: [0, -18, 0] }}
                            transition={{ duration: 4, repeat: Infinity, ease: 'easeInOut' }}
                        >
                            <Image
                                src={fields.banner_cards_image.url}
                                alt={fields.banner_cards_image.alt || ''}
                                width={491}
                                height={571}
                                priority
                                className='h-[280px] md:h-auto w-[200px] md:w-[340px] xl:w-[420px] 2xl:w-[491px]'
                            />
                        </motion.div>
                    )}
                    {fields.banner_bg_image_2?.url && (
                        <motion.div
                            className='pointer-events-none absolute bottom-0 right-0 '
                            animate={{ y: [0, 18, 0] }}
                            transition={{ duration: 4, repeat: Infinity, ease: 'easeInOut' }}
                        >
                            <Image
                                src={fields.banner_bg_image_2.url}
                                alt={fields.banner_bg_image_2.alt || ''}
                                width={474}
                                height={626}
                                className='h-[280px] md:h-auto w-[200px] md:w-[330px] xl:w-[405px] 2xl:w-[474px]'
                            />
                        </motion.div>
                    )}
                    <div className='space-y-5 lg:space-y-[30px] relative z-10'>
                        <Text size='h1' className=' leading-[50px] text-white max-w-[45rem] text-center mx-auto 2xl:leading-[90px] uppercase'>
                            <TypingTitleWrapper html={fields.banner_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={fields.banner_description}
                            />
                        </motion.div>
                    </div>
                </div>
            </div>
        </div>
    )
}
