'use client';

import { useState, useEffect, useRef, useCallback } from 'react';

export interface RollingItem {
  label: string;
  value: string;
  color?: 'default' | 'green' | 'blue' | 'red' | 'orange';
}

interface RollingTextProps {
  items: RollingItem[];
  globalTick: number;
}

const valueColorMap: Record<string, string> = {
  default: 'text-foreground font-bold',
  green: 'text-green-600 font-bold',
  blue: 'text-blue-600 font-bold',
  red: 'text-red-600 font-bold',
  orange: 'text-orange-600 font-bold',
};

export function RollingText({ items, globalTick }: RollingTextProps) {
  const [displayIndex, setDisplayIndex] = useState(() =>
    items.length > 0 ? globalTick % items.length : 0,
  );
  const [isAnimating, setIsAnimating] = useState(false);
  const isPausedRef = useRef(false);
  const displayIndexRef = useRef(displayIndex);

  useEffect(() => {
    if (items.length <= 1) return;
    if (isPausedRef.current) return;

    const targetIndex = globalTick % items.length;
    if (targetIndex === displayIndexRef.current) return;

    setIsAnimating(true);
    const timeout = setTimeout(() => {
      setDisplayIndex(targetIndex);
      displayIndexRef.current = targetIndex;
      setIsAnimating(false);
    }, 300);

    return () => clearTimeout(timeout);
  }, [globalTick, items.length]);

  const handleMouseEnter = useCallback(() => {
    isPausedRef.current = true;
  }, []);

  const handleMouseLeave = useCallback(() => {
    isPausedRef.current = false;
    const targetIndex = globalTick % items.length;
    setDisplayIndex(targetIndex);
    displayIndexRef.current = targetIndex;
  }, [globalTick, items.length]);

  if (items.length === 0) return null;

  const item = items[displayIndex];

  return (
    <span
      className={`inline-flex items-center gap-1.5 text-sm transition-all duration-300 cursor-default ${
        isAnimating ? 'opacity-0 translate-y-1' : 'opacity-100 translate-y-0'
      }`}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <span className="text-muted-foreground">{item.label}</span>
      <span className={valueColorMap[item.color ?? 'default']}>{item.value}</span>
    </span>
  );
}
