import React, { useState, useEffect, useRef } from 'react';
import { Link2, Settings2, Sparkles, Download, Play, Pause, Square, FileText, ChevronDown, ChevronUp, RefreshCw, Music, Languages, Mic, Edit3, Scissors, Film, Type, Loader2, Volume2 } from 'lucide-react';
import { downloadApi, processApi, jobsApi, bgmApi, fontsApi, thumbnailApi } from '../api/client';
import PipelineView from '../components/PipelineView';
import SubtitleEditor from '../components/SubtitleEditor';
import VideoPreview from '../components/VideoPreview';
import ManualSubtitleInput from '../components/ManualSubtitleInput';
import VideoTrimmer from '../components/VideoTrimmer';

const TRANSLATION_MODES = [
  { id: 'direct', name: '직역', desc: '원본 구조 유지하며 번역' },
  { id: 'summarize', name: '요약', desc: '핵심 내용만 추출' },
  { id: 'rewrite', name: '재구성', desc: '자연스러운 한국어로 완전 재작성 (권장)' },
];

const SUBTITLE_POSITIONS = [
  { id: 'bottom', name: '하단' },
  { id: 'center', name: '중앙' },
  { id: 'top', name: '상단' },
];

const ANIMATIONS = [
  { id: 'none', name: '없음' },
  { id: 'fade', name: '페이드' },
  { id: 'pop', name: '팝업' },
];

export default function HomePage() {
  const [url, setUrl] = useState('');
  const [currentJob, setCurrentJob] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [bgmList, setBgmList] = useState([]);
  const [fontList, setFontList] = useState([]);
  const [showSettings, setShowSettings] = useState(false);

  // 결과 드롭다운 상태
  const [showTranscript, setShowTranscript] = useState(false);
  const [showTranslation, setShowTranslation] = useState(false);
  const [showBgmSelect, setShowBgmSelect] = useState(false);
  const [isReprocessing, setIsReprocessing] = useState(false);
  const [editingTranscript, setEditingTranscript] = useState(false);
  const [showTrimmer, setShowTrimmer] = useState(false);

  // Intro text overlay (shown at beginning of video for YouTube Shorts thumbnail)
  const [introText, setIntroText] = useState('');
  const [introDuration, setIntroDuration] = useState(0.7);
  const [introFontSize, setIntroFontSize] = useState(100);
  const [isGeneratingIntroText, setIsGeneratingIntroText] = useState(false);

  // Processing options
  const [selectedBgm, setSelectedBgm] = useState(null);
  const [bgmVolume, setBgmVolume] = useState(0.3);

  // BGM Preview
  const [playingBgmId, setPlayingBgmId] = useState(null);
  const audioRef = useRef(null);
  const [isDownloadingBgm, setIsDownloadingBgm] = useState(false);
  const [translationMode, setTranslationMode] = useState('rewrite');
  const [keepOriginalAudio, setKeepOriginalAudio] = useState(false);
  const [useVocalSeparation, setUseVocalSeparation] = useState(false); // Disabled by default - causes false positives

  // Subtitle style - 중앙 위치, 폰트 72로 기본 설정
  const [subtitleStyle, setSubtitleStyle] = useState({
    font_name: 'Pretendard',
    font_size: 72,
    font_color: '#FFFFFF',
    outline_color: '#000000',
    outline_width: 3,
    position: 'center',
    bold: true,
    shadow: 1,
    background_box: false,
    animation: 'fade',
  });

  // Load BGM list and auto-select first BGM
  useEffect(() => {
    const loadAndSelectBgm = async () => {
      try {
        const res = await bgmApi.list();
        const bgms = res.data;
        setBgmList(bgms);

        // 자동으로 첫 번째 BGM 선택
        if (bgms.length > 0 && !selectedBgm) {
          setSelectedBgm(bgms[0].id);
          console.log('Auto-selected BGM:', bgms[0].name);
        } else if (bgms.length === 0) {
          // BGM이 없으면 자동 다운로드
          console.log('No BGM found, auto-downloading...');
          try {
            const downloadRes = await bgmApi.autoDownload(['upbeat', 'energetic', 'short'], 60);
            if (downloadRes.data.success) {
              const downloadedBgm = downloadRes.data.downloaded;
              setBgmList([{
                id: downloadedBgm.id,
                name: downloadedBgm.name,
                duration: downloadedBgm.duration,
                path: downloadedBgm.path,
              }]);
              setSelectedBgm(downloadedBgm.id);
              console.log('Auto-downloaded BGM:', downloadedBgm.name);
            }
          } catch (err) {
            console.log('BGM auto-download failed:', err.message);
          }
        }
      } catch (err) {
        console.error('Failed to load BGM list:', err);
      }
    };
    loadAndSelectBgm();
  }, []);

  // Load fonts list
  useEffect(() => {
    const loadFonts = async () => {
      try {
        const res = await fontsApi.list();
        setFontList(res.data.fonts || []);
      } catch (err) {
        console.error('Failed to load fonts:', err);
      }
    };
    loadFonts();
  }, []);

  // BGM Preview: Cleanup audio when component unmounts
  useEffect(() => {
    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
    };
  }, []);

  // Toggle BGM preview playback
  const toggleBgmPreview = (bgm) => {
    // If same BGM is playing, stop it
    if (playingBgmId === bgm.id) {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
      setPlayingBgmId(null);
      return;
    }

    // Stop any currently playing audio
    if (audioRef.current) {
      audioRef.current.pause();
    }

    // Create new audio and play (preview at lower volume)
    const audio = new Audio(bgm.path);
    audio.volume = 0.15; // Fixed low volume for preview (15%)
    audio.onended = () => {
      setPlayingBgmId(null);
      audioRef.current = null;
    };
    audio.play().catch(err => {
      console.error('Failed to play BGM:', err);
      setPlayingBgmId(null);
    });

    audioRef.current = audio;
    setPlayingBgmId(bgm.id);
  };

  // Stop BGM preview
  const stopBgmPreview = () => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current = null;
    }
    setPlayingBgmId(null);
  };

  // Download more BGM tracks from Freesound
  const handleDownloadMoreBgm = async () => {
    setIsDownloadingBgm(true);
    setError(null);
    try {
      // Search categories for diverse BGM
      const categories = ['upbeat music', 'chill background', 'happy music', 'cinematic'];
      let downloadedCount = 0;

      for (const category of categories) {
        try {
          // Auto-download from Freesound (CC0 license)
          const res = await bgmApi.autoDownload([category], 120);
          if (res.data.success) {
            downloadedCount++;
            console.log(`Downloaded: ${res.data.downloaded?.name}`);
          }
        } catch (e) {
          console.log(`Category ${category} failed:`, e.message);
        }
      }

      // Refresh BGM list
      const bgmRes = await bgmApi.list();
      setBgmList(bgmRes.data);

      if (downloadedCount > 0) {
        console.log(`BGM 다운로드 완료: ${downloadedCount}개 새로 받음`);
      } else {
        setError('BGM 다운로드에 실패했습니다. Freesound API 키를 확인하세요.');
      }
    } catch (err) {
      console.error('BGM 다운로드 실패:', err);
      setError('BGM 다운로드 중 오류가 발생했습니다. Freesound API 키가 필요합니다.');
    } finally {
      setIsDownloadingBgm(false);
    }
  };

  // Poll job status (manual workflow - no auto-processing)
  useEffect(() => {
    // Stop polling for these statuses (waiting for user action or terminal states)
    const stopPollingStatuses = ['completed', 'failed', 'awaiting_subtitle', 'awaiting_review', 'ready_for_trim'];
    if (!currentJob || stopPollingStatuses.includes(currentJob.status)) {
      return;
    }

    // Close trimmer when job is being processed
    if (showTrimmer && !['ready_for_trim', 'pending', 'completed'].includes(currentJob.status)) {
      setShowTrimmer(false);
    }

    const interval = setInterval(async () => {
      try {
        const res = await jobsApi.get(currentJob.job_id);
        const updatedJob = res.data;
        console.log(`[Poll] Status: ${updatedJob.status}, Progress: ${updatedJob.progress}%`);
        setCurrentJob(updatedJob);
      } catch (err) {
        console.error('Failed to fetch job status:', err);
      }
    }, 1000);

    return () => clearInterval(interval);
  }, [currentJob, showTrimmer]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!url.trim()) return;

    setIsLoading(true);
    setError(null);

    try {
      const downloadRes = await downloadApi.start(url);
      setCurrentJob({
        job_id: downloadRes.data.job_id,
        status: 'downloading',
        progress: 0,
        original_url: url,
      });
      setUrl('');
    } catch (err) {
      setError(err.response?.data?.detail || '다운로드 시작 실패');
    } finally {
      setIsLoading(false);
    }
  };

  const handleStartProcessing = async () => {
    if (!currentJob) return;

    try {
      await processApi.start(currentJob.job_id, {
        bgmId: selectedBgm,
        bgmVolume,
        keepOriginalAudio,
        subtitleStyle,
        translationMode,
        useVocalSeparation,
      });
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '처리 시작 실패');
    }
  };

  const handleReset = () => {
    setCurrentJob(null);
    setError(null);
    setSelectedBgm(null);
    setShowSettings(false);
  };

  // Handle GPT re-translation
  const handleRetranslate = async () => {
    if (!currentJob) return;

    try {
      await processApi.retranslate(currentJob.job_id);
      // Immediately fetch updated job to restart polling (status changes to 'translating')
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '재번역 시작 실패');
    }
  };

  // Handle continue processing with manual subtitles
  const handleProcessWithSubtitle = async (segments) => {
    if (!currentJob) return;

    try {
      // Update local state with the new transcript
      setCurrentJob(prev => ({ ...prev, transcript: segments }));

      // Continue processing
      await processApi.continue(currentJob.job_id, {
        bgmId: selectedBgm,
        bgmVolume,
        keepOriginalAudio: false, // No audio to keep
        subtitleStyle,
      });

      // Start polling again
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '처리 시작 실패');
    }
  };

  // Handle continue processing without subtitles (BGM only)
  const handleProcessWithoutSubtitle = async () => {
    if (!currentJob) return;

    try {
      await processApi.continue(currentJob.job_id, {
        bgmId: selectedBgm,
        bgmVolume,
        keepOriginalAudio: false,
        subtitleStyle: null,
      });

      // Start polling again
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '처리 시작 실패');
    }
  };

  const updateSubtitleStyle = (key, value) => {
    setSubtitleStyle(prev => ({ ...prev, [key]: value }));
  };

  // 영상 재생성 (수정된 자막/BGM으로)
  const handleReprocess = async () => {
    if (!currentJob) return;

    setIsReprocessing(true);
    setError(null);

    try {
      // 기존 transcript를 유지하면서 재처리
      await processApi.continue(currentJob.job_id, {
        bgmId: selectedBgm,
        bgmVolume,
        keepOriginalAudio,
        subtitleStyle,
      });

      // 상태 갱신 시작
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
      setEditingTranscript(false);
    } catch (err) {
      setError(err.response?.data?.detail || '재처리 실패');
    } finally {
      setIsReprocessing(false);
    }
  };

  // 다시 편집하기 (완료된 작업을 편집 상태로 되돌리기)
  const handleReEdit = async () => {
    if (!currentJob) return;

    setIsReprocessing(true);
    setError(null);

    try {
      await jobsApi.reEdit(currentJob.job_id);
      // 상태 갱신
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
      // 편집 UI 초기화
      setEditingTranscript(false);
      setShowTranscript(false);
      setShowTranslation(true);
    } catch (err) {
      setError(err.response?.data?.detail || '편집 모드 전환 실패');
    } finally {
      setIsReprocessing(false);
    }
  };

  // 자막 수정 저장
  const handleSaveTranscript = async (segments) => {
    if (!currentJob) return;

    try {
      await processApi.updateTranscript(currentJob.job_id, segments);
      setCurrentJob(prev => ({ ...prev, transcript: segments }));
      setEditingTranscript(false);
    } catch (err) {
      setError(err.response?.data?.detail || '자막 저장 실패');
    }
  };

  // 영상 트리밍 완료 핸들러
  const handleTrimComplete = async (result) => {
    setShowTrimmer(false);
    if (result.success) {
      // 트리밍 후 상태 갱신 (자동 재처리 안함)
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    }
  };

  // === Step-by-step Workflow Handlers ===

  // Step 1: 트리밍 스킵하고 다음 단계로
  const handleSkipTrim = async () => {
    if (!currentJob) return;
    try {
      await processApi.skipTrim(currentJob.job_id);
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '스킵 실패');
    }
  };

  // Step 2: 트랜스크립션 시작 (다음 단계로)
  const handleStartTranscription = async () => {
    if (!currentJob) return;
    setError(null);

    try {
      await processApi.startTranscription(currentJob.job_id, {
        translationMode,
        useVocalSeparation,
      });
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '트랜스크립션 시작 실패');
    }
  };

  // Step 3: 최종 영상 렌더링 시작
  const handleRenderVideo = async () => {
    if (!currentJob) return;
    setError(null);

    // BGM이 선택되어 있지 않으면 자동 선택
    let bgmToUse = selectedBgm;
    if (!bgmToUse && bgmList.length > 0) {
      bgmToUse = bgmList[0].id;
      setSelectedBgm(bgmToUse);
    }

    try {
      await processApi.render(currentJob.job_id, {
        bgmId: bgmToUse,
        bgmVolume,
        subtitleStyle,
        keepOriginalAudio,
        // Intro text overlay
        introText: introText.trim() || null,
        introDuration,
        introFontSize,
      });
      const res = await jobsApi.get(currentJob.job_id);
      setCurrentJob(res.data);
    } catch (err) {
      setError(err.response?.data?.detail || '렌더링 시작 실패');
    }
  };

  // GPT를 이용해 인트로 텍스트 생성
  const handleGenerateIntroText = async () => {
    if (!currentJob) return;
    setIsGeneratingIntroText(true);
    setError(null);

    try {
      const res = await thumbnailApi.generateCatchphrase(currentJob.job_id, 'homeshopping');
      if (res.data.catchphrase) {
        // 최대 10자 제한
        const text = res.data.catchphrase.slice(0, 10);
        setIntroText(text);
      }
    } catch (err) {
      setError(err.response?.data?.detail || '인트로 텍스트 생성 실패');
    } finally {
      setIsGeneratingIntroText(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* URL Input Section */}
      <div className="card">
        <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <Sparkles className="text-red-500" size={24} />
          영상 URL 입력
        </h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="flex gap-4">
            <div className="flex-1 relative">
              <Link2 className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500" size={20} />
              <input
                type="text"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="Douyin, Kuaishou, TikTok, YouTube URL 입력..."
                className="input-field pl-12"
                disabled={isLoading || currentJob}
              />
            </div>
            <button
              type="submit"
              disabled={isLoading || !url.trim() || currentJob}
              className="btn-primary px-8 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading ? '처리 중...' : '시작'}
            </button>
          </div>
          <p className="text-sm text-gray-500">
            지원: 抖音(Douyin), 快手(Kuaishou), TikTok, YouTube, Bilibili
          </p>
        </form>

        {error && (
          <div className="mt-4 p-4 bg-red-900/30 border border-red-800 rounded-lg text-red-400">
            {error}
          </div>
        )}
      </div>

      {/* Current Job - Pipeline View */}
      {currentJob && (
        <div className={`grid grid-cols-1 gap-6 ${showTrimmer ? 'lg:grid-cols-2' : 'lg:grid-cols-3'}`}>
          {/* Left: Pipeline Status */}
          <div className={`${showTrimmer ? '' : 'lg:col-span-2'} card`}>
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-semibold">처리 파이프라인</h2>
              <button
                onClick={handleReset}
                className="text-gray-400 hover:text-white text-sm px-3 py-1 border border-gray-700 rounded-lg hover:border-gray-600 transition-colors"
              >
                새 작업
              </button>
            </div>

            <PipelineView job={currentJob} onRetranslate={handleRetranslate} />

            {/* Completed Result */}
            {currentJob.status === 'completed' && currentJob.output_path && (
              <div className="mt-6 pt-6 border-t border-gray-800">
                <h3 className="font-semibold mb-4 flex items-center gap-2">
                  <Play className="text-green-500" size={20} />
                  완성된 영상
                </h3>
                <VideoPreview
                  videoUrl={jobsApi.downloadOutput(currentJob.job_id)}
                  jobId={currentJob.job_id}
                />
              </div>
            )}
          </div>

          {/* Right: Settings Panel */}
          <div className="space-y-4">
            {/* Step 1: Trimming Step - Show when ready_for_trim */}
            {currentJob.status === 'ready_for_trim' && currentJob.video_path && (
              <>
                {/* Video Trimmer */}
                <div className="card">
                  <h3 className="font-semibold mb-3 text-blue-400">1단계: 영상 편집</h3>
                  <p className="text-sm text-gray-400 mb-4">
                    원본 자막이 있는 부분을 잘라내거나, 그대로 다음 단계로 진행하세요.
                  </p>
                  {showTrimmer ? (
                    <VideoTrimmer
                      jobId={currentJob.job_id}
                      onTrimComplete={handleTrimComplete}
                      onCancel={() => setShowTrimmer(false)}
                    />
                  ) : (
                    <button
                      onClick={() => setShowTrimmer(true)}
                      className="w-full py-3 border border-amber-700/50 bg-amber-900/20 hover:bg-amber-900/30 rounded-lg transition-colors flex items-center justify-center gap-2 text-amber-300"
                    >
                      <Scissors size={18} />
                      영상 자르기
                    </button>
                  )}
                </div>

                {/* Translation Mode Settings */}
                <div className="card">
                  <button
                    onClick={() => setShowSettings(!showSettings)}
                    className="w-full flex items-center justify-between"
                  >
                    <span className="flex items-center gap-2 font-medium">
                      <Settings2 size={20} />
                      번역 설정
                    </span>
                    <ChevronDown
                      size={20}
                      className={`transform transition-transform ${showSettings ? 'rotate-180' : ''}`}
                    />
                  </button>
                  {showSettings && (
                    <div className="mt-4 space-y-3">
                      {TRANSLATION_MODES.map((mode) => (
                        <label
                          key={mode.id}
                          className={`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${
                            translationMode === mode.id
                              ? 'border-blue-500 bg-blue-500/10'
                              : 'border-gray-700 hover:border-gray-600'
                          }`}
                        >
                          <input
                            type="radio"
                            name="translationMode"
                            value={mode.id}
                            checked={translationMode === mode.id}
                            onChange={(e) => setTranslationMode(e.target.value)}
                            className="mt-1"
                          />
                          <div>
                            <div className="font-medium">{mode.name}</div>
                            <div className="text-sm text-gray-500">{mode.desc}</div>
                          </div>
                        </label>
                      ))}
                    </div>
                  )}
                </div>

                {/* Next Step Button */}
                <button
                  onClick={handleStartTranscription}
                  className="btn-primary w-full py-4 text-lg font-semibold"
                >
                  다음 단계 (음성 인식)
                </button>
                <button
                  onClick={handleSkipTrim}
                  className="w-full py-2 text-sm text-gray-400 hover:text-white transition-colors"
                >
                  트리밍 없이 진행
                </button>
              </>
            )}

            {/* Step 2: Script Review - Show when awaiting_review */}
            {currentJob.status === 'awaiting_review' && (
              <>
                {/* Transcript Editor - Shows all scripts */}
                {currentJob.transcript && currentJob.transcript.length > 0 && (
                  <div className="card">
                    <h3 className="font-semibold mb-3 text-blue-400">2단계: 스크립트 확인 및 편집</h3>
                    <p className="text-sm text-gray-400 mb-4">
                      변환된 스크립트를 확인하고 필요시 수정하세요. ({currentJob.transcript.length}개 자막)
                    </p>
                    <SubtitleEditor
                      segments={currentJob.transcript}
                      jobId={currentJob.job_id}
                      onUpdate={(segments) => setCurrentJob({ ...currentJob, transcript: segments })}
                      compact={false}
                    />
                  </div>
                )}

                {/* Subtitle Style Settings */}
                <div className="card">
                  <button
                    onClick={() => setShowSettings(!showSettings)}
                    className="w-full flex items-center justify-between"
                  >
                    <span className="flex items-center gap-2 font-medium">
                      <Settings2 size={20} />
                      자막 스타일
                    </span>
                    <ChevronDown
                      size={20}
                      className={`transform transition-transform ${showSettings ? 'rotate-180' : ''}`}
                    />
                  </button>
                  {showSettings && (
                    <div className="mt-4 space-y-4">
                      {/* Subtitle Position */}
                      <div>
                        <label className="block text-sm text-gray-400 mb-2">자막 위치</label>
                        <div className="grid grid-cols-3 gap-2">
                          {SUBTITLE_POSITIONS.map((pos) => (
                            <button
                              key={pos.id}
                              onClick={() => updateSubtitleStyle('position', pos.id)}
                              className={`p-2 rounded-lg border text-sm transition-colors ${
                                subtitleStyle.position === pos.id
                                  ? 'border-blue-500 bg-blue-500/10'
                                  : 'border-gray-700 hover:border-gray-600'
                              }`}
                            >
                              {pos.name}
                            </button>
                          ))}
                        </div>
                      </div>
                      {/* Font Selection */}
                      <div>
                        <label className="block text-sm text-gray-400 mb-2">폰트</label>
                        <select
                          value={subtitleStyle.font_name}
                          onChange={(e) => updateSubtitleStyle('font_name', e.target.value)}
                          className="w-full p-2 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                        >
                          {fontList.length > 0 ? (
                            fontList.map((font) => (
                              <option key={font.id} value={font.id}>
                                {font.name} - {font.style}
                              </option>
                            ))
                          ) : (
                            <option value="NanumGothic">나눔고딕 - 기본</option>
                          )}
                        </select>
                        {fontList.find(f => f.id === subtitleStyle.font_name)?.recommended_for && (
                          <p className="text-xs text-gray-500 mt-1">
                            추천: {fontList.find(f => f.id === subtitleStyle.font_name)?.recommended_for.join(', ')}
                          </p>
                        )}
                      </div>
                      {/* Font Size */}
                      <div>
                        <label className="block text-sm text-gray-400 mb-2">
                          글자 크기: {subtitleStyle.font_size}px
                        </label>
                        <input
                          type="range"
                          min="24"
                          max="96"
                          value={subtitleStyle.font_size}
                          onChange={(e) => updateSubtitleStyle('font_size', parseInt(e.target.value))}
                          className="w-full"
                        />
                      </div>
                      {/* Animation */}
                      <div>
                        <label className="block text-sm text-gray-400 mb-2">애니메이션</label>
                        <div className="grid grid-cols-3 gap-2">
                          {ANIMATIONS.map((anim) => (
                            <button
                              key={anim.id}
                              onClick={() => updateSubtitleStyle('animation', anim.id)}
                              className={`p-2 rounded-lg border text-sm transition-colors ${
                                subtitleStyle.animation === anim.id
                                  ? 'border-blue-500 bg-blue-500/10'
                                  : 'border-gray-700 hover:border-gray-600'
                              }`}
                            >
                              {anim.name}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* BGM Selection */}
                <div className="card">
                  <h3 className="font-medium mb-4 flex items-center gap-2">
                    <Music size={18} className="text-purple-400" />
                    BGM 선택
                  </h3>
                  <div className="space-y-2 max-h-48 overflow-y-auto">
                    <button
                      onClick={() => { setSelectedBgm(null); stopBgmPreview(); }}
                      className={`w-full p-2 rounded-lg border text-left text-sm transition-colors ${
                        !selectedBgm
                          ? 'border-blue-500 bg-blue-500/10'
                          : 'border-gray-700 hover:border-gray-600'
                      }`}
                    >
                      BGM 없음
                    </button>
                    {bgmList.map((bgm) => (
                      <div
                        key={bgm.id}
                        className={`flex items-center gap-2 p-2 rounded-lg border transition-colors ${
                          selectedBgm === bgm.id
                            ? 'border-blue-500 bg-blue-500/10'
                            : 'border-gray-700 hover:border-gray-600'
                        }`}
                      >
                        {/* Play/Pause Button */}
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleBgmPreview(bgm); }}
                          className={`p-1.5 rounded-full transition-colors ${
                            playingBgmId === bgm.id
                              ? 'bg-green-500/20 text-green-400'
                              : 'bg-gray-700 hover:bg-gray-600 text-gray-300'
                          }`}
                          title={playingBgmId === bgm.id ? '정지' : '미리듣기'}
                        >
                          {playingBgmId === bgm.id ? <Pause size={14} /> : <Play size={14} />}
                        </button>
                        {/* BGM Selection */}
                        <button
                          onClick={() => setSelectedBgm(bgm.id)}
                          className="flex-1 text-left text-sm"
                        >
                          <div className="font-medium truncate">{bgm.name}</div>
                          <div className="text-xs text-gray-500">
                            {Math.floor(bgm.duration / 60)}:{String(Math.floor(bgm.duration % 60)).padStart(2, '0')}
                          </div>
                        </button>
                      </div>
                    ))}
                  </div>
                  {selectedBgm && (
                    <div className="mt-3">
                      <label className="block text-xs text-gray-400 mb-1">
                        볼륨: {Math.round(bgmVolume * 100)}%
                      </label>
                      <input
                        type="range"
                        min="0"
                        max="1"
                        step="0.1"
                        value={bgmVolume}
                        onChange={(e) => setBgmVolume(parseFloat(e.target.value))}
                        className="w-full"
                      />
                    </div>
                  )}
                  {/* Currently playing indicator */}
                  {playingBgmId && (
                    <div className="mt-2 flex items-center justify-between p-2 bg-green-500/10 rounded-lg border border-green-500/30">
                      <div className="flex items-center gap-2 text-green-400 text-xs">
                        <Volume2 size={14} className="animate-pulse" />
                        재생 중: {bgmList.find(b => b.id === playingBgmId)?.name}
                      </div>
                      <button
                        onClick={stopBgmPreview}
                        className="p-1 hover:bg-green-500/20 rounded"
                        title="정지"
                      >
                        <Square size={12} className="text-green-400" />
                      </button>
                    </div>
                  )}
                  {/* Download more BGM */}
                  <button
                    onClick={handleDownloadMoreBgm}
                    disabled={isDownloadingBgm}
                    className="mt-3 w-full py-2 border border-purple-700/50 bg-purple-900/20 hover:bg-purple-900/30 rounded-lg transition-colors flex items-center justify-center gap-2 text-purple-300 text-sm disabled:opacity-50"
                  >
                    {isDownloadingBgm ? (
                      <>
                        <Loader2 size={14} className="animate-spin" />
                        BGM 다운로드 중...
                      </>
                    ) : (
                      <>
                        <Download size={14} />
                        더 많은 BGM 다운로드 (무료)
                      </>
                    )}
                  </button>
                </div>

                {/* Intro Text Input - YouTube Shorts Thumbnail */}
                <div className="card">
                  <h3 className="font-medium mb-3 flex items-center gap-2">
                    <Type size={18} className="text-pink-400" />
                    인트로 문구 (썸네일)
                  </h3>
                  <p className="text-xs text-gray-400 mb-3">
                    영상 시작 부분에 표시될 문구입니다. YouTube Shorts에서 썸네일로 사용됩니다.
                  </p>

                  {/* Text Input */}
                  <div className="space-y-3">
                    <div className="relative">
                      <input
                        type="text"
                        value={introText}
                        onChange={(e) => setIntroText(e.target.value.slice(0, 10))}
                        placeholder="최대 10자 입력..."
                        maxLength={10}
                        className="w-full p-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-lg focus:outline-none focus:border-pink-500"
                      />
                      <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-500">
                        {introText.length}/10
                      </span>
                    </div>

                    {/* GPT Generate Button */}
                    <button
                      onClick={handleGenerateIntroText}
                      disabled={isGeneratingIntroText || !currentJob.transcript?.length}
                      className="w-full py-2 border border-pink-700/50 bg-pink-900/20 hover:bg-pink-900/30 rounded-lg transition-colors flex items-center justify-center gap-2 text-pink-300 text-sm disabled:opacity-50"
                    >
                      {isGeneratingIntroText ? (
                        <>
                          <Loader2 size={16} className="animate-spin" />
                          생성 중...
                        </>
                      ) : (
                        <>
                          <Sparkles size={16} />
                          GPT로 문구 생성
                        </>
                      )}
                    </button>

                    {/* Preview */}
                    {introText && (
                      <div className="p-4 bg-black rounded-lg text-center">
                        <span
                          className="font-bold text-white"
                          style={{ fontSize: `${Math.min(introFontSize / 3, 36)}px` }}
                        >
                          {introText}
                        </span>
                        <p className="text-xs text-gray-500 mt-2">미리보기 (실제 크기와 다를 수 있음)</p>
                      </div>
                    )}

                    {/* Duration Setting */}
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">
                        정지 프레임 시간: {introDuration}초
                      </label>
                      <input
                        type="range"
                        min="0.5"
                        max="3"
                        step="0.1"
                        value={introDuration}
                        onChange={(e) => setIntroDuration(parseFloat(e.target.value))}
                        className="w-full"
                      />
                    </div>
                  </div>
                </div>

                {/* Render Button */}
                <button
                  onClick={handleRenderVideo}
                  className="w-full py-4 bg-gradient-to-r from-green-600 to-blue-600 hover:from-green-500 hover:to-blue-500 rounded-lg font-semibold text-lg flex items-center justify-center gap-2 transition-all"
                >
                  <Film size={20} />
                  최종 영상 생성
                </button>
              </>
            )}

            {/* No Audio - Manual Subtitle Input */}
            {currentJob.status === 'awaiting_subtitle' && (
              <>
                {/* BGM Selection for no-audio mode */}
                <div className="card">
                  <h3 className="font-medium mb-4 flex items-center gap-2">
                    <Music size={18} className="text-amber-400" />
                    BGM 선택 (권장)
                  </h3>
                  <p className="text-sm text-gray-400 mb-3">
                    오디오가 없으므로 BGM을 추가하는 것을 권장합니다.
                  </p>
                  <div className="space-y-2 max-h-48 overflow-y-auto">
                    <button
                      onClick={() => { setSelectedBgm(null); stopBgmPreview(); }}
                      className={`w-full p-3 rounded-lg border text-left transition-colors ${
                        !selectedBgm
                          ? 'border-amber-500 bg-amber-500/10'
                          : 'border-gray-700 hover:border-gray-600'
                      }`}
                    >
                      BGM 없음
                    </button>
                    {bgmList.map((bgm) => (
                      <div
                        key={bgm.id}
                        className={`flex items-center gap-2 p-3 rounded-lg border transition-colors ${
                          selectedBgm === bgm.id
                            ? 'border-amber-500 bg-amber-500/10'
                            : 'border-gray-700 hover:border-gray-600'
                        }`}
                      >
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleBgmPreview(bgm); }}
                          className={`p-1.5 rounded-full transition-colors ${
                            playingBgmId === bgm.id
                              ? 'bg-green-500/20 text-green-400'
                              : 'bg-gray-700 hover:bg-gray-600 text-gray-300'
                          }`}
                          title={playingBgmId === bgm.id ? '정지' : '미리듣기'}
                        >
                          {playingBgmId === bgm.id ? <Pause size={14} /> : <Play size={14} />}
                        </button>
                        <button
                          onClick={() => setSelectedBgm(bgm.id)}
                          className="flex-1 text-left"
                        >
                          <div className="font-medium truncate">{bgm.name}</div>
                          <div className="text-sm text-gray-500">
                            {Math.floor(bgm.duration / 60)}:{String(Math.floor(bgm.duration % 60)).padStart(2, '0')}
                          </div>
                        </button>
                      </div>
                    ))}
                  </div>

                  {selectedBgm && (
                    <div className="mt-4">
                      <label className="block text-sm text-gray-400 mb-2">
                        BGM 볼륨: {Math.round(bgmVolume * 100)}%
                      </label>
                      <input
                        type="range"
                        min="0"
                        max="1"
                        step="0.1"
                        value={bgmVolume}
                        onChange={(e) => setBgmVolume(parseFloat(e.target.value))}
                        className="w-full"
                      />
                    </div>
                  )}
                  {playingBgmId && (
                    <div className="mt-2 flex items-center justify-between p-2 bg-green-500/10 rounded-lg border border-green-500/30">
                      <div className="flex items-center gap-2 text-green-400 text-xs">
                        <Volume2 size={14} className="animate-pulse" />
                        재생 중: {bgmList.find(b => b.id === playingBgmId)?.name}
                      </div>
                      <button onClick={stopBgmPreview} className="p-1 hover:bg-green-500/20 rounded">
                        <Square size={12} className="text-green-400" />
                      </button>
                    </div>
                  )}
                </div>

                {/* Manual Subtitle Input */}
                <ManualSubtitleInput
                  job={currentJob}
                  onProcessWithSubtitle={handleProcessWithSubtitle}
                  onProcessWithoutSubtitle={handleProcessWithoutSubtitle}
                  onCancel={handleReset}
                />
              </>
            )}

            {/* Transcript Editor - Show during/after transcription (but not in step-by-step UI) */}
            {currentJob.transcript && currentJob.transcript.length > 0 && !['awaiting_subtitle', 'awaiting_review', 'ready_for_trim'].includes(currentJob.status) && (
              <div className="card">
                <h3 className="font-medium mb-4 flex items-center gap-2">
                  <FileText size={18} />
                  자막 편집
                </h3>
                <SubtitleEditor
                  segments={currentJob.transcript}
                  jobId={currentJob.job_id}
                  onUpdate={(segments) => setCurrentJob({ ...currentJob, transcript: segments })}
                  compact={true}
                />
              </div>
            )}

            {/* Results & Settings - Show when completed */}
            {currentJob.status === 'completed' && (
              <div className="space-y-3">
                {/* Download Buttons */}
                <div className="card space-y-3">
                  <h3 className="font-medium mb-2">다운로드</h3>
                  <a
                    href={jobsApi.downloadOutput(currentJob.job_id)}
                    download
                    className="btn-primary w-full flex items-center justify-center gap-2"
                  >
                    <Download size={18} />
                    완성 영상 다운로드
                  </a>
                  <a
                    href={jobsApi.downloadSubtitle(currentJob.job_id, 'srt')}
                    download
                    className="w-full py-2 px-4 border border-gray-700 rounded-lg hover:border-gray-600 transition-colors flex items-center justify-center gap-2"
                  >
                    <FileText size={18} />
                    자막 파일 (SRT)
                  </a>
                </div>

                {/* 다시 편집하기 버튼 */}
                <button
                  onClick={handleReEdit}
                  disabled={isReprocessing}
                  className="w-full py-3 border border-blue-600 bg-blue-600/20 hover:bg-blue-600/30 rounded-lg transition-colors flex items-center justify-center gap-2 text-blue-300"
                >
                  <Edit3 size={18} />
                  다시 편집하기 (자막, BGM, 인트로 수정)
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Quick Guide - 6 Step Pipeline */}
      {!currentJob && (
        <div className="card bg-gradient-to-br from-gray-900 to-gray-800">
          <h3 className="text-lg font-semibold mb-6">6단계 처리 파이프라인</h3>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {[
              { emoji: '📥', title: '영상 다운로드', desc: 'yt-dlp' },
              { emoji: '🎵', title: '오디오 추출', desc: 'FFmpeg' },
              { emoji: '🔇', title: '노이즈 제거', desc: '배경음 제거' },
              { emoji: '🎤', title: 'Whisper STT', desc: '음성→텍스트' },
              { emoji: '🌐', title: '한국어 변환', desc: 'GPT 요약/번역' },
              { emoji: '🎬', title: '영상 합성', desc: '자막+BGM' },
            ].map((step, i) => (
              <div key={i} className="relative text-center p-3">
                <div className="w-12 h-12 mx-auto mb-2 bg-red-500/20 rounded-xl flex items-center justify-center text-xl">
                  {step.emoji}
                </div>
                <div className="text-xs font-mono text-gray-500 mb-1">0{i + 1}</div>
                <div className="font-medium text-sm">{step.title}</div>
                <div className="text-xs text-gray-500 mt-1">{step.desc}</div>
                {i < 5 && (
                  <div className="hidden lg:block absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 text-lg text-gray-600 z-10">
                    →
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
