"use client"
import { useRef, useState, useCallback, useEffect } from 'react'
import { ChevronLeft, ChevronRight, X } from 'lucide-react'
import type { AwardsData, AwardData } from '@/lib/strapi/types'

interface AwardsSectionProps {
  data: AwardsData
}

const leafImage = 'https://www.figma.com/api/mcp/asset/d06ba0d1-b5c1-4aa7-a02b-3f8b99006ab4'

export default function AwardsSection({ data }: AwardsSectionProps) {
  const awards = data.awards
  const scrollRef = useRef<HTMLDivElement>(null)
  const [atStart, setAtStart] = useState(true)
  const [atEnd, setAtEnd] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  const [selectedAward, setSelectedAward] = useState<AwardData | null>(null)

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 800)
    check()
    window.addEventListener('resize', check)
    return () => window.removeEventListener('resize', check)
  }, [])

  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return
    const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current
    setAtStart(scrollLeft < 2)
    setAtEnd(scrollLeft + clientWidth >= scrollWidth - 2)
  }, [])

  const scroll = useCallback(
    (direction: 'left' | 'right') => {
      if (!scrollRef.current) return
      const cardWidth = isMobile ? 260 : 416
      const gap = isMobile ? 16 : 30
      const scrollAmount = cardWidth + gap
      scrollRef.current.scrollBy({
        left: direction === 'right' ? scrollAmount : -scrollAmount,
        behavior: 'smooth',
      })
    },
    [isMobile]
  )

  useEffect(() => {
    handleScroll()
  }, [handleScroll])

  return (
    <section className="relative bg-white py-16 lg:py-20 overflow-hidden">
      {/* Header: Badge + Description (constrained width) */}
      <div className="w-full max-w-[1297px] mx-auto px-5 lg:px-5 relative">
        {/* Desktop Watermark Background Text */}
        <div className="hidden lg:block absolute left-[0px] top-[100px] pointer-events-none select-none z-0 overflow-visible max-w-full">
          <p className="font-heading font-bold text-[140px] leading-[0.75] tracking-[-4px] text-[rgba(16,36,67,0.08)] m-0 w-auto whitespace-nowrap">
            {(data.watermarkLines ?? ['Awards &', 'Recognitions']).map((line, i) => (
              <span key={i} className="block">{line}</span>
            ))}
          </p>
        </div>

        <div className="relative z-10">
          <div className="flex flex-col gap-5 lg:gap-6 lg:flex-row lg:items-start lg:justify-between mb-0 lg:mb-64">
            {/* Badge */}
            <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 shrink-0"
                />
                <span className="font-heading text-black text-base uppercase leading-tight sm:leading-none whitespace-normal sm:whitespace-nowrap">
                  {data.header.badge || 'Awards & Recognitions'}
                </span>
              </span>
            </div>

            {/* Description */}
            <div className="flex flex-col gap-4 lg:gap-6 lg:max-w-[524px]">
              <p className="font-sans font-medium text-base leading-[1.5] text-[rgba(35,35,35,0.6)]">
                {data.header.description}
              </p>
              <div className="w-full border-t border-[rgba(16,36,67,0.2)]" />
            </div>
          </div>
        </div>

        {/* Mobile Watermark Background Text */}
        <div className="lg:hidden mt-8 mb-[-90px] pb-[20px] pointer-events-none select-none z-0 overflow-hidden max-w-full">
          <p className="font-heading font-bold text-[50px] leading-[0.75] tracking-[-1.83px] text-[rgba(16,36,67,0.08)] m-0 w-[353px] max-w-[100vw] whitespace-nowrap">
            {(data.watermarkLines ?? ['Awards &', 'Recognitions']).map((line, i) => (
              <span key={i} className="block">{line}</span>
            ))}
          </p>
        </div>

      </div>

      {/* Awards Carousel — left aligned with max-w container, extends to right edge */}
      <div className="relative z-10 mt-[100px] lg:mt-0">
        <div className="flex flex-col gap-6">
          <div
            ref={scrollRef}
            onScroll={handleScroll}
            className="flex gap-4 lg:gap-[30px] overflow-x-auto overflow-y-hidden scrollbar-hide py-4 -my-4 pl-5 pr-0 lg:pl-[max(20px,calc((100vw-1297px)/2+20px))] lg:pr-0"
          >
            {awards.map((award, idx) => (
              <div
                key={idx}
                onClick={() => setSelectedAward(award)}
                className="flex-shrink-0 w-[260px] lg:w-[416px] h-auto min-h-[282px] lg:min-h-[336px] pb-6 rounded-2xl overflow-hidden bg-[#f9f9f9] flex flex-col items-center cursor-pointer transition-transform hover:scale-[1.02]"
              >
                {/* Award image with decorative leaves */}
                <div className="relative mt-[20px] w-[220px] h-[160px] lg:w-[250px] lg:h-[170px] overflow-hidden shrink-0">
                  {/* Center award image */}
                  <div className="absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2 w-[160px] h-[160px] lg:w-[170px] lg:h-[170px]">
                    <img
                      src={award.image}
                      alt={award.title}
                      loading="lazy"
                      className="w-full h-full object-contain pointer-events-none"
                    />
                  </div>
                  {/* Right leaf decoration */}
                  <div className="absolute right-0 top-0 w-[54px] h-[120px] overflow-hidden pointer-events-none">
                    <img
                      src={leafImage}
                      alt=""
                      loading="lazy"
                      className="absolute h-[110%] left-[-121.39%] max-w-none top-[-5%] w-[220.56%] object-contain"
                    />
                  </div>
                  {/* Left leaf decoration (mirrored) */}
                  <div className="absolute left-[3px] top-0 w-[54px] h-[120px] -scale-y-100 rotate-180 overflow-hidden pointer-events-none">
                    <img
                      src={leafImage}
                      alt=""
                      loading="lazy"
                      className="absolute h-[110%] left-[-121.39%] max-w-none top-[-5%] w-[220.56%] object-contain"
                    />
                  </div>
                </div>

                {/* Text content */}
                <div className="mt-[5px] lg:mt-[10px] flex flex-col gap-3 items-center w-full px-4 shrink-0">
                  {award.year && (
                    <p className="font-sans font-normal text-[16px] text-[#4a5565] leading-[24px] whitespace-nowrap">
                      {award.year}
                    </p>
                  )}
                  <p className="font-heading font-bold text-[24px] text-[#102443] leading-normal text-center break-words">
                    {award.title}
                  </p>
                </div>
              </div>
            ))}
          </div>

          {/* Progress indicators + Navigation arrows */}
          <div className="flex items-center justify-end px-5 lg:px-[max(20px,calc((100vw-1297px)/2+20px))]">
            {/* Navigation Arrows */}
            <div className="flex gap-[13px] lg:gap-2 items-center">
              <button
                onClick={() => scroll('left')}
                disabled={atStart}
                className={`w-[44px] h-[44px] lg:w-[60px] lg:h-[58px] rounded-full border-2 lg:border border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${atStart ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'}`}
                aria-label="Previous award"
              >
                <ChevronLeft size={24} strokeWidth={2} className="text-[#d20010]" />
              </button>
              <button
                onClick={() => scroll('right')}
                disabled={atEnd}
                className={`w-[44px] h-[44px] lg:w-[60px] lg:h-[58px] rounded-full border-2 lg:border border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${atEnd ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'}`}
                aria-label="Next award"
              >
                <ChevronRight size={24} strokeWidth={2} className="text-[#d20010]" />
              </button>
            </div>
          </div>
        </div>
      </div>
      {/* Award Modal */}
      {selectedAward && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
          onClick={() => setSelectedAward(null)}
        >
          <div
            className="relative bg-white rounded-2xl max-w-[90vw] max-h-[90vh] w-[500px] lg:w-[600px] overflow-hidden shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Close button */}
            <button
              onClick={() => setSelectedAward(null)}
              className="absolute top-4 right-4 z-10 w-10 h-10 rounded-full bg-white/80 hover:bg-white flex items-center justify-center transition-colors shadow-md"
              aria-label="Close modal"
            >
              <X size={20} className="text-[#102443]" />
            </button>

            {/* Award image */}
            <div className="flex items-center justify-center pt-10 pb-6 px-6 bg-[#f9f9f9]">
              <div className="relative w-[280px] h-[280px] lg:w-[350px] lg:h-[350px]">
                {/* Left leaf */}
                <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[80px] h-[180px] -scale-y-100 rotate-180 overflow-hidden pointer-events-none">
                  <img
                    src={leafImage}
                    alt=""
                    className="absolute h-[110%] left-[-121.39%] max-w-none top-[-5%] w-[220.56%] object-contain"
                  />
                </div>
                {/* Center image */}
                <img
                  src={selectedAward.image}
                  alt={selectedAward.title}
                  className="w-full h-full object-contain"
                />
                {/* Right leaf */}
                <div className="absolute right-0 top-1/2 -translate-y-1/2 w-[80px] h-[180px] overflow-hidden pointer-events-none">
                  <img
                    src={leafImage}
                    alt=""
                    className="absolute h-[110%] left-[-121.39%] max-w-none top-[-5%] w-[220.56%] object-contain"
                  />
                </div>
              </div>
            </div>

            {/* Text content */}
            <div className="flex flex-col items-center gap-2 py-6 px-6">
              {selectedAward.year && (
                <p className="font-sans font-normal text-[16px] text-[#4a5565] leading-[24px]">
                  {selectedAward.year}
                </p>
              )}
              <p className="font-heading font-bold text-[28px] lg:text-[32px] text-[#102443] leading-normal text-center">
                {selectedAward.title}
              </p>
            </div>
          </div>
        </div>
      )}
    </section>
  )
}
