import { useEffect, useRef, useState } from "react";
import { motion } from "motion/react";
import "./TrueFocus.css";

interface TrueFocusProps {
  sentence?: string;
  separator?: string;
  manualMode?: boolean;
  blurAmount?: number;
  borderColor?: string;
  glowColor?: string;
  animationDuration?: number;
  pauseBetweenAnimations?: number;
  className?: string;
}

interface FocusRect { x: number; y: number; width: number; height: number; }

const TrueFocus: React.FC<TrueFocusProps> = ({
  sentence = "True Focus",
  separator = " ",
  manualMode = false,
  blurAmount = 5,
  borderColor = "oklch(0.5 0.22 285)",
  glowColor = "oklch(0.68 0.2 295 / 0.6)",
  animationDuration = 0.5,
  pauseBetweenAnimations = 1,
  className,
}) => {
  const words = sentence.split(separator);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [lastActiveIndex, setLastActiveIndex] = useState<number | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const wordRefs = useRef<(HTMLSpanElement | null)[]>([]);
  const [focusRect, setFocusRect] = useState<FocusRect>({ x: 0, y: 0, width: 0, height: 0 });

  useEffect(() => {
    if (!manualMode) {
      const interval = setInterval(() => {
        setCurrentIndex((p) => (p + 1) % words.length);
      }, (animationDuration + pauseBetweenAnimations) * 1000);
      return () => clearInterval(interval);
    }
  }, [manualMode, animationDuration, pauseBetweenAnimations, words.length]);

  useEffect(() => {
    if (currentIndex < 0) return;
    const el = wordRefs.current[currentIndex];
    if (!el || !containerRef.current) return;
    const parent = containerRef.current.getBoundingClientRect();
    const rect = el.getBoundingClientRect();
    setFocusRect({ x: rect.left - parent.left, y: rect.top - parent.top, width: rect.width, height: rect.height });
  }, [currentIndex, words.length]);

  return (
    <div className={`focus-container ${className ?? ""}`} ref={containerRef}>
      {words.map((word, index) => {
        const isActive = index === currentIndex;
        return (
          <span
            key={index}
            ref={(el) => { if (el) wordRefs.current[index] = el; }}
            className={`focus-word ${manualMode ? "manual" : ""} ${isActive && !manualMode ? "active" : ""}`}
            style={{
              filter: isActive ? "blur(0px)" : `blur(${blurAmount}px)`,
              transition: `filter ${animationDuration}s ease`,
              ["--border-color" as any]: borderColor,
              ["--glow-color" as any]: glowColor,
            }}
            onMouseEnter={() => { if (manualMode) { setLastActiveIndex(index); setCurrentIndex(index); } }}
            onMouseLeave={() => { if (manualMode) setCurrentIndex(lastActiveIndex ?? 0); }}
          >
            {word}
          </span>
        );
      })}
      <motion.div
        className="focus-frame"
        animate={{ x: focusRect.x, y: focusRect.y, width: focusRect.width, height: focusRect.height, opacity: currentIndex >= 0 ? 1 : 0 }}
        transition={{ duration: animationDuration }}
        style={{ ["--border-color" as any]: borderColor, ["--glow-color" as any]: glowColor }}
      >
        <span className="corner top-left"></span>
        <span className="corner top-right"></span>
        <span className="corner bottom-left"></span>
        <span className="corner bottom-right"></span>
      </motion.div>
    </div>
  );
};

export default TrueFocus;