"use client"
import { useRef, useCallback, useState, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'

interface MobileFeaturedCard {
  title: string
  highlight: string
  description: string
  image: string
}

const mobileFeaturedCards: MobileFeaturedCard[] = [
  {
    title: 'COVID Relief Fund',
    highlight: '₹2.05 Crores contributed to Tamil Nadu CM Relief Fund - May 17, 2021',
    description:
      "During the COVID-19 pandemic, MGM Group stepped forward to support the state government's efforts in combating the critical second wave by contributing to the Tamil Nadu Chief Minister's Relief Fund.",
    image: '/assets/about/philanthropy-covid.jpg',
  },
  {
    title: 'Blood Donation Camp',
    highlight: 'Annual blood donation camps in honour of our Founder.',
    description:
      'MGM Group organizes blood donation camps regularly to honor the legacy of our Founder, contributing to saving lives and supporting healthcare in our communities.',
    image: '/assets/about/philanthropy-blood.jpg',
  },
  {
    title: 'Environment Awareness',
    highlight: 'Over 600+ saplings planted in 6 months',
    description:
      'Our green initiative focuses on creating a sustainable environment through large-scale tree planting drives and environmental awareness programs across communities.',
    image: '/assets/about/philanthropy-environment.jpg',
  },
  {
    title: 'Eye Camp',
    highlight: 'Free eye check-up and treatment camps for communities.',
    description:
      'MGM Group conducts free eye camps providing check-ups, treatments, and eyewear to underserved communities, ensuring better vision and quality of life.',
    image: '/assets/about/philanthropy-environment-2.jpg',
  },
]

const featuredCards = mobileFeaturedCards

const MOBILE_CARD_WIDTH = 356
const MOBILE_CARD_GAP = 16
const TOTAL_MOBILE_PAGES = 3

export default function PhilanthropicActivitiesSection() {
  const mobileScrollRef = useRef<HTMLDivElement>(null)
  const [activeIndex, setActiveIndex] = useState(0)
  const [mobileActiveIndex, setMobileActiveIndex] = useState(0)

  const totalFeatured = featuredCards.length

  const scroll = useCallback((direction: 'left' | 'right') => {
    setActiveIndex((prev) => {
      if (direction === 'right') return Math.min(prev + 1, totalFeatured - 1)
      return Math.max(prev - 1, 0)
    })
  }, [totalFeatured])

  // Mobile scroll tracking
  const handleMobileScroll = useCallback(() => {
    if (!mobileScrollRef.current) return
    const sl = mobileScrollRef.current.scrollLeft
    const pageWidth = MOBILE_CARD_WIDTH + MOBILE_CARD_GAP
    const page = Math.round(sl / pageWidth)
    setMobileActiveIndex(Math.min(page, TOTAL_MOBILE_PAGES - 1))
  }, [])

  useEffect(() => {
    const el = mobileScrollRef.current
    if (!el) return
    el.addEventListener('scroll', handleMobileScroll, { passive: true })
    return () => el.removeEventListener('scroll', handleMobileScroll)
  }, [handleMobileScroll])

  const scrollToMobilePage = useCallback(
    (direction: 'prev' | 'next') => {
      if (!mobileScrollRef.current) return
      const pageWidth = MOBILE_CARD_WIDTH + MOBILE_CARD_GAP
      const newPage =
        direction === 'next'
          ? Math.min(mobileActiveIndex + 1, TOTAL_MOBILE_PAGES - 1)
          : Math.max(mobileActiveIndex - 1, 0)
      mobileScrollRef.current.scrollTo({ left: newPage * pageWidth, behavior: 'smooth' })
      setMobileActiveIndex(newPage)
    },
    [mobileActiveIndex]
  )

  return (
    <section className="bg-transparent py-16 lg:py-20 overflow-hidden lg:px-5">
      <div className="max-w-[1297px] mx-auto px-5 lg:px-0">
        {/* Header: Badge + Description */}
        <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-5 lg:gap-6 mb-10">
          {/* Badge */}
          <div>
            <span className="inline-flex items-center gap-2 px-6 py-3 bg-[#ebebeb] rounded-full">
              <img
                src="/assets/leaders/sparkle-icon.svg"
                alt=""
                loading="lazy"
                className="w-[17px] h-4 shrink-0"
              />
              <span className="font-heading text-black text-base uppercase leading-tight sm:leading-none whitespace-normal sm:whitespace-nowrap text-center">
                Philanthropic Activities
              </span>
            </span>
          </div>

          {/* Description */}
          <div className="max-w-full lg:max-w-[413px]">
            <p className="font-sans font-medium lg:font-normal text-base text-[rgba(16,36,67,0.6)] lg:text-[#4a5565] leading-[1.5] lg:leading-[24px]">
              Philanthropy at MGM Group is driven by responsibility and compassion. We support initiatives that uplift communities and create lasting social impact.
            </p>
            <div className="mt-4 lg:mt-6 border-b border-[rgba(16,36,67,0.2)]" />
          </div>
        </div>

        {/* Mobile: Featured Cards Carousel */}
        <div className="lg:hidden">
          <div
            ref={mobileScrollRef}
            className="flex gap-4 overflow-x-auto scrollbar-hide cursor-grab active:cursor-grabbing -mx-5 pl-5 pr-0"
          >
            {mobileFeaturedCards.map((card, idx) => (
              <div
                key={idx}
                className="flex-shrink-0 w-[356px] rounded-2xl overflow-hidden border border-[rgba(229,231,235,0.5)]"
                style={{ background:
                    'linear-gradient(146.6deg, rgb(42, 48, 54) 16.68%, rgb(35, 40, 45) 95.23%)',
                }}
              >
                {/* Decorative vector */}
                <div className="absolute right-0 top-[75px] w-[409px] h-[405px] opacity-20 pointer-events-none overflow-hidden">
                  <img
                    src="/assets/about/decorative-vector.svg"
                    alt=""
                    loading="lazy"
                    className="w-[303px] h-[276px] object-contain rotate-[38.68deg]"
                    aria-hidden="true"
                  />
                </div>

                {/* Image */}
                <div className="w-full h-[222px]">
                  <img
                    src={card.image}
                    alt={card.title}
                    loading="lazy"
                    draggable={false}
                    className="w-full h-full object-cover"
                  />
                </div>

                {/* Content */}
                <div className="flex flex-col gap-3 p-4 relative z-10">
                  <h3 className="font-heading font-bold text-[20px] text-white leading-normal">
                    {card.title}
                  </h3>
                  <div className="bg-[#3a4046] rounded p-3">
                    <p className="font-sans font-normal text-sm text-white leading-[20px]">
                      {card.highlight}
                    </p>
                  </div>
                  <p className="font-sans font-normal text-sm text-white/60 leading-[20px]">
                    {card.description}
                  </p>
                </div>
              </div>
            ))}
          </div>

          {/* Mobile Pagination + Arrows */}
          <div className="flex items-center justify-end w-full mt-6">
            {/* Navigation Arrows */}
            <div className="flex gap-[13px] items-center">
              <button
                onClick={() => scrollToMobilePage('prev')}
                className={`flex items-center justify-center w-[44px] h-[44px] rounded-full border-2 border-[#d20010] bg-transparent pl-[2px] ${
                  mobileActiveIndex === 0 ? 'opacity-50' : 'opacity-100'
                }`}
                aria-label="Previous activity"
                disabled={mobileActiveIndex === 0}
              >
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M15 6L9 12L15 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <button
                onClick={() => scrollToMobilePage('next')}
                className={`flex items-center justify-center w-[44px] h-[44px] rounded-full border-2 border-[#d20010] bg-transparent pl-[2px] ${
                  mobileActiveIndex === TOTAL_MOBILE_PAGES - 1 ? 'opacity-50' : 'opacity-100'
                }`}
                aria-label="Next activity"
                disabled={mobileActiveIndex === TOTAL_MOBILE_PAGES - 1}
              >
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M9 6L15 12L9 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            </div>
          </div>
        </div>

        {/* Desktop: Featured Card */}
        <div className="hidden lg:block mb-6">
            <div
              className="relative rounded-2xl overflow-hidden border border-[rgba(229,231,235,0.5)]"
              style={{ background:
                  'linear-gradient(173.33deg, rgb(42, 48, 54) 16.68%, rgb(35, 40, 45) 95.23%)',
              }}
            >
              {/* Decorative vector */}
              <div className="absolute right-[100px] -top-[156px] w-[402px] h-[400px] opacity-20 pointer-events-none">
                <img
                  src="/assets/about/decorative-vector.svg"
                  alt=""
                  loading="lazy"
                  className="w-full h-full object-contain rotate-[38.68deg]"
                />
              </div>

              <div className="flex flex-row min-h-[303px]">
                {/* Image */}
                <div className="w-1/2 h-auto">
                  <img
                    src={featuredCards[activeIndex].image}
                    alt={featuredCards[activeIndex].title}
                    loading="lazy"
                    className="w-full h-full object-cover"
                  />
                </div>

                {/* Content */}
                <div className="w-1/2 flex flex-col justify-center gap-3 p-6 relative z-10">
                  <h3 className="font-heading font-bold text-2xl text-white">
                    {featuredCards[activeIndex].title}
                  </h3>
                  <div className="bg-[#3a4046] rounded p-4">
                    <p className="font-sans font-normal text-base text-white">
                      {featuredCards[activeIndex].highlight}
                    </p>
                  </div>
                  <p className="font-sans font-normal text-base text-white/60 leading-[20px]">
                    {featuredCards[activeIndex].description}
                  </p>
                </div>
              </div>
            </div>
        </div>

        {/* Desktop: Thumbnail Cards */}
        <div className="hidden lg:grid grid-cols-4 gap-6 mb-6">
          {featuredCards.map((card, idx) => (
            <button
              key={idx}
              onClick={() => setActiveIndex(idx)}
              className={`rounded-lg overflow-hidden border flex text-left transition-all ${idx === activeIndex ? 'border-[#d20010] shadow-[0px_2px_25px_5px_rgba(16,36,67,0.05)]' : 'border-[#d9d9d9]'}`}
              style={{ background: 'radial-gradient(ellipse at top left, rgba(255,232,233,1), rgba(255,232,233,0) 80%)',
              }}
            >
              <div className="w-[140px] h-[114px] shrink-0">
                <img
                  src={card.image}
                  alt={card.title}
                  loading="lazy"
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="flex-1 p-3 flex flex-col justify-center text-[#102443]">
                <h4 className="font-heading font-bold text-base leading-normal">
                  {card.title}
                </h4>
                <p className="font-sans font-normal text-xs leading-[1.3] mt-2">
                  {card.highlight}
                </p>
              </div>
            </button>
          ))}
        </div>

        {/* Desktop: Progress bars + Navigation arrows */}
        <div className="hidden lg:flex items-center justify-end">

          <div className="flex gap-2">
            <button
              onClick={() => scroll('left')}
              disabled={activeIndex === 0}
              className={`w-[60px] h-[58px] rounded-full border-2 flex items-center justify-center transition-opacity ${activeIndex === 0 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] opacity-100 hover:opacity-80'}`}
              aria-label="Previous activity"
            >
              <ChevronLeft size={20} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
            <button
              onClick={() => scroll('right')}
              disabled={activeIndex === totalFeatured - 1}
              className={`w-[60px] h-[58px] rounded-full border-2 flex items-center justify-center transition-opacity ${activeIndex === totalFeatured - 1 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] opacity-100 hover:opacity-80'}`}
              aria-label="Next activity"
            >
              <ChevronRight size={20} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
          </div>
        </div>
      </div>
    </section>
  )
}
