"use client"
import { useRef, useState, useCallback, useEffect } from 'react'
import type { AboutPastVenturesData } from '@/lib/strapi/types'

const MOBILE_CARD_WIDTH = 274
const MOBILE_CARD_GAP = 16

interface Venture {
  name: string
  description: string
  image: string
  logo: string
  logoBg: string
}

const FALLBACK_VENTURES: Venture[] = [
  {
    name: 'Marrybrown',
    description:
      "Marrybrown, a popular Malaysian QSR known for fried chicken and fusion meals, entered India in 1999 and has expanded to over 50 outlets across Tamil Nadu in 15 years.",
    image: '/assets/portfolio/Marrybrown .png',
    logo: '/assets/244717.svg',
    logoBg: '#ffffff',
  },
  {
    name: 'MGM Anand Transport',
    description:
      "MGM Anand Transport began in 1982 and grew into a private company by 2011, expanding into multi-modal logistics across India's major ports.",
    image: '/assets/portfolio/Anand Transport.JPG',
    logo: '/assets/portfolio/anand-transport-new-logo.png',
    logoBg: '#ffffff',
  },
  {
    name: 'MGM Housing & Real Estates',
    description:
      "MGM Housing & Real Estates Pvt. Ltd., established in 1988, marked the MGM Group's entry into real estate, focusing on land development and residential projects, expanding across key locations.",
    image: '/assets/portfolio/MGM Housing & Realestate.png',
    logo: '/assets/past ventures/MGM Housing & Real Estates-01.png',
    logoBg: '#ffffff',
  },
  {
    name: 'MGM Tyre Centre',
    description:
      "MGM Tyre Centre started in 1989 in T. Nagar, offering quality tyres and services, and became a trusted name before closing in 2012.",
    image: '/assets/portfolio/MGM Tyre Centre.png',
    logo: '/assets/past ventures/MGM Tyre Center-01.png',
    logoBg: '#ffffff',
  },
  {
    name: 'MGM International Imports and Exports',
    description:
      "Leading global trade operations that connect markets worldwide, driven by quality, trust, and strong international partnerships.",
    image: '/assets/portfolio/MGM International Imports & Exports Port.jpg',
    logo: '/assets/past ventures/mgm-imports-exports-logo-new.jpeg',
    logoBg: '#ffffff',
  },
  {
    name: 'MGM Selvee World',
    description:
      "A landmark entertainment venture that delights families and reflects MGM Group's dedication to creating memorable experiences.",
    image: '/assets/portfolio/MGM Selvee World.png',
    logo: '/assets/portfolio/selvee-logo-new.jpeg',
    logoBg: '#ffffff',
  },
  {
    name: 'FUN World',
    description:
      "Birthday celebrations, coin-operated machines. Mayaajal, Esphani Centre, Luz Corner, Abirami Hall.",
    image: '/assets/portfolio/Fun world.jpg',
    logo: '/assets/past ventures/Mgm Fun world Logo-01.png',
    logoBg: '#ffffff',
  },
]

export default function PastVentures({ data }: { data: AboutPastVenturesData }) {
  const badge = data.badge || 'Past Ventures'
  const badgeIcon = data.badgeIcon || '/assets/leaders/sparkle-icon.svg'
  const description = data.description || 'Pioneering initiatives that shaped our diversified portfolio'
  const ventures: Venture[] =
    data.ventures.length > 0
      ? data.ventures.map((v) => ({
          name: v.name,
          description: v.description,
          image: v.image,
          logo: v.logo,
          logoBg: '#ffffff',
        }))
      : FALLBACK_VENTURES
  const TOTAL_MOBILE_PAGES = Math.max(1, Math.ceil(ventures.length / 2))

  const scrollRef = useRef<HTMLDivElement>(null)
  const [activeIndex, setActiveIndex] = useState(0)

  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return
    const pageWidth = (MOBILE_CARD_WIDTH + MOBILE_CARD_GAP) * 2
    const page = Math.round(scrollRef.current.scrollLeft / pageWidth)
    setActiveIndex(Math.min(page, TOTAL_MOBILE_PAGES - 1))
  }, [])

  useEffect(() => {
    const el = scrollRef.current
    if (!el) return
    el.addEventListener('scroll', handleScroll, { passive: true })
    return () => el.removeEventListener('scroll', handleScroll)
  }, [handleScroll])

  const scrollToPage = useCallback(
    (direction: 'prev' | 'next') => {
      if (!scrollRef.current) return
      const pageWidth = (MOBILE_CARD_WIDTH + MOBILE_CARD_GAP) * 2
      const newPage =
        direction === 'next'
          ? Math.min(activeIndex + 1, TOTAL_MOBILE_PAGES - 1)
          : Math.max(activeIndex - 1, 0)
      scrollRef.current.scrollTo({ left: newPage * pageWidth, behavior: 'smooth' })
      setActiveIndex(newPage)
    },
    [activeIndex]
  )

  return (
    <section className="py-16 lg:py-24">
      <div className="w-full px-[20px] lg:px-[72px]"><div className="max-w-[1297px] mx-auto">
        {/* Header: Badge + Description */}
        <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-[20px] lg:gap-6 mb-[32px] lg:mb-14">
          {/* Badge */}
          <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>

          {/* Description */}
          <div className="max-w-[350px] flex flex-col gap-[16px] lg:gap-0">
            <p className="font-sans font-medium text-base text-[#102443]/60 leading-[1.5]">
              {description}
            </p>
            <div className="lg:mt-6 border-b border-[#102443]/20" />
          </div>
        </div>
      </div></div>

      {/* Mobile: Horizontal scrollable cards */}
      <div className="lg:hidden">
        <div
          ref={scrollRef}
          className="flex gap-[16px] overflow-x-auto pl-[20px] pr-0 pb-4"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
        >
          {ventures.map((venture) => (
            <div
              key={venture.name}
              className="rounded-[16px] overflow-hidden border border-[rgba(229,231,235,0.5)] flex-shrink-0 w-[274px]"
              style={{ background:
                  'radial-gradient(ellipse at bottom left, rgba(255,232,233,1), rgba(255,232,233,0) 60%), linear-gradient(90deg, #fff 0%, #fff 100%)',
              }}
            >
              <div className="relative h-[182px] overflow-hidden p-[16px]">
                <img
                  src={venture.image}
                  alt={venture.name}
                  loading="lazy"
                  className="absolute inset-0 w-full h-full object-cover"
                />
                {venture.logo ? (
                  <div
                    className="relative z-10 w-[54px] h-[54px] rounded-[8px] overflow-hidden"
                    style={{ backgroundColor: venture.logoBg }}
                  >
                    <img
                      src={venture.logo}
                      alt={`${venture.name} logo`}
                      loading="lazy"
                      className={`w-full h-full object-contain ${
                        venture.name === 'Marrybrown' ? 'p-2' :
                        venture.name === 'MGM International Imports and Exports' ? 'p-2' : ''
                      }`}
                    />
                  </div>
                ) : (
                  <div className="relative z-10 w-[54px] h-[54px] rounded-[8px] bg-white" />
                )}
              </div>
              <div className="px-[16px] py-[20px] flex flex-col gap-[8px]">
                <h3
                  className="text-[20px] font-bold text-[#102443] leading-normal"
                >
                  {venture.name}
                </h3>
                <p
                  className="text-[14px] font-normal text-[rgba(16,36,67,0.4)] leading-[20px]"
                >
                  {venture.description}
                </p>
              </div>
            </div>
          ))}
        </div>

        {/* Progress dots + Navigation arrows */}
        <div className="flex items-center justify-end px-[20px] mt-4">
          <div className="flex gap-[13px] items-center">
            <button
              onClick={() => scrollToPage('prev')}
              className={`flex items-center justify-center w-[44px] h-[44px] rounded-full border-2 border-[#d20010] bg-transparent pl-[2px] ${activeIndex === 0 ? 'opacity-50' : 'opacity-100'
                }`}
              aria-label="Previous ventures"
              disabled={activeIndex === 0}
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <path d="M15 6L9 12L15 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              onClick={() => scrollToPage('next')}
              className={`flex items-center justify-center w-[44px] h-[44px] rounded-full border-2 border-[#d20010] bg-transparent pl-[2px] ${activeIndex === TOTAL_MOBILE_PAGES - 1 ? 'opacity-50' : 'opacity-100'
                }`}
              aria-label="Next ventures"
              disabled={activeIndex === TOTAL_MOBILE_PAGES - 1}
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <path d="M9 6L15 12L9 18" stroke="#d20010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* Desktop: Grid cards */}
      <div className="hidden lg:block px-[72px]"><div className="max-w-[1297px] mx-auto">
        <div className="grid grid-cols-3 gap-6">
          {ventures.map((venture, index) => (
            <div
              key={venture.name}
              className={`rounded-2xl overflow-hidden border border-gray-200/50 ${
                index === ventures.length - 1 && ventures.length % 3 === 1 ? 'col-start-2' : ''
              }`}
              style={{ background:
                  'radial-gradient(ellipse at bottom left, rgba(255,232,233,1), rgba(255,232,233,0) 60%), linear-gradient(90deg, #fff 0%, #fff 100%)',
              }}
            >
              <div className="relative h-[278px] overflow-hidden p-6">
                <img
                  src={venture.image}
                  alt={venture.name}
                  loading="lazy"
                  className="absolute inset-0 w-full h-full object-cover"
                />
                {venture.logo ? (
                  <div
                    className="relative z-10 w-[88px] h-[88px] rounded-2xl overflow-hidden"
                    style={{ backgroundColor: venture.logoBg }}
                  >
                    <img
                      src={venture.logo}
                      alt={`${venture.name} logo`}
                      loading="lazy"
                      className={`w-full h-full object-contain ${
                        venture.name === 'Marrybrown' ? 'p-3' :
                        venture.name === 'MGM International Imports and Exports' ? 'p-2' : ''
                      }`}
                    />
                  </div>
                ) : (
                  <div className="relative z-10 w-[88px] h-[88px] rounded-2xl bg-white" />
                )}
              </div>
              <div className="px-6 pt-6 pb-6">
                <h3 className="font-heading font-bold text-[#102443] text-2xl leading-normal mb-3">
                  {venture.name}
                </h3>
                <p className="font-sans font-normal text-base text-[#102443]/40 leading-[20px]">
                  {venture.description}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div></div>
    </section>
  )
}
