'use client'

import { SectionLabel, Text } from '@/components/ui'
import { ArrowRight } from 'lucide-react'
import Image from 'next/image'
import React, { useEffect, useRef, useState } from 'react'
import type { ProductCard } from '@/types/home'

interface FeaturedProductsProps {
  subTitle: string
  title: string
  description: string
  featureList: { list_title: string }[]
  cards: ProductCard[]
}

export const FeaturedProducts = ({ subTitle, title, description, featureList, cards }: FeaturedProductsProps) => {
  const [activeProduct, setActiveProduct] = useState(0)
  const cardRefs = useRef<Array<HTMLElement | null>>([])
  const sectionRef = useRef<HTMLElement>(null)

  useEffect(() => {
    const updateActive = () => {
      const trigger = window.innerHeight * 0.4
      let active = 0
      cardRefs.current.forEach((card, i) => {
        if (!card) return
        const top = card.getBoundingClientRect().top
        if (top <= trigger) active = i
      })
      setActiveProduct(active)
    }

    window.addEventListener('scroll', updateActive, { passive: true })
    updateActive()
    return () => window.removeEventListener('scroll', updateActive)
  }, [cards.length])

  const scrollToProduct = (index: number) => {
    setActiveProduct(index)
    cardRefs.current[index]?.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }

  return (
 <div  id='products'>
     <section ref={sectionRef} className=''>
      <div className='flex justify-between gap-[50px] xl:gap-[150px] flex-col lg:flex-row'>

        <div className='lg:sticky lg:top-16 lg:self-start max-w-[30rem]'>
          <SectionLabel
            label={subTitle}
            labelclass='border-white/10'
            textclass='text-white'
            title={<span dangerouslySetInnerHTML={{ __html: title.replace('<span>', '<span class="gradient-text">') }} />}
            titleClassName='max-w-[35rem] xl:leading-[1.12] 2xl:leading-[1.14]'
            descriptionClassName='max-w-[34rem] text-white/72 leading-relaxed'
            description={description}
          />

          <nav aria-label='Featured products' className='pt-[50px] lg:block hidden'>
            {featureList.map((product, index) => {
              const isActive = index === activeProduct
              return (
                <button
                  key={product.list_title}
                  type='button'
                  onClick={() => scrollToProduct(index)}
                  aria-current={isActive ? 'true' : undefined}
                  className={`group flex w-full items-center gap-3 first:border-t border-b border-[#EEEEEE26] py-4 transition-colors duration-300 xl:py-5 cursor-pointer ${
                    isActive ? 'text-white' : 'text-white/35 hover:text-white/70'
                  }`}
                >
                  <span
                    className='shrink-0 overflow-hidden transition-[max-width,opacity] duration-300'
                    style={{ maxWidth: isActive ? '1.25rem' : '0', opacity: isActive ? 1 : 0 }}
                    aria-hidden='true'
                  >
                    <ArrowRight className='size-4 text-[#0db96b]' strokeWidth={1.7} />
                  </span>
                  <Text size='body' textKey={product.list_title} />
                </button>
              )
            })}
          </nav>
        </div>

        <div className='scrollbar-hide space-y-[30px] lg:w-[500px] xl:w-[878px] xl:space-y-[50px]'>
          {cards.map((product, index) => (
            <article
              key={product.product_title}
              ref={(element) => { cardRefs.current[index] = element }}
              className='group relative rounded-[16px] lg:rounded-[30px] overflow-hidden bg-[#142618]'
            >
              <div className='relative'>
                <Image src={product.product_background_image} alt={product.product_title} width={878} height={500} className='h-[190px] sm:h-[400px] xl:h-[500px] rounded-[18px] lg:rounded-[32px] object-cover' />
                <div className='lg:block hidden absolute h-full w-full top-0 bg-[linear-gradient(0.16deg,#000000_0.14%,rgba(0,0,0,0)_48.22%)]' />
                <div className='lg:hidden absolute h-full w-full top-0 bg-[linear-gradient(359.87deg,rgba(0,0,0,0.9)_0.12%,rgba(0,0,0,0)_99.88%)]' />
              </div>
              <div className='absolute inset-x-0 bottom-0 z-10 p-[30px] text-white space-y-2 md:space-y-2.5'>
                <Text size='h3' className='font-semibold' textKey={product.product_title} />
                <Text size='normal' textKey={product.product_description} />
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
 </div>
  )
}
