"use client"
import { useState, useRef, useCallback, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { AboutCharitableTrustData } from '@/lib/strapi/types'

const FALLBACK_AID_ITEMS = [
  'Old age home support in Kovalam since 1995',
  'Educational aid to poor students since inception',
  'Feeding programs for orphanages',
  'Various charitable activities',
  "Food & clothes distribution on Founder's Day",
  'Scholarships, books & student support',
  'Tuticorin flood relief (2023) & medical aid (2024)',
]

const FALLBACK_SLIDES = [
  '/assets/about/responsibilty/MGM 15L Donation LittleSistersAgedHome Chennai 2015.JPG',
  '/assets/about/responsibilty/MGM_Charity_Greet_2023.jpg.JPG',
  '/assets/about/responsibilty/MGM_Cheque_Donation.JPG',
  '/assets/about/responsibilty/MGM_Charity_TV_Donation_1999.JPG',
  '/assets/about/responsibilty/MGM_Clothes_Distribution.jpg',
  '/assets/about/responsibilty/MGM_EducationSupport.JPG',
  '/assets/about/responsibilty/MGM_StJohnBritto_AgedHome_2005.JPG',
  '/assets/about/responsibilty/MGM_Student_Support.JPG',
  '/assets/about/responsibilty/MGM_FoundersDay_Food.jpg',
]

const FALLBACK_DESCRIPTION =
  'Giving back to society through meaningful initiatives Chevalier Dr. MG Muthu was a generous philanthropist who established the MGM Charitable Trust to serve society.'

export default function CharitableTrustSection({ data }: { data: AboutCharitableTrustData }) {
  const badge = data.badge || 'Group Sponsorship'
  const badgeIcon = data.badgeIcon || '/assets/about/golden-badge-icon.svg'
  const description = data.description || FALLBACK_DESCRIPTION
  const watermarkText = data.watermarkText || 'MGM Charitable Trust'
  const aidIntroText = data.aidIntroText || 'Through this trust, the group has been providing aid to:'
  const aidBulletIcon = data.aidBulletIcon || '/assets/about/badge-star-dark.svg'
  const aidItems = data.aidItems.length > 0 ? data.aidItems : FALLBACK_AID_ITEMS
  const slideUrls = data.slides.length > 0 ? data.slides : FALLBACK_SLIDES
  const slides = slideUrls.map((url) => ({ main: url, thumb: url }))

  const [activeSlide, setActiveSlide] = useState(0)
  const mobileScrollRef = useRef<HTMLDivElement>(null)
  const thumbScrollRef = useRef<HTMLDivElement>(null)
  const [mobileActiveIndex, setMobileActiveIndex] = useState(0)
  const [thumbIndex, setThumbIndex] = useState(0)
  const MOBILE_TOTAL_PAGES = Math.max(1, slides.length)
  const MOBILE_IMAGE_WIDTH = 352
  const MOBILE_IMAGE_GAP = 16
  const THUMB_CARD_WIDTH = 120
  const THUMB_GAP = 12
  const VISIBLE_THUMBS = 4

  const handleMobileScroll = useCallback(() => {
    if (!mobileScrollRef.current) return
    const pageWidth = MOBILE_IMAGE_WIDTH + MOBILE_IMAGE_GAP
    const page = Math.round(mobileScrollRef.current.scrollLeft / pageWidth)
    setMobileActiveIndex(Math.min(page, MOBILE_TOTAL_PAGES - 1))
  }, [MOBILE_TOTAL_PAGES])

  useEffect(() => {
    const el = mobileScrollRef.current
    if (!el) return
    el.addEventListener('scroll', handleMobileScroll, { passive: true })
    return () => el.removeEventListener('scroll', handleMobileScroll)
  }, [handleMobileScroll])

  const scrollMobileTo = useCallback(
    (direction: 'prev' | 'next') => {
      if (!mobileScrollRef.current) return
      const pageWidth = MOBILE_IMAGE_WIDTH + MOBILE_IMAGE_GAP
      const newPage =
        direction === 'next'
          ? Math.min(mobileActiveIndex + 1, MOBILE_TOTAL_PAGES - 1)
          : Math.max(mobileActiveIndex - 1, 0)
      mobileScrollRef.current.scrollTo({ left: newPage * pageWidth, behavior: 'smooth' })
      setMobileActiveIndex(newPage)
    },
    [mobileActiveIndex, MOBILE_TOTAL_PAGES],
  )

  const maxThumbIndex = Math.max(0, slides.length - VISIBLE_THUMBS)

  const scrollThumbs = useCallback(
    (direction: 'left' | 'right') => {
      if (!thumbScrollRef.current) return
      const newIndex =
        direction === 'right'
          ? Math.min(thumbIndex + 1, maxThumbIndex)
          : Math.max(thumbIndex - 1, 0)
      setThumbIndex(newIndex)
      thumbScrollRef.current.scrollTo({
        left: newIndex * (THUMB_CARD_WIDTH + THUMB_GAP),
        behavior: 'smooth',
      })
    },
    [thumbIndex, maxThumbIndex],
  )

  const handleThumbClick = useCallback(
    (i: number) => {
      setActiveSlide(i)
      const newThumbStart = Math.max(0, Math.min(i - Math.floor(VISIBLE_THUMBS / 2), slides.length - VISIBLE_THUMBS))
      setThumbIndex(newThumbStart)
      if (thumbScrollRef.current) {
        thumbScrollRef.current.scrollTo({
          left: newThumbStart * (THUMB_CARD_WIDTH + THUMB_GAP),
          behavior: 'smooth',
        })
      }
    },
    [slides.length],
  )

  const safeActiveSlide = Math.min(activeSlide, slides.length - 1)

  return (
    <section className="w-full pt-28 pb-10 lg:pt-40 lg:pb-16">
      {/* ===== MOBILE LAYOUT ===== */}
      <div className="lg:hidden px-[17px]">
        {/* 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"
            >
              <img src={badgeIcon} alt="" loading="lazy" className="w-[17px] h-4" />
              {badge}
            </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)' }}
            >
              {description}
            </p>
            <div className="border-b border-[#102443]/20" />
          </div>
        </div>

        {/* Image slider - horizontal scroll */}
        <div
          ref={mobileScrollRef}
          className="flex gap-[16px] overflow-x-auto mb-[20px]"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
        >
          {slides.map((s, i) => (
            <div
              key={i}
              className="relative flex-shrink-0 rounded-[8px] overflow-hidden"
              style={{ width: '352px', height: '218px' }}
            >
              <img
                src={s.main}
                alt=""
                loading="lazy"
                className="absolute inset-0 w-full h-full object-cover"
              />
              <div
                className="absolute inset-0"
                style={{
                  background: 'linear-gradient(179deg, rgba(0,0,0,0) 69%, rgba(0,0,0,0.5) 95%)',
                }}
              />
            </div>
          ))}
        </div>

        {/* Navigation arrows */}
        <div className="flex items-center justify-end mb-[20px]" style={{ width: '353px', maxWidth: '100%' }}>
          <div className="flex gap-[13px] items-center">
            <button
              onClick={() => scrollMobileTo('prev')}
              disabled={mobileActiveIndex === 0}
              className={`flex items-center justify-center w-[44px] h-[44px] rounded-full border-2 border-[#d20010] bg-transparent transition-all active:scale-95 ${mobileActiveIndex === 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'
                }`}
              aria-label="Previous image"
            >
              <ChevronLeft size={18} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
            <button
              onClick={() => scrollMobileTo('next')}
              disabled={mobileActiveIndex === MOBILE_TOTAL_PAGES - 1}
              className={`flex items-center justify-center w-[44px] h-[44px] rounded-full border-2 border-[#d20010] bg-transparent transition-all active:scale-95 ${mobileActiveIndex === MOBILE_TOTAL_PAGES - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'
                }`}
              aria-label="Next image"
            >
              <ChevronRight size={18} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
          </div>
        </div>

        {/* Watermark text */}
        <p
          className="font-heading relative z-0 text-[12vw] leading-[0.8] tracking-[-1px] select-none mb-[22px] lg:mb-[0px] px-2 whitespace-pre-line"
          style={{
            color: 'rgba(16, 36, 67, 0.08)',
          }}
          aria-hidden="true"
        >
          {watermarkText.replace(/\s+(?=[Tt]rust\b)/, '\n')}
        </p>

        {/* Trust Aid Card */}
        <div
          className="relative z-10 mt-[-20px] rounded-[16px] overflow-hidden flex flex-col py-10 px-6 sm:px-8"
          style={{
            background:
              'radial-gradient(ellipse at 42% 84%, rgba(255,232,233,0) 0%, rgba(255,232,233,1) 100%), #fff',
          }}
        >
          <div className="relative z-10 flex flex-col gap-[24px] w-full">
            <p
              className="font-sans text-[#101828] text-[16px] font-medium leading-[24px]"
            >
              {aidIntroText}
            </p>
            <div className="flex flex-col gap-5">
              {aidItems.map((item, i) => (
                <div key={i} className="flex items-start gap-4">
                  <img
                    src={aidBulletIcon}
                    alt=""
                    loading="lazy"
                    className="w-[17px] h-4 shrink-0 mt-1"
                  />
                  <p
                    className="font-sans text-[#4a5565] text-[14px] font-normal leading-[24px]"
                  >
                    {item}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ===== DESKTOP LAYOUT ===== */}
      <div className="hidden lg:block px-[72px]"><div className="max-w-[1297px] mx-auto">
        {/* Section Header */}
        <div className="flex flex-row items-start justify-between gap-6 mb-4">
          <div>
            <span className="inline-flex items-center gap-2 px-6 py-3 bg-[#ebebeb] rounded-full">
              <img src={badgeIcon} alt="" loading="lazy" className="w-[17px] h-4" />
              <span
                className="font-heading text-black text-base uppercase leading-none"
              >
                {badge}
              </span>
            </span>
          </div>
          <div className="max-w-[453px]">
            <p
              className="font-sans text-[#4a5565] text-base leading-[24px]"
            >
              {description}
            </p>
            <div className="mt-6 border-b border-[#102443]/20" />
          </div>
        </div>

        {/* Watermark + Content overlapping layout */}
        <div className="relative">
          {/* Watermark text overlay */}
          <p
            className="font-heading text-[64px] sm:text-[96px] lg:text-[160px] leading-[0.8] tracking-[-1.83px] sm:tracking-[-4px] lg:tracking-[-6.4px] text-[rgba(32,38,43,0.04)] w-full select-none font-bold pointer-events-none mb-[60px] whitespace-pre-line"
            aria-hidden="true"
          >
            {watermarkText.replace(/\s+(?=[Tt]rust\b)/, '\n')}
          </p>

          {/* Content: Aid List + Charity Image — image overlaps watermark */}
          <div className="flex flex-row gap-6 items-end mt-[-60px] relative z-10">
            <div
              className="relative rounded-2xl overflow-hidden p-10 w-[526px] flex items-center"
              style={{
                background:
                  'radial-gradient(ellipse at 42% 84%, rgba(255,232,233,0) 0%, rgba(255,232,233,1) 100%), #fff',
              }}
            >
              <div className="relative z-10 flex flex-col gap-6 px-6">
                <p
                  className="font-sans text-[#101828] text-base font-medium leading-[24px] max-w-[358px]"
                >
                  {aidIntroText}
                </p>
                <div className="flex flex-col gap-4">
                  {aidItems.map((item, i) => (
                    <div key={i} className="flex items-center gap-6">
                      <img
                        src={aidBulletIcon}
                        alt=""
                        loading="lazy"
                        className="w-[17px] h-4 shrink-0"
                      />
                      <p
                        className="font-sans text-[#4a5565] text-base leading-[24px]"
                      >
                        {item}
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="flex-1 min-h-[460px] rounded-2xl overflow-hidden relative">
              <img
                key={safeActiveSlide}
                src={slides[safeActiveSlide]?.main}
                alt="MGM Charitable Trust activities"
                loading="lazy"
                className="absolute inset-0 w-full h-full object-cover rounded-2xl transition-opacity duration-300"
              />
              <div
                className="absolute inset-0 rounded-2xl"
                style={{
                  background: 'linear-gradient(179deg, rgba(0,0,0,0) 69%, rgba(0,0,0,0.5) 95%)',
                }}
              />
              {/* Thumbnails slider */}
              <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-2 z-10 w-[calc(100%-32px)] sm:w-auto max-w-[95%] justify-center">
                <button
                  onClick={() => scrollThumbs('left')}
                  disabled={thumbIndex === 0}
                  className={`w-7 h-7 rounded-full border border-white/60 flex items-center justify-center shrink-0 transition-all active:scale-95 ${thumbIndex === 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-80 hover:opacity-100'
                    }`}
                  aria-label="Previous thumbnails"
                >
                  <ChevronLeft size={16} strokeWidth={1.5} className="text-white" />
                </button>
                <div
                  ref={thumbScrollRef}
                  className="flex gap-3 overflow-hidden min-w-0"
                  style={{ width: '100%', maxWidth: `${VISIBLE_THUMBS * THUMB_CARD_WIDTH + (VISIBLE_THUMBS - 1) * THUMB_GAP}px` }}
                >
                  <div className="flex gap-3">
                    {slides.map((s, i) => (
                      <button
                        key={i}
                        onClick={() => handleThumbClick(i)}
                        className={`w-[120px] h-[72px] rounded-lg overflow-hidden border-2 shrink-0 transition-all ${i === safeActiveSlide ? 'border-white opacity-100 scale-105' : 'border-white/40 opacity-70 hover:opacity-90'
                          }`}
                      >
                        <img src={s.thumb} alt="" loading="lazy" className="w-full h-full object-cover" />
                      </button>
                    ))}
                  </div>
                </div>
                <button
                  onClick={() => scrollThumbs('right')}
                  disabled={thumbIndex >= maxThumbIndex}
                  className={`w-7 h-7 rounded-full border border-white/60 flex items-center justify-center shrink-0 transition-all active:scale-95 ${thumbIndex >= maxThumbIndex ? 'opacity-30 cursor-not-allowed' : 'opacity-80 hover:opacity-100'
                    }`}
                  aria-label="Next thumbnails"
                >
                  <ChevronRight size={16} strokeWidth={1.5} className="text-white" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      </div>
    </section>
  )
}
