"use client";

import React from "react";
import { useParallax } from "@/hooks/use-parallax";
import { ParallaxElement } from "../ParallaxElement";

interface ParallaxTextProps {
  text: string;
  speed?: number;
  direction?: "up" | "down" | "left" | "right";
  className?: string;
  splitBy?: "characters" | "words" | "lines";
  stagger?: number;
  element?: React.ElementType;
}

export const ParallaxText: React.FC<ParallaxTextProps> = ({
  text,
  speed = 0.1,
  direction = "up",
  className = "",
  splitBy = "words",
  stagger = 0.1,
  element,
}) => {
  if (splitBy === "characters") {
    const Element = element || "div";
    return (
      <Element className={`parallax-text inline-flex flex-wrap ${className}`}>
        {text.split("").map((char, index) => (
          <ParallaxCharacter
            key={index}
            char={char}
            speed={speed}
            direction={direction}
            index={index}
            stagger={stagger}
          />
        ))}
      </Element>
    );
  }

  if (splitBy === "words") {
    return (
      <div className={`parallax-text inline-flex flex-wrap ${className}`}>
        {text.split(" ").map((word, wordIndex) => (
          <span key={wordIndex} className="inline-flex mr-2 last:mr-0">
            {word.split("").map((char, charIndex) => (
              <ParallaxCharacter
                key={`${wordIndex}-${charIndex}`}
                char={char}
                speed={speed}
                direction={direction}
                index={wordIndex * 10 + charIndex}
                stagger={stagger}
              />
            ))}
          </span>
        ))}
      </div>
    );
  }

  return (
    <ParallaxElement speed={speed} direction={direction} className={className}>
      {text}
    </ParallaxElement>
  );
};

const ParallaxCharacter: React.FC<{
  char: string;
  speed: number;
  direction: string;
  index: number;
  stagger: number;
}> = ({ char, speed, direction, index, stagger }) => {
  const charRef = useParallax({
    speed: speed * (1 + index * stagger * 0.1),
    direction: direction as "up" | "down" | "left" | "right" | undefined,
  });

  return (
    <span
      ref={charRef as React.RefObject<HTMLSpanElement>}
      className="inline-block parallax-character"
      style={{ willChange: "transform" }}
    >
      {char === " " ? "\u00A0" : char}
    </span>
  );
};
