"use client"
import { useRef, useState, useCallback, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { PhilanthropicData } from '@/lib/strapi/types'
import { homepageDefaults } from '@/lib/api/defaults'

interface PhilanthropicSectionProps {
  data?: PhilanthropicData
}

export default function PhilanthropicSection({ data = homepageDefaults.philanthropic }: PhilanthropicSectionProps) {
  const allActivities = data.activities
  const smallActivities = data.activities.map((a) => ({
    title: a.title,
    description: a.highlight,
    image: a.image,
  }))
  const scrollRef = useRef<HTMLDivElement>(null)
  const [activeSlide, setActiveSlide] = useState(0)
  const currentActivity = allActivities[activeSlide]

  const handlePrev = () => {
    setActiveSlide((prev) => (prev > 0 ? prev - 1 : allActivities.length - 1))
  }

  const handleNext = () => {
    setActiveSlide((prev) => (prev < allActivities.length - 1 ? prev + 1 : 0))
  }

  const [, setScrollIndex] = useState(0)
  const [selectedDesktopIndex, setSelectedDesktopIndex] = useState(0)
  const [, setCanScrollLeft] = useState(false)
  const [, setCanScrollRight] = useState(true)
  const desktopActivity = allActivities[selectedDesktopIndex]
  const CARD_WIDTH = 416 + 24

  const handleSubCardClick = (title: string, event: React.MouseEvent) => {
    const idx = allActivities.findIndex((a) => a.title === title)
    if (idx !== -1) setSelectedDesktopIndex(idx)
    
    if (event.currentTarget) {
      event.currentTarget.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' })
    }
  }

  const handleScrollCards = (direction: 'left' | 'right') => {
    const newIndex = direction === 'right'
      ? Math.min(selectedDesktopIndex + 1, allActivities.length - 1)
      : Math.max(selectedDesktopIndex - 1, 0)
    setSelectedDesktopIndex(newIndex)
    setScrollIndex(newIndex)
    if (scrollRef.current) {
      scrollRef.current.scrollTo({
        left: newIndex * CARD_WIDTH,
        behavior: 'smooth',
      })
    }
  }

  const checkScroll = useCallback(() => {
    if (!scrollRef.current) return
    const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current
    const maxScroll = scrollWidth - clientWidth

    setCanScrollLeft(scrollLeft > 0)
    setCanScrollRight(maxScroll > 0 && Math.ceil(scrollLeft) < maxScroll - 5)

    if (maxScroll > 0) {
      const progress = scrollLeft / maxScroll
      const idx = Math.round(progress * (smallActivities.length - 1))
      setScrollIndex(Math.min(idx, smallActivities.length - 1))
    } else {
      setScrollIndex(0)
    }
  }, [])

  useEffect(() => {
    checkScroll()
    const el = scrollRef.current
    if (!el) return
    el.addEventListener('scroll', checkScroll, { passive: true })
    window.addEventListener('resize', checkScroll)
    return () => {
      el.removeEventListener('scroll', checkScroll)
      window.removeEventListener('resize', checkScroll)
    }
  }, [checkScroll])

  return (
    <section className="py-10 lg:py-16">
      {/* ===== MOBILE LAYOUT ===== */}
      <div className="lg:hidden px-[20px]">
        {/* Header */}
        <div className="flex flex-col gap-[20px] mb-[32px]">
          <div>
            <span
              className="font-heading inline-flex items-center gap-2 px-[24px] py-[12px] bg-[#ebebeb] rounded-[66px] text-[16px] text-black uppercase leading-tight sm:leading-none whitespace-normal sm:whitespace-nowrap text-center"
            >
              <img src={data.header.badgeIcon || "/assets/leaders/sparkle-icon.svg"} alt="" loading="lazy" className="w-[17px] h-4 shrink-0" />
              {data.header.badge || 'Philanthropic Activities'}
            </span>
          </div>
          <div className="flex flex-col gap-[16px]">
            <p
              className="font-sans text-[16px] font-medium leading-[1.5]"
              style={{ color: 'rgba(16, 36, 67, 0.6)' }}
            >
              {data.header.description}
            </p>
            <div className="border-b border-[#102443]/20" />
          </div>
        </div>

        {/* Featured card as slider */}
        <div
          className="relative w-full min-h-[650px] rounded-[16px] overflow-hidden border border-[rgba(229,231,235,0.5)] flex flex-col"
          style={{ background: 'linear-gradient(147deg, rgb(42, 48, 54) 16.7%, rgb(35, 40, 45) 95.2%)',
          }}
        >
          {/* Decorative vector */}
          <img
            src="/assets/about/decorative-vector.svg"
            alt=""
            loading="lazy"
            className="absolute pointer-events-none opacity-20"
            style={{ width: '303px',
              height: '276px',
              top: '75px',
              left: '177px',
              transform: 'rotate(38.68deg)',
            }}
            aria-hidden="true"
          />

          {/* Image */}
          <div className="w-full h-[222px] relative">
            <img
              src={currentActivity.image}
              alt={currentActivity.title}
              className="absolute inset-0 w-full h-full object-cover"
              loading="lazy"
            />
          </div>

          {/* Content */}
          <div className="flex flex-col gap-[12px] p-[16px] relative z-10 flex-1">
            <h3
              className="font-heading text-white text-[20px] leading-normal font-bold"
            >
              {currentActivity.title}
            </h3>
            <div className="bg-[#3a4046] rounded-[4px] p-[12px]">
              <p
                className="font-sans text-white text-[14px] font-normal leading-[20px]"
              >
                {currentActivity.highlight}
              </p>
            </div>
            <p
              className="font-sans text-[14px] font-normal leading-[20px]"
              style={{ color: 'rgba(255, 255, 255, 0.6)' }}
            >
              {currentActivity.description}
            </p>
          </div>
        </div>

        {/* Dots + Arrows */}
        <div className="flex items-center justify-end mt-[20px]">
          <div className="flex items-center gap-2">
            <button
              onClick={handlePrev}
              disabled={activeSlide === 0}
              className={`w-[44px] h-[44px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${activeSlide === 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'}`}
              aria-label="Previous"
            >
              <ChevronLeft size={18} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
            <button
              onClick={handleNext}
              disabled={activeSlide === allActivities.length - 1}
              className={`w-[44px] h-[44px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${activeSlide === allActivities.length - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'}`}
              aria-label="Next"
            >
              <ChevronRight size={18} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
          </div>
        </div>
      </div>

      {/* ===== DESKTOP LAYOUT ===== */}
      <div className="hidden lg:block">
        {/* Header + Featured card in max-width container */}
        <div className="max-w-[1296px] mx-auto">
          {/* Section Header */}
          <div className="flex flex-row items-start justify-between gap-6 mb-10">
            <div>
              <span className="inline-flex items-center gap-2 px-6 py-3 bg-[#ebebeb] rounded-full">
                <img src={data.header.badgeIcon || "/assets/leaders/sparkle-icon.svg"} alt="" loading="lazy" className="w-[17px] h-4" />
                <span
                  className="font-heading text-black text-base uppercase leading-none"
                >
                  {data.header.badge || 'Philanthropic Activities'}
                </span>
              </span>
            </div>
            <div className="max-w-[413px]">
              <p
                className="font-sans text-[#4a5565] text-base leading-[24px]"
              >
                {data.header.description}
              </p>
              <div className="mt-6 border-b border-[#102443]/20" />
            </div>
          </div>

          {/* Featured Activity Card */}
          <div
            className="w-full h-[380px] rounded-2xl overflow-hidden flex flex-row border border-[rgba(229,231,235,0.5)] mb-6"
            style={{ background: 'linear-gradient(173deg, rgb(42,48,54) 17%, rgb(35,40,45) 95%)',
            }}
          >
            <div className="w-1/2 h-full relative">
              <img
                src={desktopActivity.image}
                alt={desktopActivity.title}
                loading="lazy"
                className="absolute inset-0 w-full h-full object-cover rounded-[13px]"
              />
            </div>
            <div className="flex-1 flex flex-col gap-3 justify-center p-6 relative">
              <h3
              className="font-heading text-white text-[24px] leading-normal font-bold"
            >
              {desktopActivity.title}
              </h3>
              <div className="bg-[#3a4046] rounded p-4">
                <p
                  className="font-sans text-white text-base leading-[24px]"
                >
                  {desktopActivity.highlight}
                </p>
              </div>
              <p
                className="font-sans text-white/60 text-base leading-[20px]"
              >
                {desktopActivity.description}
              </p>
            </div>
          </div>
        </div>

        {/* Scrollable Activity Cards Row — aligned left with section, overflows right */}
        <div
          ref={scrollRef}
          className="flex gap-6 overflow-x-auto pb-4"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none', paddingLeft: 'max(72px, calc((100% - 1296px) / 2))', paddingRight: '72px' }}
        >
          {smallActivities.map((activity, i) => {
            const isActive = allActivities[selectedDesktopIndex]?.title === activity.title
            return (
              <div
                key={i}
                onClick={(e) => handleSubCardClick(activity.title, e)}
                className={`flex-shrink-0 w-[416px] h-[140px] rounded-lg overflow-hidden flex border cursor-pointer transition-all duration-300 ${isActive
                    ? 'border-[#d20010] shadow-[0px_2px_25px_5px_rgba(210,0,16,0.15)]'
                    : 'border-[rgba(229,231,235,0.5)] shadow-[0px_2px_25px_5px_rgba(16,36,67,0.05)]'
                  }`}
                style={{ background:
                    'radial-gradient(ellipse at 42% 84%, rgba(255,232,233,0) 0%, rgba(255,232,233,1) 100%), #fff',
                }}
              >
                <div className="w-[173px] h-full shrink-0 relative">
                  <img
                    src={activity.image}
                    alt={activity.title}
                    loading="lazy"
                    className="absolute inset-0 w-full h-full object-cover"
                  />
                </div>
                <div className="flex-1 flex flex-col gap-2 justify-center p-3">
                  <h4
                    className="font-heading text-[#102443] text-base leading-normal font-bold"
                  >
                    {activity.title}
                  </h4>
                  <p
                    className="text-[#102443] text-xs leading-[1.1]"
                  >
                    {activity.description}
                  </p>
                </div>
              </div>
            )
          })}
        </div>

        {/* Progress + Arrows */}
        <div className="flex items-center justify-end mt-4 max-w-[1296px] mx-auto px-[72px]">
          <div className="flex items-center gap-2">
            <button
              onClick={() => handleScrollCards('left')}
              disabled={selectedDesktopIndex === 0}
              className={`w-[58px] h-[58px] rounded-full border-2 flex items-center justify-center transition-all active:scale-95 ${selectedDesktopIndex === 0 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] opacity-100 hover:opacity-80'}`}
              aria-label="Previous"
            >
              <ChevronLeft size={20} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
            <button
              onClick={() => handleScrollCards('right')}
              disabled={selectedDesktopIndex === allActivities.length - 1}
              className={`w-[58px] h-[58px] rounded-full border-2 flex items-center justify-center transition-all active:scale-95 ${selectedDesktopIndex === allActivities.length - 1 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] opacity-100 hover:opacity-80'}`}
              aria-label="Next"
            >
              <ChevronRight size={20} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
          </div>
        </div>
      </div>
    </section>
  )
}
