import React from 'react';
import { useCurrentFrame, interpolate, spring, useVideoConfig } from 'remotion';

interface Props {
  text: string;
  delay?: number;
  style?: React.CSSProperties;
  staggerMs?: number;
}

// Animates each word in individually
export const AnimatedHeadline: React.FC<Props> = ({ text, delay = 0, style = {}, staggerMs = 3 }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const words = text.split(' ');

  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25em 0.2em', ...style }}>
      {words.map((word, i) => {
        const wordDelay = delay + i * staggerMs;
        const progress = spring({
          frame: frame - wordDelay,
          fps,
          config: { damping: 16, stiffness: 150, mass: 0.6 },
        });
        const opacity = interpolate(frame - wordDelay, [0, 10], [0, 1], {
          extrapolateLeft: 'clamp',
          extrapolateRight: 'clamp',
        });
        const translateY = interpolate(progress, [0, 1], [50, 0]);
        return (
          <span
            key={i}
            style={{
              display: 'inline-block',
              opacity,
              transform: `translateY(${translateY}px)`,
              overflow: 'hidden',
            }}
          >
            {word}
          </span>
        );
      })}
    </div>
  );
};
