"use client";

import React, { useRef, useEffect } from "react";
import Image from "next/image";

interface Country {
  name: string;
  flag: string;
}

interface MarqueeRowProps {
  countries: Country[];
  reverse?: boolean;
}

const MarqueeRow: React.FC<MarqueeRowProps> = ({ countries, reverse = false }) => {
  const marqueeRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let scrollAmount = 0;
    const speed = 0.5;
    const element = marqueeRef.current;
    if (!element) return;
    let frameId: number;

    const scroll = () => {
      scrollAmount += reverse ? -speed : speed;
      element.scrollLeft = scrollAmount;

      if (!reverse && scrollAmount >= element.scrollWidth / 2) {
        scrollAmount = 0;
      }
      if (reverse && scrollAmount <= 0) {
        scrollAmount = element.scrollWidth / 2;
      }

      frameId = requestAnimationFrame(scroll);
    };

    frameId = requestAnimationFrame(scroll);

    return () => {
      if (frameId) cancelAnimationFrame(frameId);
    };
  }, [reverse]);

  return (
    <div className="overflow-hidden whitespace-nowrap w-full" ref={marqueeRef}>
      <div className="inline-flex gap-3 md:gap-4 px-2 md:px-4">
        {[...countries, ...countries].map((country, index) => (
          <div
            key={index}
            className="flex items-center gap-2 px-3 py-2 md:px-4 md:py-2 justify-between w-37.5 md:w-45 border border-gray-300 rounded-full text-xs md:text-sm bg-white shadow-sm"
          >
            <Image
              src={country.flag}
              alt={country.name + ' flag'}
              height="400"
              width="400"
              className="w-8 h-8 md:w-10 md:h-10 rounded-full object-cover"
              style={{ minWidth: 32, minHeight: 32 }}
            />
            <p className="text-[12px] sm:text-[12px] md:text-[14px] lg:text-[14px] xl:text-[14px] text-black font-normal">{country.name}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default MarqueeRow;