'use client'

import { SectionLabel, Text } from '@/components/ui'
import { motion, useMotionValueEvent, useScroll } from 'motion/react'
import React, { useEffect, useRef, useState } from 'react'
import Image from 'next/image'
import type { WhyPayseyIcon } from '@/types/home'

interface WhyPaySeyProps {
  subTitle: string
  title: string
  description: string
  icons: WhyPayseyIcon[]
  image: string
  backgroundImage: string
}

interface WhyPayseyFeatureProps {
    feature: WhyPayseyIcon & { fromX: number; fromY: number }
    index: number
    revealed: boolean
    isDesktop: boolean
}

const DESKTOP_STICKY_TOP = 70

const WhyPayseyFeature = ({ feature, index, revealed, isDesktop }: WhyPayseyFeatureProps) => {
    if (isDesktop) {
        return (
            <motion.div
                initial={{ opacity: 0, x: feature.fromX, y: feature.fromY, scale: 0.62 }}
                animate={revealed
                    ? { opacity: 1, x: 0, y: 0, scale: 1 }
                    : { opacity: 0, x: feature.fromX, y: feature.fromY, scale: 0.62 }}
                transition={{ duration: 0.85, ease: [0.22, 1, 0.36, 1], delay: revealed ? index * 0.07 : 0 }}
                className={`absolute z-10 flex flex-col items-center text-center space-y-5  ${
                    index === 0 ? '-left-[195px] -top-2'
                    : index === 1 ? '2xl:-right-[220px] -right-[180px] -top-2'
                    : index === 2 ? '-left-[270px] bottom-10 xl:-left-[350px]  [@media(min-width:1700px)]:bottom-20'
                    : index === 3 ? '-right-[300px] bottom-10 xl:-right-[250px]  2xl:-right-[350px]  [@media(min-width:1700px)]:bottom-20'
                    : 'right-20 xl:right-22 -top-42 2xl:-top-50  '
                }`}
            >
                <Image src={feature.why_paysey_icon} alt='' width={145} height={145} className='size-[80px] 2xl:size-[100px] object-contain' />
                <Text size='body' fontWeight={700} className='text-white max-w-[13rem]' textKey={feature.why_paysey_title} />
            </motion.div>
        )
    }

    return (
        <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5, ease: 'easeOut', delay: index * 0.1 }}
            className='flex flex-col items-center text-center space-y-3'
        >
            <Image src={feature.why_paysey_icon} alt='' width={100} height={100} className='size-[72px] object-contain xl:size-[100px]' />
            <Text size='body' fontWeight={700} className='text-white max-w-[13rem]' textKey={feature.why_paysey_title} />
        </motion.div>
    )
}

export const WhyPaySey = ({ subTitle, title, description, icons, image, backgroundImage }: WhyPaySeyProps) => {
    // Start each desktop icon from behind the phone image, then reveal outward.
    const positions = [
        { fromX: 235, fromY: 120 },
        { fromX: -235, fromY: 120 },
        { fromX: 300, fromY: -135 },
        { fromX: -300, fromY: -135 },
        { fromX: -85, fromY: 260 },
    ]
    const whyPayseyData = icons.map((icon, i) => ({ ...icon, ...(positions[i] ?? { fromX: 0, fromY: 0 }) }))
    const stickySectionRef = useRef<HTMLDivElement>(null)
    const [revealedStage, setRevealedStage] = useState(0)
    const [hasMounted, setHasMounted] = useState(false)
    const stageRef = useRef(0)
    const { scrollYProgress } = useScroll({
        target: stickySectionRef,
        offset: [`start ${DESKTOP_STICKY_TOP}px`, 'end end'],
    })

    useEffect(() => {
        const frame = requestAnimationFrame(() => setHasMounted(true))

        return () => cancelAnimationFrame(frame)
    }, [])

    useMotionValueEvent(scrollYProgress, 'change', (latest) => {
        const nextStage = latest >= 0.58 ? 2 : latest >= 0.28 ? 1 : 0

        if (stageRef.current !== nextStage) {
            stageRef.current = nextStage
            setRevealedStage(nextStage)
        }
    })

    return (
        <section id='why-paysey' className='relative'>
            <div className='relative bg-[radial-gradient(45.54%_60.96%_at_50%_100%,#2D643A_0%,#101E10_100%)] '>
                <div className='container xl:hidden'>
                    <div className='relative z-30 stack'>
                        <SectionLabel
                            label={subTitle}
                            labelclass='border-[#313C31]'
                            textclass='mx-auto text-center text-white'
                            className='flex-center flex-col'
                            title={<span dangerouslySetInnerHTML={{ __html: title.replace('<span>', '<span class="gradient-text">') }} />}
                            description={description}
                        />
                    </div>

                    {/* Mobile/Tablet layout */}
                    <div className={`xl:hidden flex flex-col sm:items-center gap-10 mt-10 ${!hasMounted ? 'invisible' : ''}`}>
                        <div className='grid grid-cols-2 gap-4 '>
                            {whyPayseyData.slice(0, -1).map((feature, index) => (
                                <WhyPayseyFeature key={feature.why_paysey_title} feature={feature} index={index} revealed={true} isDesktop={false} />
                            ))}
                        </div>
                        {whyPayseyData.length % 2 !== 0 && (
                            <div className='flex justify-center'>
                                <WhyPayseyFeature feature={whyPayseyData[whyPayseyData.length - 1]} index={whyPayseyData.length - 1} revealed={true} isDesktop={false} />
                            </div>
                        )}
                        <motion.div
                            initial={{ opacity: 0, y: 30 }}
                            whileInView={{ opacity: 1, y: 0 }}
                            viewport={{ once: true }}
                            transition={{ duration: 0.6, ease: 'easeOut' }}
                            className='sm:w-[300px]'
                        >
                            <Image src={image} alt='Paysey wallet application' width={523} height={700} className='h-auto w-full' priority />
                        </motion.div>
                    </div>

                </div>

                <div className={`hidden xl:block ${!hasMounted ? 'invisible' : ''}`}>
                    <div className='container'>
                        <div className='relative z-30 stack'>
                            <SectionLabel
                                label={subTitle}
                                labelclass='border-[#313C31]'
                                textclass='mx-auto text-center text-white'
                                className='flex-center flex-col'
                                title={<span dangerouslySetInnerHTML={{ __html: title.replace('<span>', '<span class="gradient-text">') }} />}
                                description={description}
                            />
                        </div>
                    </div>

                    <div ref={stickySectionRef} className='h-[160vh]'>
                        <div className='sticky top-[70px] h-[calc(100dvh-70px)] overflow-hidden'>
                            <div className='container'>
                                <div className='relative flex-center h-[calc(100dvh-70px)] items-end pt-0'>
                                    <div className='absolute z-0 h-[600px] w-full'>
                                        <Image src={backgroundImage} alt='' fill className='pointer-events-none h-[600px] w-full bottom-0 object-contain' />
                                    </div>
                                    <div className='relative'>
                                        <motion.div
                                            initial={{ opacity: 0, y: 170, scale: 0.86 }}
                                            animate={revealedStage >= 1 ? { opacity: 1, y: 0, scale: 1 } : { opacity: 0, y: 170, scale: 0.86 }}
                                            transition={{ duration: 0.6, ease: 'easeOut' }}
                                            className='relative z-20 xl:w-[416px]'
                                            style={{ willChange: 'transform, opacity' }}
                                        >
                                            <Image src={image} alt='Paysey wallet application' width={416} height={550} className='[@media(max-height:700px)]:h-[400px] object-contain [@media(min-height:700px)]:h-[430px]  [@media(min-height:770px)]:h-[550px] xl:w-[416px]'  />
                                        </motion.div>

                                        {whyPayseyData.map((feature, index) => (
                                            <WhyPayseyFeature key={feature.why_paysey_title} feature={feature} index={index} revealed={revealedStage >= 2} isDesktop={true} />
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    )
}
