'use client'
import { ArrowUpRightIcon } from '@/app/assets/svg/icon'
import { Button, Text } from '@/components/ui'
import { cn } from '@/lib/utils'
import Image from 'next/image'
import React, { useEffect, useRef } from 'react'
import backgroundAnimation from '@/app/assets/Image/Hero_BG_Animation_1.json'
import { Lottie } from 'lottie-react'
import { motion, useMotionValue, useScroll, useSpring, useTransform } from 'motion/react'
import type { AppDownloadLink, HomeImage } from '@/types/home'
import { useIsRtl } from '@/lib/use-is-rtl'
interface HeroSectionProps {
    title: string
    description: string
    buttonText: string
    buttonUrl: string
    mainImage: HomeImage
    transactionImage: HomeImage
    cardImage: HomeImage
    moneySavingImage: HomeImage
    qrImage: HomeImage
    downloadAppText: string
    appDownloadLinks: AppDownloadLink[]
}
const TitleHtml = ({ title }: { title: string }) => (
    <span dangerouslySetInnerHTML={{ __html: title.replace('<span>', '<span class="gradient-text">') }} />
)
const END_SCROLL_HOLD_DISTANCE = 200

const ActionButtons = ({ buttonText, buttonUrl, className }: { buttonText: string; buttonUrl: string; className?: string }) => (
    <div className={className}>
        <Button onClick={() => { window.location.href = buttonUrl }}>
            {buttonText}
            <ArrowUpRightIcon />
        </Button>
    </div>
)
const DownloadButtons = ({
    text,
    links,
    className,
}: {
    text: string
    links: AppDownloadLink[]
    className?: string
}) => (
    <div className={className}>
        <Text size='normal' textKey={text} className='text-secondary' />
        <div className='flex gap-[18px]'>
            {links.map(({ app_icon: icon, app_link: link }, index) => (
                <a
                    key={`${icon.id}-${index}`}
                    href={link || '#'}
                    target={link && link !== '#' ? '_blank' : undefined}
                    rel={link && link !== '#' ? 'noopener noreferrer' : undefined}
                    aria-label={icon.alt || text}
                    className='block shrink-0'
                >
                    <Image
                        src={icon.url}
                        alt={icon.alt || text}
                        width={icon.width}
                        height={icon.height}
                        className='h-[50px] w-[50px] object-contain'
                    />
                </a>
            ))}
        </div>
    </div>
)
export const HeroSection = ({
    title, description, buttonText, buttonUrl,
    mainImage, transactionImage, cardImage, moneySavingImage, qrImage,
    downloadAppText, appDownloadLinks
}: HeroSectionProps) => {
    const isRtl = useIsRtl()
    const sectionStartRef = useRef<HTMLDivElement>(null)
    const sectionRef = useRef<HTMLDivElement>(null)
    const mobileScrollRef = useRef<HTMLDivElement>(null)
    const animationDone = useRef(false)
    const touchStartRef = useRef<{ x: number; y: number } | null>(null)
    const progressFrameRef = useRef(0)
    const pendingDeltaRef = useRef(0)
    const endScrollHoldRef = useRef(0)
    const progress = useMotionValue(0)
    const sProgress = useSpring(progress, { stiffness: 50, damping: 18 })
    const titleY = useTransform(sProgress, [0, 1], ['0px', '-35vh'])
    const titleScale = useTransform(sProgress, [0, 1], [1, 0.52])
    const imagesOpacity = useTransform(sProgress, [0.2, 0.7], [0, 1])
    const menY = useTransform(sProgress, [0, 1], [300, 0])
    const topLeftX = useTransform(sProgress, [0, 1], [-600, 0])
    const bottomLeftX = useTransform(sProgress, [0, 1], [-600, 0])
    const bottomLeftY = useTransform(sProgress, [0, 1], [400, 0])
    const topRightX = useTransform(sProgress, [0, 1], [600, 0])
    const topRightY = useTransform(sProgress, [0, 1], [-400, 0])
    const bottomRightX = useTransform(sProgress, [0, 1], [600, 0])
    const bottomRightY = useTransform(sProgress, [0, 1], [400, 0])
    const { scrollYProgress: mobileProgress } = useScroll({
        target: mobileScrollRef,
        offset: ['start start', 'end end'],
    })
    const sMobileProgress = useSpring(mobileProgress, { stiffness: 55, damping: 20 })
    const mobileImagesOpacity = useTransform(sMobileProgress, [0.08, 0.55], [0, 1])
    const mobileMainY = useTransform(sMobileProgress, [0, 0.75], [220, 0])
    const mobileTopLeftX = useTransform(sMobileProgress, [0, 0.75], [-260, 0])
    const mobileBottomLeftX = useTransform(sMobileProgress, [0, 0.75], [-260, 0])
    const mobileBottomLeftY = useTransform(sMobileProgress, [0, 0.75], [170, 0])
    const mobileTopRightX = useTransform(sMobileProgress, [0, 0.75], [260, 0])
    const mobileTopRightY = useTransform(sMobileProgress, [0, 0.75], [-170, 0])
    const mobileBottomRightX = useTransform(sMobileProgress, [0, 0.75], [260, 0])
    const mobileBottomRightY = useTransform(sMobileProgress, [0, 0.75], [170, 0])
    useEffect(() => {
        const section = sectionRef.current
        const sectionStart = sectionStartRef.current
        if (!section || !sectionStart) return
        const isElementVisible = (element: HTMLElement) => {
            const styles = window.getComputedStyle(element)
            return styles.display !== 'none' && styles.visibility !== 'hidden'
        }
        const isCenteredInViewport = (target: HTMLElement, startTarget = target) => {
            if (!isElementVisible(target)) return false

            const sectionTop = startTarget.getBoundingClientRect().top + window.scrollY
            const sectionCenter = sectionTop + target.offsetHeight / 2
            const viewportCenter = window.scrollY + window.innerHeight / 2
            const centerTolerance = Math.min(80, window.innerHeight * 0.1)
            return Math.abs(sectionCenter - viewportCenter) <= centerTolerance
        }
        const isSectionCenteredInViewport = () => {
            return isCenteredInViewport(section, sectionStart)
        }
        const updateProgress = (deltaY: number) => {
            const goingDown = deltaY > 0
            const currentProgress = progress.get()

            if (goingDown) {
                if (animationDone.current) {
                    endScrollHoldRef.current = Math.max(0, endScrollHoldRef.current - Math.abs(deltaY))
                    return true
                }

                const next = Math.min(1, currentProgress + Math.min(Math.abs(deltaY) / 600, 0.12))
                progress.set(next)
                if (next >= 1) {
                    animationDone.current = true
                    endScrollHoldRef.current = END_SCROLL_HOLD_DISTANCE
                }
                return true
            }

            if (currentProgress === 0) return false

            animationDone.current = false
            endScrollHoldRef.current = 0
            progress.set(Math.max(0, currentProgress - Math.min(Math.abs(deltaY) / 600, 0.12)))
            return true
        }

        const canUpdateProgress = (deltaY: number) => {
            if (deltaY > 0) return !animationDone.current || endScrollHoldRef.current > 0
            return progress.get() > 0
        }

        const scheduleProgressUpdate = (deltaY: number) => {
            pendingDeltaRef.current += deltaY
            if (progressFrameRef.current) return

            progressFrameRef.current = requestAnimationFrame(() => {
                const nextDelta = pendingDeltaRef.current
                pendingDeltaRef.current = 0
                progressFrameRef.current = 0

                if (nextDelta !== 0) {
                    updateProgress(nextDelta)
                }
            })
        }

        const handleWheel = (e: WheelEvent) => {
            if (!isSectionCenteredInViewport()) return
            if (canUpdateProgress(e.deltaY)) {
                e.preventDefault()
                scheduleProgressUpdate(e.deltaY)
            }
        }

        const handleTouchStart = (e: TouchEvent) => {
            const touch = e.touches[0]
            touchStartRef.current = touch ? { x: touch.clientX, y: touch.clientY } : null
        }

        const handleTouchMove = (e: TouchEvent) => {
            if (!isSectionCenteredInViewport()) return

            const touch = e.touches[0]
            const start = touchStartRef.current
            if (!touch || !start) return

            const deltaX = start.x - touch.clientX
            const deltaY = start.y - touch.clientY
            if (Math.abs(deltaY) < 8 || Math.abs(deltaY) < Math.abs(deltaX)) return

            if (canUpdateProgress(deltaY)) {
                e.preventDefault()
                scheduleProgressUpdate(deltaY)
                touchStartRef.current = { x: touch.clientX, y: touch.clientY }
            }
        }

        const handleTouchEnd = () => {
            touchStartRef.current = null
        }

        window.addEventListener('wheel', handleWheel, { passive: false })
        section.addEventListener('touchstart', handleTouchStart, { passive: true })
        section.addEventListener('touchmove', handleTouchMove, { passive: false })
        section.addEventListener('touchend', handleTouchEnd, { passive: true })
        section.addEventListener('touchcancel', handleTouchEnd, { passive: true })

        return () => {
            cancelAnimationFrame(progressFrameRef.current)
            window.removeEventListener('wheel', handleWheel)
            section.removeEventListener('touchstart', handleTouchStart)
            section.removeEventListener('touchmove', handleTouchMove)
            section.removeEventListener('touchend', handleTouchEnd)
            section.removeEventListener('touchcancel', handleTouchEnd)
        }
    }, [progress])
    return (
        <>
            <div ref={sectionStartRef} aria-hidden='true' className='hidden h-0 lg:block ' />
            <div ref={sectionRef} className='relative isolate hidden h-[calc(100dvh-70px)] min-h-[500px] overflow-hidden bg-primary px-[25px] [container-type:size] lg:sticky lg:top-0 lg:block  [@media(min-width:1700px)]:px-[50px]'>
                <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>
                {/* Scrolled state */}
                <div className='relative h-full'>
                    <div className='absolute inset-0 flex items-center justify-center pointer-events-none'>
                        <motion.div style={{ y: titleY, scale: titleScale }} className='w-full px-[clamp(24px,3vw,50px)]'>
                            <Text size='h1' fontWeight={600} className='mx-auto max-w-[80rem] text-center text-[clamp(40px,8cqh,75px)] leading-[1.12] text-white uppercase'>
                                <TitleHtml title={title} />
                            </Text>
                        </motion.div>
                    </div>
                    <motion.div style={{ opacity: imagesOpacity }} className='absolute bottom-0 left-1/2 w-[clamp(360px,calc(75cqh-112px),529px)] max-w-[42vw] -translate-x-1/2'>
                        <div className='relative z-20 w-full'>
                            <motion.div style={{ y: menY }}>
                                <Image src={mainImage.url} alt={mainImage.alt} width={mainImage.width} height={mainImage.height} className='h-auto w-full object-contain' />
                            </motion.div>
                            <motion.div className='absolute top-[32%] -left-[19%] -z-10 w-[42%]' style={{ x: topLeftX }}>
                                <Image src={transactionImage.url} alt={transactionImage.alt} width={transactionImage.width} height={transactionImage.height} className='h-auto w-full' />
                            </motion.div>
                            <motion.div className='absolute bottom-[13%] -left-[18%] z-50 w-[30%]' style={{ x: bottomLeftX, y: bottomLeftY }}>
                                <Image src={moneySavingImage.url} alt={moneySavingImage.alt} width={moneySavingImage.width} height={moneySavingImage.height} className='h-auto w-full' />
                            </motion.div>
                            <motion.div className='absolute top-[15%] -right-[17%] -z-10 w-[51%]' style={{ x: topRightX, y: topRightY }}>
                                <Image src={cardImage.url} alt={cardImage.alt} width={cardImage.width} height={cardImage.height} className='h-auto w-full rounded-[clamp(14px,1.4vw,21.59px)] border border-[#FFFFFF80] shadow-[0px_27.76px_55.52px_-13.33px_#00000040]' />
                            </motion.div>
                            <motion.div className='absolute right-[-8%] bottom-[8%] w-[30%]' style={{ x: bottomRightX, y: bottomRightY }}>
                                <Image src={qrImage.url} alt={qrImage.alt} width={qrImage.width} height={qrImage.height} className='h-auto w-full' />
                            </motion.div>
                        </div>
                    </motion.div>
                    <div className={cn('absolute bottom-[30px]', isRtl ? 'right-0' : 'left-0')}>
                        <Button onClick={() => { window.location.href = buttonUrl }}>
                            {buttonText}
                            <ArrowUpRightIcon />
                        </Button>
                    </div>
                    <div className={cn('absolute bottom-[30px] flex justify-end', isRtl ? 'left-0' : 'right-0')}>
                        <DownloadButtons text={downloadAppText} links={appDownloadLinks} className='space-y-2.5' />
                    </div>
                </div>
            </div>
            {/* Mobile */}
            <div ref={mobileScrollRef} className='relative h-[190dvh] bg-primary lg:hidden'>
                <div className='sticky top-0 flex h-[100dvh] overflow-hidden px-5 pt-[clamp(28px,6vw,52px)]'>
                    <div className='flex w-full flex-col justify-between gap-[clamp(24px,5vw,40px)]'>
                        <div className='space-y-[clamp(20px,4vw,28px)]'>
                            <div className='space-y-5'>
                                <Text size='h1' fontWeight={600} className='leading-[50px] text-white max-w-[50rem] mx-auto text-center uppercase'>
                                    <TitleHtml title={title} />
                                </Text>
                                <Text size='normal' className='text-white text-center' textKey={description} />
                            </div>
                            <div className='flex-center'>
                                <ActionButtons buttonText={buttonText} buttonUrl={buttonUrl} />
                            </div>
                        </div>
                        <DownloadButtons text={downloadAppText} links={appDownloadLinks} className='space-y-2.5 flex flex-col items-center' />
                        <motion.div
                            className='relative z-20 mx-auto w-[clamp(247px,43vw,400px)]'
                            style={{ opacity: mobileImagesOpacity }}
                        >
                            <motion.div
                                style={{ y: mobileMainY }}
                            >
                                <Image src={mainImage.url} alt={mainImage.alt} width={mainImage.width} height={mainImage.height} className='h-auto w-full object-contain' />
                            </motion.div>
                            <motion.div
                                className='absolute top-[30%] -left-[20%] -z-10 w-[52%] sm:-left-[20%] md:-left-[35%]'
                                style={{ x: mobileTopLeftX }}
                            >
                                <Image src={transactionImage.url} alt={transactionImage.alt} width={transactionImage.width} height={transactionImage.height} className='h-auto w-full' />
                            </motion.div>
                            <motion.div
                                className='absolute bottom-[13%] sm:bottom-[5%] -left-[20%] z-50 w-[30%] sm:w-[48%] sm:-left-[20%] md:-left-[35%]'
                                style={{ x: mobileBottomLeftX, y: mobileBottomLeftY }}
                            >
                                <Image src={moneySavingImage.url} alt={moneySavingImage.alt} width={moneySavingImage.width} height={moneySavingImage.height} className='h-auto w-full' />
                            </motion.div>
                            <motion.div
                                className='absolute top-[15%] -right-[12%] -z-10 w-[52%] sm:-right-[20%] md:-right-[18%]'
                                style={{ x: mobileTopRightX, y: mobileTopRightY }}
                            >
                                <Image src={cardImage.url} alt={cardImage.alt} width={cardImage.width} height={cardImage.height} className='h-auto w-full rounded-[clamp(10px,2vw,18px)] border border-[#FFFFFF80] object-cover' />
                            </motion.div>
                            <motion.div
                                className='absolute right-[-8%] bottom-[7%] w-[35%] sm:-right-[15%] md:-right-[25%]'
                                style={{ x: mobileBottomRightX, y: mobileBottomRightY }}
                            >
                                <Image src={qrImage.url} alt={qrImage.alt} width={qrImage.width} height={qrImage.height} className='h-auto w-full' />
                            </motion.div>
                        </motion.div>
                    </div>
                </div>
            </div>


            
        </>
    )
}
