"use client"
import Link from 'next/link'
import { useState, useCallback, useEffect, useRef } from 'react'
import { useDragScroll } from '../hooks/useDragScroll'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { LeadershipData } from '@/lib/strapi/types'

interface LeadershipSectionProps {
  data: LeadershipData
}

const MOBILE_CARD_GAP = 16
const DESKTOP_CARD_GAP = 34

export default function LeadershipSection({ data }: LeadershipSectionProps) {
  const leaders = data.leaders
  const { scrollRef, handlers } = useDragScroll()
  const [activePageIndex, setActivePageIndex] = useState(0)
  const scrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const prevPageRef = useRef(0)
  const cardWidthRef = useRef(274)

  const updatePage = useCallback(() => {
    if (!scrollRef.current) return
    const scrollLeft = scrollRef.current.scrollLeft
    const gap = window.innerWidth >= 800 ? DESKTOP_CARD_GAP : MOBILE_CARD_GAP
    const pageWidth = cardWidthRef.current + gap
    const totalPages = leaders.length
    const page = Math.max(0, Math.min(Math.round(scrollLeft / pageWidth), totalPages - 1))

    if (page !== prevPageRef.current) {
      prevPageRef.current = page
      setActivePageIndex(page)
    }
  }, [scrollRef])

  const handleScroll = useCallback(() => {
    if (scrollTimerRef.current != null) clearTimeout(scrollTimerRef.current)
    scrollTimerRef.current = setTimeout(() => {
      scrollTimerRef.current = null
      updatePage()
    }, 150)
  }, [updatePage])

  useEffect(() => {
    const el = scrollRef.current
    if (!el) return
    const card = el.querySelector<HTMLElement>('[data-leader-card]')
    if (card) cardWidthRef.current = card.offsetWidth
    updatePage()
    el.addEventListener('scroll', handleScroll, { passive: true })
    window.addEventListener('resize', handleScroll)
    return () => {
      el.removeEventListener('scroll', handleScroll)
      window.removeEventListener('resize', handleScroll)
      if (scrollTimerRef.current != null) {
        clearTimeout(scrollTimerRef.current)
        scrollTimerRef.current = null
      }
    }
  }, [scrollRef, handleScroll, updatePage])

  const scrollToCard = useCallback((direction: 'left' | 'right') => {
    if (!scrollRef.current) return
    const el = scrollRef.current
    const gap = window.innerWidth >= 800 ? DESKTOP_CARD_GAP : MOBILE_CARD_GAP
    const scrollAmount = cardWidthRef.current + gap
    const maxScroll = el.scrollWidth - el.clientWidth
    const target = direction === 'right'
      ? Math.min(el.scrollLeft + scrollAmount, maxScroll)
      : Math.max(el.scrollLeft - scrollAmount, 0)
    el.scrollTo({ left: target, behavior: 'smooth' })
  }, [scrollRef])

  return (
    <section id="leadership" className="relative bg-white overflow-hidden py-16 lg:py-20 lg:px-5">
      <div className="max-w-[1297px] mx-auto px-5 lg:px-0 relative">
        {/* Desktop Watermark Background Text */}
        <div
          className="hidden lg:block absolute pointer-events-none select-none -left-2 top-[45px] z-0 overflow-visible max-w-full"
          aria-hidden="true"
        >
          <p
            className="font-heading font-bold leading-[0.75] tracking-[-4px] text-[140px] text-[rgba(16,36,67,0.13)] m-0 w-auto break-words"
          >
            {(data.watermarkLines ?? ['Leaders At', 'MGM']).map((line, i) => (
              <span key={i} className="block">{line}</span>
            ))}
          </p>
        </div>

        {/* Content */}
        <div className="relative z-10">
          {/* Top Section: Badge + Description */}
          <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-5 lg:gap-6 mb-0 lg:mb-[140px]">
            {/* Left: 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 || 'Our leadership'}
                </span>
              </span>
            </div>

            {/* Right: Description */}
            <div className="max-w-full lg:max-w-[524px]">
              <p className="font-sans font-medium text-base text-[rgba(35,35,35,0.6)] lg:text-[rgba(16,36,67,0.6)] leading-[1.5]">
                {data.header.description}
              </p>
              <div className="mt-4 lg:mt-6 border-b border-[rgba(16,36,67,0.2)]" />
            </div>
          </div>

          {/* Mobile Watermark Background Text */}
          <div
            className="lg:hidden mt-8 mb-[-70px] pointer-events-none select-none z-0 overflow-hidden max-w-full"
            aria-hidden="true"
          >
            <p
              className="font-heading font-bold leading-[0.75] tracking-[-1.83px] text-[50px] text-[rgba(16,36,67,0.13)] m-0 w-[353px] max-w-[100vw] break-words"
            >
              {(data.watermarkLines ?? ['Leaders At', 'MGM']).map((line, i) => (
                <span key={i} className="block">{line}</span>
              ))}
            </p>
          </div>

          {/* Leader Cards Carousel */}
          <div className="mt-[100px] lg:mt-0 relative z-10">
            <div
              ref={scrollRef}
              className="flex gap-4 lg:gap-[34px] overflow-x-auto overflow-y-hidden scrollbar-hide cursor-grab active:cursor-grabbing lg:cursor-default -mr-5 lg:mr-0 relative z-10 snap-x snap-mandatory lg:overflow-x-visible"
              onMouseDown={handlers.onMouseDown}
              onMouseUp={handlers.onMouseUp}
              onMouseMove={handlers.onMouseMove}
              onMouseLeave={handlers.onMouseUp}
            >
              {leaders.map((leader, index) => (
                <Link
                  href={`/about?slide=${index}`}
                  key={`${leader.name}-${index}`}
                  data-leader-card
                  className="flex flex-col shrink-0 w-[274px] lg:w-[400px] gap-5 bg-white relative snap-start lg:snap-align-none cursor-pointer group"
                >
                  <div className="relative z-20 w-full h-[280px] lg:h-[336px] rounded-[10px] border border-[#d1d5dc] overflow-hidden bg-[#E5E7EB] transition-transform duration-300 group-hover:shadow-lg">
                    <img
                      src={leader.image}
                      alt={leader.name}
                      loading="lazy"
                      draggable={false}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                      style={{ objectPosition: 'center top' }}
                    />
                  </div>
                  <div className="flex flex-col gap-1 bg-white">
                    <h3 className="font-heading font-bold text-[20px] lg:text-2xl text-[#102443] leading-normal m-0 group-hover:text-[#d20010] transition-colors">
                      {leader.name}
                    </h3>
                    <p className="font-sans text-base text-[rgba(16,36,67,0.4)] leading-[20px] m-0">
                      {leader.title}
                    </p>
                  </div>
                </Link>
              ))}
            </div>

            {/* Progress Bars + Navigation Arrows (mobile only) */}
            <div className="flex lg:hidden items-center justify-end w-full mt-6">
              <div className="flex gap-2 items-center">
                <button
                  onClick={() => scrollToCard('left')}
                  disabled={activePageIndex === 0}
                  className={`w-[44px] h-[44px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${
                    activePageIndex === 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'
                  }`}
                  aria-label="Previous leader"
                >
                  <ChevronLeft size={20} strokeWidth={1.5} className="text-[#d20010]" />
                </button>
                <button
                  onClick={() => scrollToCard('right')}
                  disabled={activePageIndex === leaders.length - 1}
                  className={`w-[44px] h-[44px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${
                    activePageIndex === leaders.length - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'
                  }`}
                  aria-label="Next leader"
                >
                  <ChevronRight size={20} strokeWidth={1.5} className="text-[#d20010]" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
