"use client"
import { useRef, useCallback, useState, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { BusinessPortfolioData } from '@/lib/strapi/types'

interface BusinessPortfolioProps {
  data: BusinessPortfolioData
}

const MOBILE_CARD_GAP = 16
const DESKTOP_CARD_GAP = 24

export default function BusinessPortfolio({ data }: BusinessPortfolioProps) {
  const businesses = data.businesses
  const scrollRef = useRef<HTMLDivElement>(null)
  const [activePageIndex, setActivePageIndex] = useState(0)
  const [atStart, setAtStart] = useState(true)
  const [atEnd, setAtEnd] = useState(false)
  const rafRef = useRef<number | null>(null)
  const prevPageRef = useRef(0)

  const getCardWidth = useCallback(() => {
    if (!scrollRef.current) return 274
    return scrollRef.current.querySelector<HTMLElement>('[data-card]')?.offsetWidth || 274
  }, [])

  const scroll = useCallback((direction: 'left' | 'right') => {
    if (!scrollRef.current) return
    const cardWidth = getCardWidth()
    const scrollAmount = cardWidth + DESKTOP_CARD_GAP
    scrollRef.current.scrollBy({
      left: direction === 'right' ? scrollAmount : -scrollAmount,
      behavior: 'smooth',
    })
  }, [getCardWidth])

  const updateScrollState = useCallback(() => {
    if (!scrollRef.current) return
    const { scrollLeft } = scrollRef.current
    const isDesktop = window.innerWidth >= 800
    const gap = isDesktop ? DESKTOP_CARD_GAP : MOBILE_CARD_GAP
    const cardWidth = getCardWidth()
    const pageWidth = cardWidth + gap

    // Use the first card's position as baseline to account for left padding offset
    const firstCard = scrollRef.current.querySelector<HTMLElement>('[data-card]')
    const cardStartOffset = firstCard ? firstCard.offsetLeft : 0
    const adjustedScroll = Math.max(0, scrollLeft - cardStartOffset)

    const totalPages = businesses.length
    const rawPage = adjustedScroll / pageWidth
    const page = Math.max(0, Math.min(Math.round(rawPage), totalPages - 1))

    if (page !== prevPageRef.current) {
      prevPageRef.current = page
      setActivePageIndex(page)
    }

    const { scrollWidth, clientWidth } = scrollRef.current
    setAtStart(adjustedScroll < 2)
    setAtEnd(scrollLeft + clientWidth >= scrollWidth - 2)
  }, [getCardWidth])

  const handleScroll = useCallback(() => {
    if (rafRef.current != null) return
    rafRef.current = requestAnimationFrame(() => {
      rafRef.current = null
      updateScrollState()
    })
  }, [updateScrollState])

  const handleResize = useCallback(() => {
    handleScroll()
  }, [handleScroll])

  useEffect(() => {
    const el = scrollRef.current
    if (!el) return
    updateScrollState()
    el.addEventListener('scroll', handleScroll, { passive: true })
    window.addEventListener('resize', handleResize)
    return () => {
      el.removeEventListener('scroll', handleScroll)
      window.removeEventListener('resize', handleResize)
      if (rafRef.current != null) {
        cancelAnimationFrame(rafRef.current)
        rafRef.current = null
      }
    }
  }, [handleScroll, handleResize, updateScrollState])

  const isDragging = useRef(false)
  const startX = useRef(0)
  const scrollStartLeft = useRef(0)

  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (!scrollRef.current) return
    isDragging.current = true
    startX.current = e.pageX - scrollRef.current.offsetLeft
    scrollStartLeft.current = scrollRef.current.scrollLeft
    scrollRef.current.style.cursor = 'grabbing'
  }, [])

  const handleMouseUp = useCallback(() => {
    isDragging.current = false
    if (scrollRef.current) scrollRef.current.style.cursor = 'grab'
  }, [])

  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    if (!isDragging.current || !scrollRef.current) return
    e.preventDefault()
    const x = e.pageX - scrollRef.current.offsetLeft
    const walk = (x - startX.current) * 1.5
    scrollRef.current.scrollLeft = scrollStartLeft.current - walk
  }, [])

  return (
    <section id="companies" className="relative pb-20 lg:pb-20 overflow-hidden" style={{ background: 'linear-gradient(180deg, #2A3036 0%, #3D454C 25%, #656C72 50%, #CFD9E8 75%, #FFFFFF 100%)' }}>

      {/* Header: Badge + Description */}
      <div className="relative z-10 w-full max-w-[1297px] mx-auto px-5 lg:px-0 pt-16 lg:pt-24">
        <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-5 lg:gap-6 mb-6 lg:mb-14">
          {/* 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"
              />
              <span className="font-heading text-black text-base uppercase leading-none">
                {data.header.badge || 'Our Past Ventures'}
              </span>
            </span>
          </div>

          {/* Description */}
          <div className="max-w-full lg:max-w-[524px]">
            <p
              className="font-sans font-medium text-base leading-[1.5]"
              style={{ color: 'rgba(255, 255, 255, 0.60)',
              }}
            >
              {data.header.description}
            </p>
            <div className="mt-4 lg:mt-6 border-b border-[rgba(255,255,255,0.20)]" />
          </div>
        </div>
      </div>

      {/* Cards Carousel - starts inside max-width, extends to right viewport edge */}
      <div className="relative z-10 w-full max-w-[1297px] mx-auto px-5 lg:px-0">
        <div
          ref={scrollRef}
          className="flex gap-4 lg:gap-6 overflow-x-auto scrollbar-hide cursor-grab snap-x snap-mandatory lg:scroll-smooth"
          style={{ marginRight: 'calc(-1 * max(20px, (100vw - 1297px) / 2))' }}
          onMouseDown={handleMouseDown}
          onMouseUp={handleMouseUp}
          onMouseMove={handleMouseMove}
          onMouseLeave={handleMouseUp}
        >
          {businesses.map((biz) => (
            <div
              key={biz.name}
              data-card
              className="flex-shrink-0 w-[277px] lg:w-[416px] rounded-2xl overflow-hidden border border-[rgba(229,231,235,0.5)] snap-start snap-always"
              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%)',
              }}
            >
              {/* Image area */}
              <div className="relative h-[182px] lg:h-[278px] overflow-hidden p-4 lg:p-6">
                <img
                  src={biz.image}
                  alt={biz.name}
                  className="absolute inset-0 w-full h-full object-cover"
                  loading="lazy"
                  draggable={false}
                />
                {/* Subtle overlay on image area */}
                <div className="absolute inset-0 bg-gray-200/50" style={{ mixBlendMode: 'multiply' }} />
                {/* Logo */}
                {biz.logo && (
                  <div
                    className="relative z-10 w-[54px] h-[54px] lg:w-[88px] lg:h-[88px] rounded-lg lg:rounded-2xl overflow-hidden"
                    style={{ backgroundColor: biz.logoBg }}
                  >
                    <img
                      src={biz.logo}
                      alt={`${biz.name} logo`}
                      loading="lazy"
                      className={`w-full h-full object-contain ${
                        biz.name === 'Marrybrown' ? 'p-2 lg:p-3' :
                        biz.name === 'MGM International Imports and Exports' ? 'p-2' : ''
                      }`}
                      draggable={false}
                    />
                  </div>
                )}
                {!biz.logo && (
                  <div className="relative z-10 w-[54px] h-[54px] lg:w-[88px] lg:h-[88px] rounded-lg lg:rounded-2xl bg-white" />
                )}
              </div>

              {/* Text area */}
              <div className="px-4 py-5 lg:px-6 lg:py-6">
                <h3 className="font-heading font-bold text-[#102443] text-[20px] lg:text-2xl leading-normal mb-2 lg:mb-3">
                  {biz.name}
                </h3>
                <p className="font-sans font-normal text-sm lg:text-base text-[rgba(16,36,67,0.4)] leading-[20px]">
                  {biz.description}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Progress Bars + Navigation Arrows */}
      <div className="relative z-10 mt-6 lg:mt-8 max-w-[1297px] mx-auto px-5 lg:px-0">
        <div className="flex items-center justify-end pb-4 lg:pb-0">

          <div className="flex gap-2 items-center flex-shrink-0">
            <button
              onClick={() => scroll('left')}
              disabled={atStart}
              className={`w-[44px] h-[44px] lg:w-[60px] lg:h-[58px] rounded-full border-2 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 business"
            >
              <ChevronLeft size={20} strokeWidth={1.5} 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 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 business"
            >
              <ChevronRight size={20} strokeWidth={1.5} className="text-[#d20010]" />
            </button>
          </div>
        </div>
      </div>
    </section>
  )
}
