"use client"
import { useState, useRef, useCallback, useEffect } from 'react'
import type { AboutFounderData } from '@/lib/strapi/types'

interface FounderSlide {
  badge: string
  badgeIcon: string
  bio: string[]
  watermark: string
  image: string
  quote: string
  quoteAttribution: string
}

const FALLBACK_SLIDES: FounderSlide[] = [
  {
    badge: 'About the founder',
    badgeIcon: '/assets/leaders/sparkle-icon.svg',
    bio: [
      'Chevalier Dr. Manuel Gnana Muthu (MGM) was born on 2nd April 1935 in Tirunelveli, TamilNadu, as the second son of Mr.Manuel and Mrs.Rajalakshmi. He began his career at the Chennai Port in 1957 and later founded the MGM Group of Companies, which started with logistics and hospitality and grew into areas like Coal and Mineral Mining, Food Chains, International Trading, Housing, Distilleries, IMFS, and the famous MGM Dizzee World theme park in Chennai.',
      'Known for his business skills and commitment to social causes, Dr. Muthu has worked to support the underprivileged and shared his journey in his autobiography, "Rags to Riches: Chevalier Seva Ratna Dr. M. G. Muthu" (1999). He was also honored with the Chevalier Virudhu Award.',
    ],
    watermark: 'About The Founder',
    image: '/assets/home/our leader/MG Muthu Founder Profile.webp',
    quote:
      'Truth, Hard work, Simplicity, Honesty and Faith" - These are the five golden tenets which the Founder - Chairman of the Group followed strictly. The Five Golden Mantras are the five Towers of the Group`s victory.',
    quoteAttribution: '- An excerpt from his autobiography',
  },
  {
    badge: 'About Vice Chairman',
    badgeIcon: '/assets/leaders/sparkle-icon.svg',
    bio: [
      'Mr. MGM Maran, also known as Nesamani Maran Muthu, is the Vice Chairman of the MGM Group of Companies, a leading conglomerate based in Chennai. Known for his strategic insight and progressive leadership, he has played a key role in expanding the Group\'s presence across multiple industries. With a strong foundation in values such as integrity, innovation, and social responsibility, he continues to strengthen the organization\'s legacy. Mr. Maran is recognized for his people-centric approach and commitment to sustainable growth. His leadership continues to guide the MGM Group toward long-term success on both national and global platforms. ',
    ],
    watermark: 'Vision For The Future',
    image: '/assets/mgm-maran-new.png',
    quote:
      '"The foundation we build today will determine the heights we reach tomorrow. Let every brick be laid with honesty and every pillar stand on truth."',
    quoteAttribution: '- Mr. MGM Maran',
  },
  {
    badge: 'About Group Managing Director',
    badgeIcon: '/assets/leaders/sparkle-icon.svg',
    bio: [
      'Mr. MGM Anand Muthu is a prominent Indian business leader and the Managing Director of the MGM Group of Companies, headquartered in Chennai. With over two decades of experience, he has been instrumental in expanding the group\'s presence across South India while upholding its strong legacy. As the son of visionary founder Dr. M.G. Muthu, he continues to build on values of integrity, discipline, and innovation. Under his leadership, the group has diversified into hospitality, entertainment, logistics, and manufacturing. Anand Muthu is known for his strategic vision, operational expertise, and commitment to sustainable growth and long-term business excellence.',
    ],
    watermark: 'Legacy Of Excellence',
    image: '/assets/home/our leader/MGM Anand Profile.webp?v=2',
    quote:
      '"A work of real merit finds success at last, as we have found. Nothing succeeds like success…"',
    quoteAttribution: '-Mr. MGM Anand Muthu',
  },
]

export default function FounderSection({ data }: { data: AboutFounderData }) {
  const [activeSlide, setActiveSlide] = useState(0)
  const slides = data.slides.length > 0 ? data.slides : FALLBACK_SLIDES
  const safeActive = slides.length > 0 ? Math.min(activeSlide, slides.length - 1) : 0
  const slide = slides[safeActive]
  const totalSlides = slides.length

  const touchStartX = useRef(0)
  const touchEndX = useRef(0)

  const handlePrev = useCallback(() => {
    setActiveSlide((prev) => (prev > 0 ? prev - 1 : prev))
  }, [])

  const handleNext = useCallback(() => {
    setActiveSlide((prev) => (prev < totalSlides - 1 ? prev + 1 : prev))
  }, [totalSlides])

  const isSwiping = useRef(false)

  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX
    touchEndX.current = e.touches[0].clientX
    isSwiping.current = false
  }

  const handleTouchMove = (e: React.TouchEvent) => {
    touchEndX.current = e.touches[0].clientX
    isSwiping.current = true
  }

  const handleTouchEnd = () => {
    if (!isSwiping.current) return
    const diff = touchStartX.current - touchEndX.current
    if (Math.abs(diff) > 50) {
      diff > 0 ? handleNext() : handlePrev()
    }
  }

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft') handlePrev()
      if (e.key === 'ArrowRight') handleNext()
    }
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [handlePrev, handleNext])

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search)
      const slideParam = params.get('slide')
      if (slideParam !== null) {
        const slideIndex = parseInt(slideParam, 10)
        if (!isNaN(slideIndex) && slideIndex >= 0 && slideIndex < totalSlides) {
          window.setTimeout(() => setActiveSlide(slideIndex), 0)
          
          // Smooth scroll to the section in case the user clicked from another page
          // Give it a small timeout to ensure the DOM is ready and page has rendered
          setTimeout(() => {
            const el = document.getElementById('founder-section')
            if (el) {
               const y = el.getBoundingClientRect().top + window.scrollY - 100
               window.scrollTo({ top: y, behavior: 'smooth' })
            }
          }, 100)
        }
      }
    }
  }, [totalSlides])

  if (!slide) return null

  return (
    <div id="founder-section" className="w-full px-5 lg:px-[72px]"><div className="max-w-[1297px] mx-auto">
      {/* ===== MOBILE ===== */}
      <div
        className="lg:hidden flex flex-col gap-5 pb-16"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {/* Main content area */}
        <div className="flex flex-col items-start pb-10">
          {/* Image + watermark grid (overlapping) */}
          <div
            className="inline-grid mb-[-80px] w-full"
            style={{ gridTemplateColumns: '1fr',
              gridTemplateRows: 'max-content',
              marginTop: activeSlide === 0 ? '-12px' : undefined,
            }}
          >
            {/* Watermark text */}
            <p
              className="font-heading text-[14vw] md:text-[24vw] leading-[0.8] tracking-[-2px] text-[rgba(32,38,43,0.04)] w-full select-none font-black text-right pointer-events-none break-words"
              style={{ gridColumn: 1,
                gridRow: 1,
                marginTop: '-45px',
                zIndex: 0,
              }}
              aria-hidden="true"
            >
              {slide.watermark}
            </p>
            {/* Founder image */}
            <div
              style={{ gridColumn: 1,
                gridRow: 1,
                width: '229px',
                height: '259px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <div>
                <div className="overflow-hidden" style={{ width: '229px', height: '259px' }}>
                  <img
                    src={slide.image}
                    alt="Founder portrait"
                    className="w-full h-full object-cover"
                    loading="lazy"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Red gradient card */}
          <div
            className="relative z-[1] flex flex-col gap-[18px] items-start rounded-2xl"
            style={{ width: '100%',
              minHeight: '660px',
              padding: '24px',
              background: 'linear-gradient(139deg, rgb(156, 29, 53) 16.7%, rgb(210, 0, 16) 95.2%)',
            }}
          >
            {/* Badge */}
            <div
              className="bg-white flex gap-2 items-center rounded-[66px] shrink-0 max-w-full"
              style={{ padding: '12px 24px' }}
            >
              <img src={slide.badgeIcon} alt="" className="w-[17px] h-4 shrink-0" loading="lazy" />
              <p
                 className="font-heading text-[#102443] text-[14px] sm:text-[16px] uppercase leading-[1.2] break-words"
              >
                {slide.badge}
              </p>
            </div>

            {/* Quote card + Bio wrapper */}
            <div className="flex flex-col gap-5 items-start relative w-full">
              {/* Quote card */}
              <div
                className="relative flex flex-col gap-4 items-start rounded-2xl w-full"
                style={{
                  maxWidth: '311px',
                  borderLeft: '6.4px solid #8b2e40',
                  padding: '20px 24px',
                  background: 'radial-gradient(ellipse at 42% 84%, #ffffff 0%, #ebebeb 100%)',
                }}
              >
                <p
                  className="text-[#102443] text-[12px] font-normal leading-[24px]"
                >
                  {slide.quote}
                </p>
                <p
                  className="text-[12px] font-normal leading-[22px]"
                  style={{ color: 'rgba(16, 36, 67, 0.7)' }}
                >
                  {slide.quoteAttribution}
                </p>
              </div>

              {/* Bio text */}
              <div
                className="text-white text-[13px] font-medium whitespace-pre-wrap"
              >
                {slide.bio.map((paragraph, i) => (
                  <p key={i} className="leading-[1.5]" style={{ marginBottom: i < slide.bio.length - 1 ? 0 : undefined }}>
                    {paragraph}
                    {i < slide.bio.length - 1 && (
                      <>
                        {'\n'}
                        <span className="block">&nbsp;</span>
                      </>
                    )}
                  </p>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Navigation */}
        <div className="flex items-center justify-end" style={{ width: '353px', maxWidth: '100%' }}>
          <div className="flex items-center gap-[13px]">
            <button
              onClick={handlePrev}
              disabled={activeSlide === 0}
              className={`flex items-center justify-center rounded-[66px] border-2 transition-opacity ${activeSlide === 0 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] opacity-50 hover:opacity-100'}`}
              style={{ width: '44px', height: '44px', paddingLeft: '2px' }}
              aria-label="Previous slide"
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" className="rotate-180">
                <path d="M9.5 6L15.5 12L9.5 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              onClick={handleNext}
              disabled={activeSlide === totalSlides - 1}
              className={`flex items-center justify-center rounded-[66px] border-2 transition-all ${activeSlide === totalSlides - 1 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] group'}`}
              style={{ width: '44px', height: '44px', paddingLeft: '2px' }}
              aria-label="Next slide"
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <path d="M9.5 6L15.5 12L9.5 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* ===== DESKTOP ===== */}
      <div
        className="hidden lg:flex lg:flex-col lg:gap-4 lg:items-start"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {/* Main content grid */}
        <div className="inline-grid" style={{ gridTemplateColumns: 'max-content', gridTemplateRows: 'max-content' }}>
          {/* Red gradient card — left */}
          <div
            className="flex flex-col items-start justify-between gap-6 rounded-2xl"
            style={{ gridColumn: 1,
              gridRow: 1,
              width: '606px',
              minHeight: '660px',
              marginTop: '13px',
              padding: '32px',
              background: 'linear-gradient(154deg, rgb(156, 29, 53) 16.7%, rgb(210, 0, 16) 95.2%)',
            }}
          >
            {/* Badge */}
            <div
              className="bg-white flex gap-2 items-center rounded-[66px] shrink-0 max-w-full"
              style={{ padding: '12px 24px' }}
            >
              <img src={slide.badgeIcon} alt="" className="w-[17px] h-4 shrink-0" loading="lazy" />
              <p
                 className="font-heading text-[#102443] text-[16px] uppercase leading-[1.2] break-words"
              >
                {slide.badge}
              </p>
            </div>

            {/* Bio text */}
            <div
              className="font-sans text-white text-[16px] font-medium whitespace-pre-wrap"
            >
              {slide.bio.map((paragraph, i) => (
                <p key={i} className="leading-[1.5]" style={{ marginBottom: i < slide.bio.length - 1 ? 0 : undefined }}>
                  {paragraph}
                  {i < slide.bio.length - 1 && (
                    <>
                      {'\n'}
                      <span className="block">&nbsp;</span>
                    </>
                  )}
                </p>
              ))}
            </div>
          </div>

          {/* Right side — watermark + image + quote */}
          <div
            className="relative inline-grid"
            style={{ gridColumn: 1,
              gridRow: 1,
              marginLeft: '616px',
              gridTemplateColumns: 'max-content',
              gridTemplateRows: 'max-content',
            }}
          >
            {/* Watermark text */}
            <p
              className="font-heading text-[160px] leading-[0.8] tracking-[-6.4px] text-[rgba(32,38,43,0.04)] w-[680px] select-none font-bold pointer-events-none"
              style={{ gridColumn: 1,
                gridRow: 1,
              }}
              aria-hidden="true"
            >
              {slide.watermark}
            </p>

            {/* Founder image */}
            <div
              className="flex items-center justify-center"
              style={{ gridColumn: 1,
                gridRow: 1,
                width: '477px',
                height: '541px',
                marginLeft: '20px',
                marginTop: '26px',
              }}
            >
              <div>
                <div className="overflow-hidden" style={{ width: '477px', height: '541px' }}>
                  <img
                    src={slide.image}
                    alt="Founder portrait"
                    className="w-full h-full object-cover"
                    loading="lazy"
                  />
                </div>
              </div>
            </div>

            {/* Quote card */}
            <div
              className="relative flex flex-col gap-4 items-start rounded-2xl"
              style={{ gridColumn: 1,
                gridRow: 1,
                width: '573px',
                height: '202px',
                marginLeft: '92px',
                marginTop: '408px',
                borderLeft: '6.4px solid #9c1d35',
                padding: '35px 24px 24px 24px',
                background: 'radial-gradient(ellipse at 42% 84%, #ffffff 0%, #ebebeb 100%)',
              }}
            >
              {/* Decorative quote marks */}
              <p
                className="absolute select-none pointer-events-none"
                style={{ fontFamily: "'Times New Roman', serif",
                  fontStyle: 'italic',
                  fontSize: '430px',
                  lineHeight: 0.7,
                  letterSpacing: '-34.4px',
                  left: '320px',
                  top: '-69px',
                  width: '215px',
                  height: '125px',
                  background: 'linear-gradient(to top, rgba(255,255,255,0.2), rgba(255,255,255,0))',
                  WebkitBackgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                }}
                aria-hidden="true"
              >
                {"'" + "'"}
              </p>
              <p
                className="font-sans text-[#102443] text-[14px] font-normal leading-[28px]"
              >
                {slide.quote}
              </p>
              <p
                className="font-sans text-[16px] font-normal leading-[22px]"
                style={{ color: 'rgba(16, 36, 67, 0.7)' }}
              >
                {slide.quoteAttribution}
              </p>
            </div>
          </div>
        </div>

        {/* Navigation */}
        <div className="flex items-center justify-end w-full">
          <div className="flex gap-2 items-center">
            <button
              onClick={handlePrev}
              disabled={activeSlide === 0}
              className={`flex items-center justify-center rounded-[66px] border-2 transition-opacity ${activeSlide === 0 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] opacity-50 hover:opacity-100'}`}
              style={{ width: '60px', height: '58px', paddingLeft: '2px' }}
              aria-label="Previous slide"
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" className="rotate-180">
                <path d="M9.5 6L15.5 12L9.5 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              onClick={handleNext}
              disabled={activeSlide === totalSlides - 1}
              className={`flex items-center justify-center rounded-[66px] border-2 transition-all ${activeSlide === totalSlides - 1 ? 'border-[#d20010] opacity-30 cursor-not-allowed' : 'border-[#d20010] group'}`}
              style={{ width: '60px', height: '58px', paddingLeft: '2px' }}
              aria-label="Next slide"
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <path d="M9.5 6L15.5 12L9.5 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
         </div>
       </div>
      </div>
    </div>
  )
}

