import { useEffect, useRef, useState } from 'react'
import { clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'

function cn(...inputs: Parameters<typeof clsx>) {
  return twMerge(clsx(inputs))
}

export interface MovingCardItem {
  quote: string
  name:  string
  title: string
  level?: 'critical' | 'high' | 'medium' | 'low' | 'opportunity'
}

interface InfiniteMovingCardsProps {
  items:      MovingCardItem[]
  direction?: 'left' | 'right'
  speed?:     'fast' | 'normal' | 'slow'
  pauseOnHover?: boolean
  className?: string
}

const levelConfig = {
  critical:    { dot: '#7f1d1d', label: 'بحرانی',   text: '#7f1d1d',        bg: 'rgba(127,29,29,0.08)'   },
  high:        { dot: '#9b1c1c', label: 'بالا',      text: '#9b1c1c',        bg: 'rgba(155,28,28,0.07)'   },
  medium:      { dot: '#92400e', label: 'متوسط',     text: '#92400e',        bg: 'rgba(146,64,14,0.07)'   },
  low:         { dot: '#166534', label: 'پایین',     text: '#166534',        bg: 'rgba(22,101,52,0.07)'   },
  opportunity: { dot: '#1e40af', label: 'فرصت',      text: '#1e40af',        bg: 'rgba(30,64,175,0.07)'   },
}

export function InfiniteMovingCards({
  items,
  direction     = 'left',
  speed         = 'slow',
  pauseOnHover  = true,
  className,
}: InfiniteMovingCardsProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const scrollerRef  = useRef<HTMLUListElement>(null)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    if (!containerRef.current || !scrollerRef.current) return

    /* Clone items for seamless loop */
    const items = Array.from(scrollerRef.current.children)
    items.forEach(item => {
      const clone = item.cloneNode(true)
      scrollerRef.current!.appendChild(clone)
    })

    /* Set CSS custom properties */
    const dur = speed === 'fast' ? '25s' : speed === 'normal' ? '45s' : '70s'
    containerRef.current.style.setProperty('--animation-duration',  dur)
    containerRef.current.style.setProperty('--animation-direction',
      direction === 'right' ? 'reverse' : 'forwards')

    setReady(true)
  }, [direction, speed])

  return (
    <div
      ref={containerRef}
      className={cn('relative overflow-hidden', className)}
      style={{
        /* Fade masks on both edges */
        WebkitMaskImage:
          'linear-gradient(to right, transparent 0%, black 8%, black 92%, transparent 100%)',
        maskImage:
          'linear-gradient(to right, transparent 0%, black 8%, black 92%, transparent 100%)',
      }}
    >
      <ul
        ref={scrollerRef}
        className={cn(
          'flex min-w-full shrink-0 gap-5 w-max flex-nowrap',
          ready && 'animate-scroll',
          pauseOnHover && 'hover:[animation-play-state:paused]',
        )}
        style={{ direction: 'ltr' }}   /* keep scroll direction LTR regardless of page RTL */
      >
        {items.map((item, idx) => {
          const cfg = item.level ? levelConfig[item.level] : levelConfig.high
          return (
            <li
              key={idx}
              style={{
                width:        340,
                flexShrink:   0,
                background:   'var(--paper)',
                border:       '1px solid var(--rule-thin)',
                borderTop:    `3px solid ${cfg.dot}`,
                padding:      '28px 28px 24px',
                direction:    'rtl',
                fontFamily:   'Vazir, sans-serif',
                position:     'relative',
              }}
            >
              {/* Level badge */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 14 }}>
                <div style={{
                  width: 7, height: 7, borderRadius: '50%',
                  background: cfg.dot, flexShrink: 0,
                }} />
                <span style={{
                  fontSize: 9, fontWeight: 700, letterSpacing: '2px',
                  textTransform: 'uppercase', color: cfg.dot,
                }}>
                  {cfg.label}
                </span>
              </div>

              {/* Quote / description */}
              <p style={{
                fontSize:     13.5,
                lineHeight:   1.85,
                color:        'var(--ink-2)',
                fontWeight:   300,
                marginBottom: 20,
              }}>
                {item.quote}
              </p>

              {/* Footer */}
              <div style={{
                paddingTop:  14,
                borderTop:   '1px solid var(--rule-thin)',
                display:     'flex',
                justifyContent: 'space-between',
                alignItems:  'center',
              }}>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>
                    {item.name}
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--ink-5)' }}>
                    {item.title}
                  </div>
                </div>
                <div style={{
                  fontSize: 9, fontWeight: 700, letterSpacing: '1px',
                  textTransform: 'uppercase', color: cfg.text,
                  background: cfg.bg,
                  padding: '4px 10px',
                }}>
                  {cfg.label}
                </div>
              </div>
            </li>
          )
        })}
      </ul>
    </div>
  )
}
