import React from 'react';
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from 'remotion';
import {
  CaptionsData,
  getCurrentSegment,
  getCurrentWordIndex,
} from '../utils/captions';

interface SubtitlesProps {
  captions: CaptionsData;
  highlightColor?: string;
  normalColor?: string;
  fontSize?: number;
}

/**
 * 逐字高亮字幕组件
 * 根据时间戳逐字高亮显示字幕（无背景，纯文字描边）
 */
export const Subtitles: React.FC<SubtitlesProps> = ({
  captions,
  highlightColor = '#FFFF00',
  normalColor = '#FFFFFF',
  fontSize = 52,
}) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  const currentTimeInSeconds = frame / fps;

  // 获取当前段落
  const currentSegment = getCurrentSegment(captions, currentTimeInSeconds);

  if (!currentSegment || currentSegment.words.length === 0) {
    return null;
  }

  // 获取当前高亮字的索引
  const currentWordIndex = getCurrentWordIndex(currentSegment, currentTimeInSeconds);

  return (
    <AbsoluteFill
      style={{
        justifyContent: 'flex-end',
        alignItems: 'center',
        paddingBottom: '6%',
      }}
    >
      <p
        style={{
          margin: 0,
          fontSize: `${fontSize}px`,
          fontFamily: '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif',
          fontWeight: 800,
          lineHeight: 1.4,
          textAlign: 'center',
          maxWidth: '90%',
          wordBreak: 'keep-all',
          letterSpacing: '2px',
        }}
      >
        {currentSegment.words.map((word, index) => {
          const isHighlighted = index <= currentWordIndex;
          return (
            <span
              key={`${word.word}-${index}`}
              style={{
                color: isHighlighted ? highlightColor : normalColor,
                textShadow: `
                  -3px -3px 0 #000,
                  3px -3px 0 #000,
                  -3px 3px 0 #000,
                  3px 3px 0 #000,
                  0 0 12px rgba(0,0,0,0.9),
                  0 4px 8px rgba(0,0,0,0.6)
                `,
                transition: 'color 0.05s ease',
              }}
            >
              {word.word}
            </span>
          );
        })}
      </p>
    </AbsoluteFill>
  );
};
