
"use client";

import React, { useEffect, useState } from "react";
import "./animated-scroll.css";

interface AnimatedScrollProps {
  items?: string[];
  textColor?: string;
}

const defaultItems = [
  "NEW REALITY FOR YOUR CHILD",
  "GREAT OPPORTUNITIES",
  "TEAMWORK",
  "NEW REALITY FOR YOUR CHILD",
  "GREAT OPPORTUNITIES",
  "TEAMWORK",
];

const AnimatedScroll = ({
  items = defaultItems,
  textColor = "#0097dc",
}: AnimatedScrollProps) => {
  const [isRTL, setIsRTL] = useState(false);

  useEffect(() => {
    const detectDirection = () => {
      const htmlDir = document.documentElement.getAttribute("dir");
      const bodyDir = document.body.getAttribute("dir");

      const rtl =
        htmlDir?.toLowerCase() === "rtl" ||
        bodyDir?.toLowerCase() === "rtl" ||
        document.documentElement.dir?.toLowerCase() === "rtl" ||
        document.body.dir?.toLowerCase() === "rtl";

      setIsRTL(rtl);
    };

    detectDirection();

    // Detect direction changes when the language changes.
    const observer = new MutationObserver(detectDirection);

    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["dir", "lang"],
    });

    observer.observe(document.body, {
      attributes: true,
      attributeFilter: ["dir"],
    });

    return () => observer.disconnect();
  }, []);

  // Repeat the items to create a seamless loop.
  const loopItems = [...items, ...items, ...items];

  return (
    <div
      className={`marquee relative w-full overflow-hidden bg-transparent py-4 pt-6 ${
        isRTL ? "marquee-rtl" : "marquee-ltr"
      }`}
      dir={isRTL ? "rtl" : "ltr"}
    >
      <div
        className="marquee-track flex items-center whitespace-nowrap"
        dir="ltr"
      >
        {loopItems.map((text, index) => (
          <React.Fragment key={`${index}-${text}`}>
            <span
              dir="auto"
              style={{ color: textColor }}
              className="marquee-text mx-4 text-lg font-bold uppercase tracking-wide"
            >
              {text}
            </span>

            <span
              aria-hidden="true"
              style={{ backgroundColor: textColor }}
              className="marquee-dot mx-4 inline-block h-2.5 w-2.5 shrink-0 rounded-full"
            />
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

export default AnimatedScroll;
