'use client'

import { SectionLabel, Text } from '@/components/ui'
import { motion, useMotionValueEvent, useScroll, useTransform } from 'motion/react'
import Image from 'next/image'
import React, { useRef, useState } from 'react'
import type { PaymentJourneyCard } from '@/types/home'

interface PaymentJourneyProps {
  subTitle: string
  title: string
  description: string
  cards: PaymentJourneyCard[]
}

const CARD_SCROLL_HEIGHT_VH = 90

export const PaymentJourney = ({ subTitle, title, description, cards }: PaymentJourneyProps) => {
  const sectionRef = useRef<HTMLElement>(null)
  const sliderRef = useRef<HTMLDivElement>(null)
  const cardRefs = useRef<Array<HTMLElement | null>>([])
  const activeIndexRef = useRef(0)
  const [activeIndex, setActiveIndex] = useState(0)
  const cardCount = Math.max(cards.length, 1)
  const desktopSectionHeight = `${cardCount * CARD_SCROLL_HEIGHT_VH}vh`
  const { scrollYProgress } = useScroll({
    target: sectionRef,
    offset: ['start start', 'end end'],
  })
  const trackX = useTransform(scrollYProgress, [0, 1], ['0vw', `${-(cardCount - 1) * 100}vw`])

  useMotionValueEvent(scrollYProgress, 'change', (latest) => {
    if (cards.length <= 1) return

    const nextIndex = Math.min(cards.length - 1, Math.max(0, Math.round(latest * (cards.length - 1))))
    if (nextIndex !== activeIndexRef.current) {
      activeIndexRef.current = nextIndex
      setActiveIndex(nextIndex)
    }
  })

  return (
    <div className='stack'>
      <section
        id='payment-journey'
        className='overflow-hidden bg-[#F5F5F5] py-20 md:py-24 xl:py-[150px]'
      >
        <div className='shrink-0 pxcontainer'>
          <SectionLabel
            textclass='mx-auto max-w-[50rem] text-center'
            className='flex-center flex-col space-y-5'
            label={subTitle}
            title={<span dangerouslySetInnerHTML={{ __html: title.replace('<span>', '<span class="gradient-text-green">') }} />}
            description={description}
          />
        </div>

        {/* Mobile: vertical stack */}
        <div className='flex flex-col gap-10 lg:hidden pxcontainer stack'>
          {cards.map((item, index) => (
            <div key={item.made_for_everyday_payments_background__text} className='flex flex-col sm:items-center'>
              <div className='relative z-20'>
                <h2 className='text-center relative uppercase text-[#101E10]/10 -z-10 top-5 text-[64px] font-extrabold leading-[64px]'>{item.made_for_everyday_payments_background__text}</h2>
                <div className='flex gap-10 flex-col'>
                  <div className='flex-center'>
                    <Image src={item.made_for_everyday_payments_image} alt='Paysey mobile wallet application' width={250} height={500} className='w-[250px]' priority={index === 0} />
                  </div>
                  <div className='space-y-3'>
                    <Text size='h3' fontWeight={600} textKey={item.made_for_everyday_payments_title} />
                    <Text size='normal' textKey={item.made_for_everyday_payments_description} />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Desktop: vertical scroll drives the pinned horizontal journey */}
        <section ref={sectionRef} className='relative hidden overflow-clip lg:block' style={{ height: desktopSectionHeight }}>
          <div className='sticky top-0 h-screen overflow-hidden'>
            <motion.div ref={sliderRef} style={{ x: trackX }} className='flex h-full w-max will-change-transform'>
              {cards.map((item, index) => (
                <motion.article
                  key={item.made_for_everyday_payments_background__text}
                  ref={(element) => { cardRefs.current[index] = element }}
                  aria-hidden={activeIndex !== index}
                  initial={{ opacity: index === 0 ? 1 : 0.5, scale: index === 0 ? 1 : 0.965 }}
                  animate={activeIndex === index ? { opacity: 1, scale: 1 } : { opacity: 0.5, scale: 0.965 }}
                  transition={{ type: 'spring', stiffness: 80, mass: 0.5 }}
                  className='relative flex h-full w-screen shrink-0 items-center justify-center overflow-hidden px-[7vw] lg:px-[11vw]'
                >
                  <div className='relative z-20 mx-auto flex h-[90vh] w-full items-center justify-center'>
                    <h2 className='pointer-events-none absolute left-1/2 top-[clamp(1rem,5vh,3rem)] -z-10 w-max -translate-x-1/2 whitespace-nowrap uppercase text-[#101E10]/8 text-[90px] font-extrabold xl:text-[120px]'>{item.made_for_everyday_payments_background__text}</h2>
                    <div className='stackinline flex-center'>
                      <div className='relative z-20 w-[clamp(210px,min(26vw,45vh),350px)]'>
                        <Text
                          size='h3'
                          fontWeight={600}
                          className='absolute left-[calc(-1*clamp(17rem,24vw,22rem))] top-1/2 -z-10 max-w-[18rem] -translate-y-1/2 xl:max-w-[20rem]'
                          textKey={item.made_for_everyday_payments_title}
                        />
                        <Image
                          src={item.made_for_everyday_payments_image}
                          alt='Paysey mobile wallet application'
                          width={350}
                          height={700}
                          className='h-auto max-h-[86vh] w-full object-contain'
                          sizes='(min-width: 1280px) 350px, (min-width: 1024px) 26vw, 250px'
                          priority={index === 0}
                        />
                        <Text
                          size='normal'
                          className='absolute right-[calc(-1*clamp(17rem,27vw,25rem))] bottom-[clamp(7rem,22vh,12.5rem)] max-w-[18rem] xl:max-w-[20rem]'
                          textKey={item.made_for_everyday_payments_description}
                        />
                      </div>
                    </div>
                  </div>
                </motion.article>
              ))}
            </motion.div>
          </div>
        </section>
      </section>
    </div>
  )
}
