/**
 * AnimatedText Component
 *
 * Text with word emphasis capability and fade-in animation.
 */

import React from 'react';
import { interpolate, useCurrentFrame } from 'remotion';
import { darkPalette } from '../lib/colors';

type AnimatedTextProps = {
  text: string;
  emphasis?: string[];
  className?: string;
  style?: React.CSSProperties;
  fadeInDuration?: number;
};

export const AnimatedText: React.FC<AnimatedTextProps> = ({
  text,
  emphasis = [],
  className,
  style,
  fadeInDuration = 15,
}) => {
  const frame = useCurrentFrame();

  // Ensure fadeInDuration is at least 1 to avoid monotonically increasing error
  const effectiveDuration = Math.max(1, fadeInDuration);
  const opacity = fadeInDuration === 0
    ? 1
    : interpolate(frame, [0, effectiveDuration], [0, 1], {
        extrapolateRight: 'clamp',
      });

  // Build segments for emphasis matching (handles multi-word phrases)
  const segments: { text: string; isEmphasis: boolean }[] = [];
  let currentText = text;

  // Sort emphasis by length (longest first) to match longer phrases first
  const sortedEmphasis = [...emphasis].sort((a, b) => b.length - a.length);

  for (const emp of sortedEmphasis) {
    const lowerEmp = emp.toLowerCase();
    const lowerCurrent = currentText.toLowerCase();
    const index = lowerCurrent.indexOf(lowerEmp);

    if (index !== -1) {
      // Add text before emphasis
      if (index > 0) {
        segments.push({ text: currentText.slice(0, index), isEmphasis: false });
      }
      // Add emphasis text
      segments.push({
        text: currentText.slice(index, index + emp.length),
        isEmphasis: true,
      });
      // Continue with remaining text
      currentText = currentText.slice(index + emp.length);
    }
  }

  // Add any remaining text
  if (currentText) {
    segments.push({ text: currentText, isEmphasis: false });
  }

  // If no emphasis found, just use the original text
  const finalSegments = segments.length > 0 ? segments : [{ text, isEmphasis: false }];

  return (
    <span className={className} style={{ ...style, opacity }}>
      {finalSegments.map((segment, i) => (
        <span
          key={i}
          style={{
            color: segment.isEmphasis ? darkPalette.accent : 'inherit',
            fontWeight: segment.isEmphasis ? 600 : 'inherit',
          }}
        >
          {segment.text}
        </span>
      ))}
    </span>
  );
};
