import React, { useRef, useEffect } from 'react';
import { gsap } from '../../lib/gsap.ts';
import { useReducedMotion } from '../../hooks/useReducedMotion.ts';

interface SplitHeadlineProps {
  text: string;
  className?: string;
  as?: 'h1' | 'h2' | 'h3';
}

export const SplitHeadline: React.FC<SplitHeadlineProps> = ({ text, className, as: Tag = 'h1' }) => {
  const ref = useRef<HTMLHeadingElement>(null);
  const reduced = useReducedMotion();

  useEffect(() => {
    if (reduced || !ref.current) return;
    const chars = ref.current.querySelectorAll('.split-char');
    gsap.fromTo(
      chars,
      { y: 40, opacity: 0, filter: 'blur(8px)' },
      { y: 0, opacity: 1, filter: 'blur(0px)', duration: 0.8, stagger: 0.03, ease: 'power3.out' }
    );
  }, [reduced]);

  const splitText = text.split('').map((char, i) => (
    <span key={i} className="split-char inline-block">
      {char === ' ' ? '\u00A0' : char}
    </span>
  ));

  return (
    <Tag ref={ref} className={className}>
      {splitText}
    </Tag>
  );
};