'use client';
import { useVirtualizer } from '@tanstack/react-virtual';

import { useParams, useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowLeft,
  Play,
  Sparkles,
  RefreshCw,
  Clock,
  CheckCircle2,
  AlertCircle,
  Loader2,
  FileText,
  Film,
  Trash2,
  MoreVertical,
  X,
  Languages,
  Search,
  Tag,
  Copy,
  Check,
  TrendingUp,
  Zap,
  Hash,
} from 'lucide-react';
import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { 
  useProject, 
  useGenerateScript, 
  useApproveAndQueue, 
  useUpdateProject, 
  useDeleteProject,
  useGenerateSceneImage,
  useUpscaleSceneImage,
  useRegenerateScene,
  useCancelRender,
  useGenerateSeoTitles,
  useSelectSeoTitle,
  useGenerateSocialContent
} from '@/hooks/use-api';
import { useRenderProgress } from '@/hooks/use-render-progress';
import { SceneCard } from '@/components/project/scene-card';
import { RenderProgress } from '@/components/project/render-progress';
import { VideoPlayer } from '@/components/project/video-player';
import { projectsApi, apiClient } from '@/lib/api/api-service';
import { CINEMATIC_REFERENCES } from '@/constants/cinematic-references';
import { languages } from '@/components/projects/ProjectConfiguration';
import { toaster as toast } from '@/components/ui/feedback/toaster';

// X (Twitter) ikonunu burada da tanımlıyoruz
const XIcon = ({ size = 16 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
  </svg>
);

const YouTubeIcon = ({ size = 16 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M23.5 6.19a3.02 3.02 0 0 0-2.12-2.14C19.53 3.5 12 3.5 12 3.5s-7.53 0-9.38.55A3.02 3.02 0 0 0 .5 6.19 31.7 31.7 0 0 0 0 12a31.7 31.7 0 0 0 .5 5.81 3.02 3.02 0 0 0 2.12 2.14c1.85.55 9.38.55 9.38.55s7.53 0 9.38-.55a3.02 3.02 0 0 0 2.12-2.14A31.7 31.7 0 0 0 24 12a31.7 31.7 0 0 0-.5-5.81zM9.55 15.57V8.43L15.82 12l-6.27 3.57z" />
  </svg>
);

const InstagramIcon = ({ size = 16 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 1 0 0 12.324 6.162 6.162 0 0 0 0-12.324zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.406-11.845a1.44 1.44 0 1 0 0 2.881 1.44 1.44 0 0 0 0-2.881z" />
  </svg>
);

const STATUS_MAP: Record<string, { label: string; color: string; icon: React.ElementType; bgClass: string }> = {
  DRAFT: { label: 'Taslak', color: 'text-neutral-400', icon: FileText, bgClass: 'bg-neutral-500/10 border-neutral-500/20' },
  GENERATING_SCRIPT: { label: 'Senaryo Üretiliyor', color: 'text-neutral-300', icon: Sparkles, bgClass: 'bg-neutral-500/10 border-neutral-500/20' },
  PENDING: { label: 'Kuyrukta', color: 'text-neutral-400', icon: Clock, bgClass: 'bg-neutral-500/10 border-neutral-500/20' },
  GENERATING_MEDIA: { label: 'Medya Üretiliyor', color: 'text-neutral-300', icon: Sparkles, bgClass: 'bg-neutral-500/10 border-neutral-500/20' },
  RENDERING: { label: 'Video İşleniyor', color: 'text-neutral-300', icon: Film, bgClass: 'bg-neutral-500/10 border-neutral-500/20' },
  COMPLETED: { label: 'Tamamlandı', color: 'text-neutral-100', icon: CheckCircle2, bgClass: 'bg-neutral-500/20 border-neutral-500/30' },
  FAILED: { label: 'Başarısız', color: 'text-neutral-500', icon: AlertCircle, bgClass: 'bg-neutral-800/50 border-neutral-800' },
};

const videoStyles = [
  // Film & Sinema
  { id: "CINEMATIC", label: "Sinematik", emoji: "🎬", desc: "Film kalitesinde görseller", category: "Film & Sinema" },
  { id: "DOCUMENTARY", label: "Belgesel", emoji: "📹", desc: "Bilimsel ve ciddi ton", category: "Film & Sinema" },
  { id: "STORYTELLING", label: "Hikâye Anlatımı", emoji: "📖", desc: "Anlatı odaklı, sürükleyici", category: "Film & Sinema" },
  { id: "NEWS", label: "Haber", emoji: "📰", desc: "Güncel ve bilgilendirici", category: "Film & Sinema" },
  { id: "ARTISTIC", label: "Sanatsal", emoji: "🎨", desc: "Yaratıcı ve sıra dışı", category: "Film & Sinema" },
  { id: "NOIR", label: "Film Noir", emoji: "🖤", desc: "Karanlık, dramatik", category: "Film & Sinema" },
  { id: "VLOG", label: "Vlog", emoji: "📱", desc: "Günlük, samimi", category: "Film & Sinema" },
  // Animasyon
  { id: "ANIME", label: "Anime", emoji: "⛩️", desc: "Japon animasyon stili", category: "Animasyon" },
  { id: "ANIMATION_3D", label: "3D Animasyon", emoji: "🧊", desc: "Pixar kalitesi", category: "Animasyon" },
  { id: "ANIMATION_2D", label: "2D Animasyon", emoji: "✏️", desc: "Klasik el çizimi", category: "Animasyon" },
  { id: "STOP_MOTION", label: "Stop Motion", emoji: "🧸", desc: "Kare kare animasyon", category: "Animasyon" },
  { id: "MOTION_COMIC", label: "Hareketli Çizgi Roman", emoji: "💥", desc: "Panel bazlı anlatım", category: "Animasyon" },
  { id: "CARTOON", label: "Karikatür", emoji: "🎭", desc: "Çizgi film stili", category: "Animasyon" },
  { id: "CLAYMATION", label: "Claymation", emoji: "🏺", desc: "Kil animasyon", category: "Animasyon" },
  { id: "PIXEL_ART", label: "Pixel Art", emoji: "👾", desc: "8-bit retro oyun", category: "Animasyon" },
  { id: "ISOMETRIC", label: "İzometrik", emoji: "🔷", desc: "İzometrik animasyon", category: "Animasyon" },
  // Eğitim & Bilgi
  { id: "EDUCATIONAL", label: "Eğitim", emoji: "🎓", desc: "Öğretici ve açıklayıcı", category: "Eğitim & Bilgi" },
  { id: "INFOGRAPHIC", label: "İnfografik", emoji: "📊", desc: "Veri görselleştirme", category: "Eğitim & Bilgi" },
  { id: "WHITEBOARD", label: "Whiteboard", emoji: "📝", desc: "Tahta animasyonu", category: "Eğitim & Bilgi" },
  { id: "EXPLAINER", label: "Explainer", emoji: "💡", desc: "Ürün/konsept anlatımı", category: "Eğitim & Bilgi" },
  { id: "DATA_VIZ", label: "Veri Görselleştirme", emoji: "📈", desc: "Grafikler ve tablolar", category: "Eğitim & Bilgi" },
  // Retro & Nostaljik
  { id: "RETRO_80S", label: "Retro 80s", emoji: "🕹️", desc: "Synthwave estetik", category: "Retro & Nostaljik" },
  { id: "VINTAGE_FILM", label: "Vintage Film", emoji: "📽️", desc: "Super 8 filmi", category: "Retro & Nostaljik" },
  { id: "VHS", label: "VHS", emoji: "📼", desc: "Kaset estetik", category: "Retro & Nostaljik" },
  { id: "POLAROID", label: "Polaroid", emoji: "📸", desc: "Analog fotoğraf", category: "Retro & Nostaljik" },
  { id: "RETRO_90S", label: "Retro 90s Y2K", emoji: "💿", desc: "Y2K & internet", category: "Retro & Nostaljik" },
  // Sanat Akımları
  { id: "WATERCOLOR", label: "Suluboya", emoji: "🎨", desc: "Suluboya resim", category: "Sanat Akımları" },
  { id: "OIL_PAINTING", label: "Yağlı Boya", emoji: "🖌️", desc: "Klasik tuval", category: "Sanat Akımları" },
  { id: "IMPRESSIONIST", label: "Empresyonist", emoji: "🌅", desc: "Monet tarzı", category: "Sanat Akımları" },
  { id: "POP_ART", label: "Pop Art", emoji: "🎯", desc: "Warhol stili", category: "Sanat Akımları" },
  { id: "UKIYO_E", label: "Ukiyo-e", emoji: "🏯", desc: "Japon gravür", category: "Sanat Akımları" },
  { id: "ART_DECO", label: "Art Deco", emoji: "✨", desc: "1920s zarafet", category: "Sanat Akımları" },
  { id: "SURREAL", label: "Sürrealist", emoji: "🌀", desc: "Dalí tarzı", category: "Sanat Akımları" },
  { id: "COMIC_BOOK", label: "Çizgi Roman", emoji: "💬", desc: "Marvel/DC stili", category: "Sanat Akımları" },
  { id: "SKETCH", label: "Karakalem", emoji: "✍️", desc: "Kalem çizim", category: "Sanat Akımları" },
  // Modern & Minimal
  { id: "MINIMALIST", label: "Minimalist", emoji: "⚪", desc: "Apple estetiği", category: "Modern & Minimal" },
  { id: "GLASSMORPHISM", label: "Glassmorphism", emoji: "🔮", desc: "Cam efekti", category: "Modern & Minimal" },
  { id: "NEON", label: "Neon Glow", emoji: "💜", desc: "Neon ışıkları", category: "Modern & Minimal" },
  { id: "CYBERPUNK", label: "Cyberpunk", emoji: "🤖", desc: "Gelecek distopya", category: "Modern & Minimal" },
  { id: "STEAMPUNK", label: "Steampunk", emoji: "⚙️", desc: "Viktoryan mekanik", category: "Modern & Minimal" },
  { id: "ABSTRACT", label: "Soyut", emoji: "🔵", desc: "Abstract sanat", category: "Modern & Minimal" },
  // Fotoğrafik
  { id: "PRODUCT", label: "Ürün Fotoğrafı", emoji: "📦", desc: "Studio çekim", category: "Fotoğrafik" },
  { id: "FASHION", label: "Moda", emoji: "👗", desc: "Editöryal çekim", category: "Fotoğrafik" },
  { id: "AERIAL", label: "Havadan", emoji: "🚁", desc: "Drone görüntüsü", category: "Fotoğrafik" },
  { id: "MACRO", label: "Makro", emoji: "🔬", desc: "Yakın çekim", category: "Fotoğrafik" },
  { id: "PORTRAIT", label: "Portre", emoji: "🧑", desc: "Portre fotoğraf", category: "Fotoğrafik" },
];

const stagger = {
  hidden: { opacity: 0 },
  show: { opacity: 1, transition: { staggerChildren: 0.06 } },
};

const fadeUp = {
  hidden: { opacity: 0, y: 12 },
  show: { opacity: 1, y: 0, transition: { duration: 0.4, ease: [0.16, 1, 0.3, 1] as const } },
};

export default function ProjectDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [showMenu, setShowMenu] = useState(false);
  const [regeneratingSceneId, setRegeneratingSceneId] = useState<string | null>(null);
  const [mounted, setMounted] = useState(false);
  
  const [showTranslateModal, setShowTranslateModal] = useState(false);
  const [targetLanguage, setTargetLanguage] = useState<string>("");
  const [isTranslating, setIsTranslating] = useState(false);

  const confirmTranslate = async () => {
    if (!id || !targetLanguage) return;
    try {
      setIsTranslating(true);
      const res = await apiClient.post(`/projects/${id}/translate`, { targetLanguage });
      toast.success({ title: "Proje başarıyla çevrildi!" });
      setShowTranslateModal(false);
      setTargetLanguage("");
      // refetch() to maybe update some states, or router.push to the new project
      router.push(`/dashboard/projects/${res.data.id}`);
    } catch (err: any) {
      toast.error(err?.response?.data?.message || "Çeviri sırasında bir hata oluştu.");
    } finally {
      setIsTranslating(false);
    }
  };

  useEffect(() => {
    setMounted(true);
  }, []);

  // Veri hook'ları (Aktif işlem varsa 3 saniyede bir polling yap)
  const { data: project, isLoading, error, refetch } = useProject(id, {
    refetchInterval: (data: any) => {
      if (!data) return false;
      const isGenerating = data.status === 'GENERATING_MEDIA' || 
                           data.renderJobs?.some((j: any) => j.status === 'QUEUED' || j.status === 'PROCESSING');
      return isGenerating ? 3000 : false;
    }
  });
  const generateScriptMutation = useGenerateScript();
  const approveMutation = useApproveAndQueue();
  const deleteMutation = useDeleteProject();
  const cancelRenderMutation = useCancelRender();

  // Virtualization for long-form video scenes
  const parentRef = useRef<HTMLDivElement>(null);
  const rowVirtualizer = useVirtualizer({
    count: project?.scenes?.length || 0,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 300, // Estimated height of a SceneCard
    overscan: 5, // Render 5 items outside of the visible area
  });
  const generateImageMutation = useGenerateSceneImage();
  const upscaleImageMutation = useUpscaleSceneImage();
  const regenerateSceneMutation = useRegenerateScene();
  const seoTitlesMutation = useGenerateSeoTitles();
  const selectTitleMutation = useSelectSeoTitle();
  const generateSocialMutation = useGenerateSocialContent();

  const [generatingImageId, setGeneratingImageId] = useState<string | null>(null);
  const [upscalingImageId, setUpscalingImageId] = useState<string | null>(null);
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [activeCaptionTab, setActiveCaptionTab] = useState<'youtube' | 'tiktok' | 'instagram' | 'twitter'>('youtube');

  // WebSocket progress
  const renderState = useRenderProgress(
    project?.status && ['PENDING', 'GENERATING_MEDIA', 'RENDERING'].includes(project.status) ? id : undefined,
  );

  // Sahne güncelleme
  const handleSceneUpdate = async (sceneId: string, data: { narrationText?: string; visualPrompt?: string; subtitleText?: string }) => {
    try {
      await projectsApi.update(`${id}/scenes/${sceneId}` as unknown as string, data as any);
      refetch();
    } catch (err) {
      console.error('Sahne güncelleme hatası:', err);
    }
  };

  // Sahne yeniden üretim
  const handleSceneRegenerate = async (sceneId: string) => {
    setRegeneratingSceneId(sceneId);
    regenerateSceneMutation.mutate(
      { projectId: id, sceneId },
      {
        onSettled: () => setRegeneratingSceneId(null),
        onSuccess: () => refetch(),
      }
    );
  };

  // Sahne görseli oluşturma
  const handleGenerateImage = (sceneId: string, customPrompt?: string) => {
    setGeneratingImageId(sceneId);
    generateImageMutation.mutate(
      { projectId: id, sceneId, customPrompt },
      {
        onSettled: () => setGeneratingImageId(null),
        onSuccess: () => refetch(),
      }
    );
  };

  // Sahne görseli upscale
  const handleUpscaleImage = (sceneId: string) => {
    setUpscalingImageId(sceneId);
    upscaleImageMutation.mutate(
      { projectId: id, sceneId },
      {
        onSettled: () => setUpscalingImageId(null),
        onSuccess: () => refetch(),
      }
    );
  };

  // Senaryo üret
  const handleGenerateScript = () => {
    generateScriptMutation.mutate(id, {
      onSuccess: () => refetch(),
    });
  };

  // Panoya kopyala
  const copyToClipboard = (text: string, field: string) => {
    navigator.clipboard.writeText(text);
    setCopiedField(field);
    toast.success({ title: 'Panoya kopyalandı!' });
    setTimeout(() => setCopiedField(null), 2000);
  };

  // SEO başlıkları üret
  const handleGenerateSeoTitles = () => {
    seoTitlesMutation.mutate(id, {
      onSuccess: () => {
        refetch();
        toast.success({ title: '5 yeni SEO başlığı üretildi!' });
      },
      onError: () => {
        toast.error({ title: 'SEO başlık üretimi başarısız.' });
      },
    });
  };

  // SEO başlık seç
  const handleSelectTitle = (title: string) => {
    selectTitleMutation.mutate({ projectId: id, title }, {
      onSuccess: () => {
        refetch();
        toast.success({ title: 'Başlık güncellendi!' });
      },
      onError: () => {
        toast.error({ title: 'Başlık güncellenemedi.' });
      },
    });
  };

  // Onayla ve gönder
  const handleApprove = () => {
    approveMutation.mutate({ projectId: id }, {
      onSuccess: () => refetch(),
    });
  };

  // İptal et
  const handleCancelRender = () => {
    if (confirm('Aktif video üretimini iptal etmek istediğinize emin misiniz?')) {
      cancelRenderMutation.mutate(id, {
        onSuccess: () => refetch(),
      });
    }
  };

  // Sil
  const handleDelete = () => {
    if (confirm('Bu projeyi silmek istediğinize emin misiniz?')) {
      deleteMutation.mutate(id, {
        onSuccess: () => router.push('/dashboard/projects'),
      });
    }
  };

  // ── Loading ──
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="flex flex-col items-center gap-3">
          <Loader2 size={32} className="animate-spin text-neutral-400" />
          <p className="text-sm text-[var(--color-text-muted)]">Proje yükleniyor...</p>
        </div>
      </div>
    );
  }

  // ── Error ──
  if (error || !project) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="card-surface p-8 text-center max-w-md">
          <AlertCircle size={40} className="text-red-400 mx-auto mb-3" />
          <h2 className="text-lg font-semibold mb-2">Proje Bulunamadı</h2>
          <p className="text-sm text-[var(--color-text-muted)] mb-4">
            Bu proje silinmiş veya erişim izniniz yok.
          </p>
          <Link href="/dashboard/projects" className="btn-primary text-sm">
            Projelere Dön
          </Link>
        </div>
      </div>
    );
  }

  const statusInfo = STATUS_MAP[project.status] || STATUS_MAP.DRAFT;
  const StatusIcon = statusInfo.icon;
  const isRendering = ['PENDING', 'GENERATING_MEDIA', 'RENDERING', 'GENERATING_SCRIPT'].includes(project.status);
  const isEditable = !isRendering; // COMPLETED, DRAFT, FAILED → editable
  const hasScript = project.scenes && project.scenes.length > 0;
  const isCompleted = project.status === 'COMPLETED';
  const tweetData = project.sourceTweetData as Record<string, any> | undefined;

  const currentStyle = videoStyles.find(s => s.id === project.videoStyle);

  const handleStyleChange = async (newStyleId: string) => {
    if (newStyleId === project.videoStyle) return;
    try {
      await projectsApi.update(id, { videoStyle: newStyleId } as any);
      refetch();
    } catch (error) {
      console.error('Failed to update style:', error);
    }
  };

  const handleCinematicReferenceChange = async (newRef: string) => {
    if (newRef === project.cinematicReference) return;
    try {
      await projectsApi.update(id, { cinematicReference: newRef || undefined } as any);
      refetch();
    } catch (error) {
      console.error('Failed to update cinematic reference:', error);
    }
  };

  return (
    <motion.div
      variants={stagger}
      initial="hidden"
      animate="show"
      className="space-y-5 max-w-4xl mx-auto pb-8"
    >
      {/* ── Üst Bar — Geri + Aksiyonlar ── */}
      <motion.div variants={fadeUp} className="flex items-center justify-between">
        <Link
          href="/dashboard/projects"
          className="flex items-center gap-2 text-sm text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)] transition-colors"
        >
          <ArrowLeft size={16} />
          Projeler
        </Link>

        <div className="relative">
          <button
            onClick={() => setShowMenu(!showMenu)}
            className="w-8 h-8 rounded-lg flex items-center justify-center text-[var(--color-text-muted)] hover:bg-[var(--color-bg-elevated)] transition-colors"
          >
            <MoreVertical size={16} />
          </button>

          {showMenu && (
            <div className="absolute right-0 top-10 card-surface p-1.5 min-w-[160px] z-50 shadow-xl">
              <button
                onClick={() => { refetch(); setShowMenu(false); }}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] rounded-lg transition-colors"
              >
                <RefreshCw size={14} /> Yenile
              </button>
              <button
                onClick={() => { setShowMenu(false); setShowTranslateModal(true); }}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] rounded-lg transition-colors"
              >
                <Languages size={14} /> Çevir
              </button>
              <button
                onClick={() => { handleDelete(); setShowMenu(false); }}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-400 hover:bg-red-500/10 rounded-lg transition-colors"
              >
                <Trash2 size={14} /> Sil
              </button>
            </div>
          )}
        </div>
      </motion.div>

      {/* ── Proje Header ── */}
      <motion.div variants={fadeUp} className="card-surface p-5 md:p-6">
        <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-2">
              {/* Durum badge */}
              <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium border ${statusInfo.bgClass} ${statusInfo.color}`}>
                <StatusIcon size={12} />
                {statusInfo.label}
              </span>

              {/* Tweet kaynak badge */}
              {project.sourceType === 'X_TWEET' && (
                <span className="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-medium bg-sky-500/10 border border-sky-500/20 text-sky-400">
                  <XIcon size={10} /> Tweet
                </span>
              )}
            </div>

            <h1 className="font-[family-name:var(--font-display)] text-xl md:text-2xl font-bold tracking-tight text-[var(--color-text-primary)] truncate">
              {project.title}
            </h1>

            {project.description && (
              <p className="text-sm text-[var(--color-text-muted)] mt-1.5 line-clamp-2">
                {project.description}
              </p>
            )}
          </div>

          {/* Meta bilgiler */}
          <div className="flex flex-wrap items-center gap-3 text-xs text-[var(--color-text-ghost)] shrink-0">
            <span className="flex items-center gap-1">
              <Clock size={12} /> {project.targetDuration}s
            </span>
            
            <select
              value={project.videoStyle}
              onChange={(e) => handleStyleChange(e.target.value)}
              disabled={isRendering}
              className="bg-[var(--color-bg-base)] border border-[var(--color-border-faint)] rounded-md px-2 py-0.5 text-xs text-[var(--color-text-secondary)] focus:outline-none focus:border-neutral-500/50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              {videoStyles.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.emoji} {s.label}
                </option>
              ))}
            </select>
            
            {project.videoStyle === 'CINEMATIC' && (
              <select
                value={project.cinematicReference || ''}
                onChange={(e) => handleCinematicReferenceChange(e.target.value)}
                disabled={isRendering}
                className="bg-[var(--color-bg-base)] border border-[var(--color-border-faint)] rounded-md px-2 py-0.5 text-xs text-[var(--color-text-secondary)] focus:outline-none focus:border-neutral-500/50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer w-44 truncate"
              >
                <option value="">🎬 Sinematik Yönetmen/Film...</option>
                {CINEMATIC_REFERENCES.map(ref => (
                  <option key={ref.value} value={ref.value}>{ref.label}</option>
                ))}
              </select>
            )}

            <span className="uppercase text-[10px] tracking-wider">{project.language}</span>
            <span className="text-[10px]">
              {new Date(project.createdAt).toLocaleDateString('tr-TR', {
                day: 'numeric', month: 'short', year: 'numeric',
              })}
            </span>
          </div>
        </div>

        {/* Tweet kaynak bilgisi */}
        {tweetData && (
          <div className="mt-4 p-3 rounded-xl bg-sky-500/5 border border-sky-500/10">
            <div className="flex items-center gap-2 mb-1">
              <XIcon size={14} />
              <span className="text-xs font-medium text-sky-400">
                @{tweetData.authorUsername as string}
              </span>
              {tweetData.viralScore && (
                <span className="text-[10px] px-1.5 py-0.5 rounded-md bg-amber-500/15 text-amber-400 font-medium">
                  🔥 {String(tweetData.viralScore)}/100
                </span>
              )}
            </div>
            <p className="text-xs text-[var(--color-text-muted)] line-clamp-2">
              {tweetData.text as string}
            </p>
          </div>
        )}

        {/* Aksiyon butonları */}
        <div className="flex flex-wrap items-center gap-2 mt-4 pt-4 border-t border-[var(--color-border-faint)]">
          {/* Senaryo üret (draft, senaryo yok) */}
          {!hasScript && (
            <button
              onClick={handleGenerateScript}
              disabled={isRendering || generateScriptMutation.isPending}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] text-sm font-medium hover:bg-neutral-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {generateScriptMutation.isPending ? (
                <Loader2 size={15} className="animate-spin" />
              ) : (
                <Sparkles size={15} />
              )}
              AI ile Senaryo Üret
            </button>
          )}

          {/* Senaryo yeniden üret (draft/failed, senaryo var) */}
          {hasScript && (
            <button
              onClick={handleGenerateScript}
              disabled={isRendering || generateScriptMutation.isPending}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)] text-sm font-medium hover:bg-[var(--color-bg-surface)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {generateScriptMutation.isPending ? (
                <Loader2 size={15} className="animate-spin" />
              ) : (
                <RefreshCw size={15} />
              )}
              Senaryoyu Yeniden Üret
            </button>
          )}

          {/* Onayla ve video üretimini başlat */}
          {hasScript && (
            <button
              onClick={handleApprove}
              disabled={isRendering || approveMutation.isPending}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] text-sm font-medium hover:bg-neutral-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {approveMutation.isPending ? (
                <Loader2 size={15} className="animate-spin" />
              ) : (
                <Play size={15} />
              )}
              Onayla & Video Üret
            </button>
          )}

          {/* Üretimi İptal Et (Sadece aktif işlem varsa) */}
          {isRendering && (
            <button
              onClick={handleCancelRender}
              disabled={cancelRenderMutation.isPending}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-red-500/10 text-red-400 text-sm font-medium hover:bg-red-500/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {cancelRenderMutation.isPending ? (
                <Loader2 size={15} className="animate-spin" />
              ) : (
                <X size={15} />
              )}
              Üretimi İptal Et
            </button>
          )}
        </div>

        {/* Hata mesajı — kapatılabilir ve aksiyon butonlu */}
        {project.errorMessage && (
          <div className="mt-3 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
            <div className="flex items-center justify-between mb-1">
              <div className="flex items-center gap-2">
                <AlertCircle size={14} className="text-red-400" />
                <span className="text-xs font-medium text-red-400">Hata</span>
              </div>
              <button
                onClick={() => {
                  // Sayfayı yeniden yükleyerek güncel veriyi al
                  refetch();
                }}
                className="text-red-400/60 hover:text-red-400 transition-colors"
                title="Kapat"
              >
                <X size={14} />
              </button>
            </div>
            <p className="text-xs text-red-400/80 mb-2">{project.errorMessage}</p>
            {hasScript && (
              <button
                onClick={handleGenerateScript}
                disabled={generateScriptMutation.isPending}
                className="text-xs px-3 py-1.5 rounded-md bg-red-500/20 text-red-300 hover:bg-red-500/30 transition-colors disabled:opacity-50"
              >
                {generateScriptMutation.isPending ? 'Üretiliyor...' : '🔄 Senaryoyu Yeniden Üret'}
              </button>
            )}
          </div>
        )}
      </motion.div>

      {/* ── Render Progress (WebSocket) ── */}
      {isRendering && (
        <motion.div variants={fadeUp}>
          <RenderProgress renderState={renderState} projectStatus={project.status} />
        </motion.div>
      )}

      {/* ── Video Player (tamamlandıysa) ── */}
      {isCompleted && project.finalVideoUrl && (
        <motion.div variants={fadeUp}>
          <VideoPlayer
            videoUrl={project.finalVideoUrl}
            thumbnailUrl={project.thumbnailUrl}
            title={project.title}
          />
        </motion.div>
      )}

      {/* ── Sahneler ── */}
      {hasScript && (
        <motion.div variants={fadeUp}>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-semibold text-[var(--color-text-primary)] flex items-center gap-2">
              <Film size={15} className="text-neutral-400" />
              Senaryo — {project.scenes!.length} sahne
            </h2>
            <span className="text-[10px] text-[var(--color-text-ghost)]">
              Toplam: {project.scenes!.reduce((sum, s) => sum + s.duration, 0)}s
            </span>
          </div>

          <div 
            ref={parentRef} 
            className="w-full h-[800px] overflow-auto pr-2 rounded-xl"
          >
            <div
              style={{
                height: `${rowVirtualizer.getTotalSize()}px`,
                width: '100%',
                position: 'relative',
              }}
            >
              {rowVirtualizer.getVirtualItems().map((virtualRow) => {
                const scene = project.scenes![virtualRow.index];
                return (
                  <div
                    key={virtualRow.key}
                    data-index={virtualRow.index}
                    ref={rowVirtualizer.measureElement}
                    style={{
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: '100%',
                      transform: `translateY(${virtualRow.start}px)`,
                      paddingBottom: '12px',
                    }}
                  >
                    <SceneCard
                      scene={scene}
                      isEditable={isEditable}
                      isRendering={isRendering}
                      onUpdate={handleSceneUpdate}
                      onRegenerate={handleSceneRegenerate}
                      onGenerateImage={handleGenerateImage}
                      onUpscaleImage={handleUpscaleImage}
                      isRegenerating={regeneratingSceneId === scene.id}
                      isGeneratingImage={generatingImageId === scene.id}
                      isUpscalingImage={upscalingImageId === scene.id}
                    />
                  </div>
                );
              })}
            </div>
          </div>
        </motion.div>
      )}

      {/* ── SEO & Sosyal Medya Power Engine ── */}
      {hasScript && (
        <motion.div variants={fadeUp}>
          <div className="card-surface p-5 rounded-2xl border border-[var(--color-border-subtle)]">
            {/* Header */}
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-4">
                <h2 className="text-sm font-semibold text-[var(--color-text-primary)] flex items-center gap-2">
                  <TrendingUp size={15} className="text-emerald-400" />
                  SEO & Sosyal Medya
                </h2>
                <button
                  onClick={() => generateSocialMutation.mutate(id as string)}
                  disabled={generateSocialMutation.isPending}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-medium bg-gradient-to-r from-emerald-500/20 to-teal-500/20 text-emerald-300 hover:from-emerald-500/30 hover:to-teal-500/30 border border-emerald-500/20 transition-all disabled:opacity-50"
                  title="Eksik SEO veya Sosyal Medya içeriklerini yapay zeka ile yeniden üret"
                >
                  {generateSocialMutation.isPending ? (
                    <Loader2 size={12} className="animate-spin" />
                  ) : (
                    <RefreshCw size={12} />
                  )}
                  Tümünü Yeniden Üret
                </button>
              </div>
              {project.seoScore != null && (
                <div className="flex items-center gap-2">
                  <div className="relative w-10 h-10">
                    <svg className="w-10 h-10 -rotate-90" viewBox="0 0 36 36">
                      <path
                        d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                        fill="none"
                        stroke="rgba(255,255,255,0.1)"
                        strokeWidth="3"
                      />
                      <path
                        d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                        fill="none"
                        stroke={project.seoScore >= 80 ? '#34d399' : project.seoScore >= 50 ? '#fbbf24' : '#f87171'}
                        strokeWidth="3"
                        strokeDasharray={`${project.seoScore}, 100`}
                        strokeLinecap="round"
                      />
                    </svg>
                    <span className="absolute inset-0 flex items-center justify-center text-[10px] font-bold text-white">
                      {project.seoScore}
                    </span>
                  </div>
                  <span className="text-[10px] text-[var(--color-text-muted)]">SEO<br/>Skoru</span>
                </div>
              )}
            </div>

            {/* ─── Başlık Yönetimi ─── */}
            <div className="mb-5">
              <div className="flex items-center justify-between mb-2">
                <h3 className="text-xs font-semibold text-[var(--color-text-secondary)] uppercase tracking-wider">
                  📌 SEO Başlıkları
                </h3>
                <button
                  onClick={handleGenerateSeoTitles}
                  disabled={seoTitlesMutation.isPending}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-medium bg-gradient-to-r from-violet-500/20 to-purple-500/20 text-violet-300 hover:from-violet-500/30 hover:to-purple-500/30 border border-violet-500/20 transition-all disabled:opacity-50"
                >
                  {seoTitlesMutation.isPending ? (
                    <Loader2 size={12} className="animate-spin" />
                  ) : (
                    <Zap size={12} />
                  )}
                  5 Yeni Başlık Üret
                </button>
              </div>

              {/* Mevcut başlık */}
              <div className="bg-[var(--color-bg-elevated)] rounded-xl p-3 mb-2 border border-emerald-500/20">
                <div className="flex items-center gap-2 mb-1">
                  <CheckCircle2 size={12} className="text-emerald-400" />
                  <span className="text-[10px] text-emerald-400 font-medium uppercase">Aktif Başlık</span>
                </div>
                <p className="text-sm font-medium text-white">{project.seoTitle || project.title}</p>
              </div>

              {/* Alternatif başlıklar */}
              {project.seoTitleAlts && project.seoTitleAlts.length > 0 && (
                <div className="space-y-1.5">
                  {project.seoTitleAlts.map((alt, i) => (
                    <button
                      key={i}
                      onClick={() => handleSelectTitle(alt)}
                      disabled={selectTitleMutation.isPending || alt === (project.seoTitle || project.title)}
                      className={`w-full text-left p-2.5 rounded-lg border text-xs transition-all ${
                        alt === (project.seoTitle || project.title)
                          ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-300'
                          : 'border-[var(--color-border-subtle)] hover:border-violet-500/30 hover:bg-violet-500/5 text-[var(--color-text-secondary)]'
                      } disabled:opacity-40`}
                    >
                      <span className="text-[10px] text-[var(--color-text-ghost)] mr-2">#{i + 1}</span>
                      {alt}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* ─── SEO Keywords ─── */}
            {project.seoKeywords && project.seoKeywords.length > 0 && (
              <div className="mb-5">
                <h3 className="text-xs font-semibold text-[var(--color-text-secondary)] uppercase tracking-wider mb-2 flex items-center gap-1.5">
                  <Search size={12} />
                  Anahtar Kelimeler ({project.seoKeywords.length})
                </h3>
                <div className="flex flex-wrap gap-1.5">
                  {project.seoKeywords.map((kw, i) => {
                    const colors = [
                      'bg-blue-500/15 text-blue-300 border-blue-500/20',
                      'bg-emerald-500/15 text-emerald-300 border-emerald-500/20',
                      'bg-amber-500/15 text-amber-300 border-amber-500/20',
                      'bg-violet-500/15 text-violet-300 border-violet-500/20',
                      'bg-rose-500/15 text-rose-300 border-rose-500/20',
                      'bg-cyan-500/15 text-cyan-300 border-cyan-500/20',
                    ];
                    return (
                      <span
                        key={i}
                        className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium border ${colors[i % colors.length]}`}
                      >
                        <Tag size={10} />
                        {kw}
                      </span>
                    );
                  })}
                </div>
              </div>
            )}

            {/* ─── Hashtag'ler ─── */}
            {project.scriptJson?.seo?.hashtags && project.scriptJson.seo.hashtags.length > 0 && (
              <div className="mb-5">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-xs font-semibold text-[var(--color-text-secondary)] uppercase tracking-wider flex items-center gap-1.5">
                    <Hash size={12} />
                    Hashtag&apos;ler
                  </h3>
                  <button
                    onClick={() => copyToClipboard(
                      project.scriptJson!.seo.hashtags.map((h: string) => `#${h}`).join(' '),
                      'hashtags'
                    )}
                    className="flex items-center gap-1 text-[10px] text-[var(--color-text-muted)] hover:text-white transition-colors"
                  >
                    {copiedField === 'hashtags' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} />}
                    Tümünü Kopyala
                  </button>
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {project.scriptJson.seo.hashtags.map((tag: string, i: number) => (
                    <span
                      key={i}
                      className="px-2.5 py-1 rounded-full text-[11px] font-medium bg-sky-500/10 text-sky-300 border border-sky-500/20"
                    >
                      #{tag}
                    </span>
                  ))}
                  {/* Trending hashtag'ler */}
                  {project.scriptJson.seo.trendingHashtags?.map((tag: string, i: number) => (
                    <span
                      key={`trend-${i}`}
                      className="px-2.5 py-1 rounded-full text-[11px] font-medium bg-orange-500/15 text-orange-300 border border-orange-500/20 flex items-center gap-1"
                    >
                      <TrendingUp size={10} />
                      #{tag}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* ─── Sosyal Medya Caption'ları ─── */}
            {project.socialContent && (
              <div>
                <h3 className="text-xs font-semibold text-[var(--color-text-secondary)] uppercase tracking-wider mb-3 flex items-center gap-1.5">
                  <Sparkles size={12} />
                  Sosyal Medya İçerikleri
                </h3>

                {/* Tab navigasyonu */}
                <div className="flex gap-1 mb-3 p-1 bg-[var(--color-bg-elevated)] rounded-xl">
                  {[
                    { key: 'youtube' as const, label: 'YouTube', icon: YouTubeIcon, color: 'text-red-400' },
                    { key: 'tiktok' as const, label: 'TikTok', icon: Film, color: 'text-cyan-400' },
                    { key: 'instagram' as const, label: 'Instagram', icon: InstagramIcon, color: 'text-pink-400' },
                    { key: 'twitter' as const, label: 'X', icon: XIcon, color: 'text-white' },
                  ].map((tab) => (
                    <button
                      key={tab.key}
                      onClick={() => setActiveCaptionTab(tab.key)}
                      className={`flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-[11px] font-medium transition-all ${
                        activeCaptionTab === tab.key
                          ? 'bg-[var(--color-bg-surface)] text-white shadow-sm'
                          : 'text-[var(--color-text-muted)] hover:text-white'
                      }`}
                    >
                      <tab.icon size={12} className={activeCaptionTab === tab.key ? tab.color : ''} />
                      <span className="hidden sm:inline">{tab.label}</span>
                    </button>
                  ))}
                </div>

                {/* Caption içeriği */}
                <div className="bg-[var(--color-bg-elevated)] rounded-xl p-4 border border-[var(--color-border-subtle)]">
                  {activeCaptionTab === 'youtube' && (
                    <div className="space-y-3">
                      {project.socialContent.youtubeTitle && (
                        <div>
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-[10px] text-[var(--color-text-muted)] uppercase">Başlık</span>
                            <button onClick={() => copyToClipboard(project.socialContent!.youtubeTitle!, 'yt-title')} className="p-1 hover:bg-white/5 rounded">
                              {copiedField === 'yt-title' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} className="text-[var(--color-text-muted)]" />}
                            </button>
                          </div>
                          <p className="text-sm font-medium text-white">{project.socialContent.youtubeTitle}</p>
                        </div>
                      )}
                      {project.socialContent.youtubeDescription && (
                        <div>
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-[10px] text-[var(--color-text-muted)] uppercase">Açıklama</span>
                            <button onClick={() => copyToClipboard(project.socialContent!.youtubeDescription!, 'yt-desc')} className="p-1 hover:bg-white/5 rounded">
                              {copiedField === 'yt-desc' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} className="text-[var(--color-text-muted)]" />}
                            </button>
                          </div>
                          <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-line leading-relaxed">{project.socialContent.youtubeDescription}</p>
                        </div>
                      )}
                    </div>
                  )}

                  {activeCaptionTab === 'tiktok' && project.socialContent.tiktokCaption && (
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-[10px] text-[var(--color-text-muted)] uppercase">TikTok Caption</span>
                        <button onClick={() => copyToClipboard(project.socialContent!.tiktokCaption!, 'tiktok')} className="p-1 hover:bg-white/5 rounded">
                          {copiedField === 'tiktok' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} className="text-[var(--color-text-muted)]" />}
                        </button>
                      </div>
                      <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-line leading-relaxed">{project.socialContent.tiktokCaption}</p>
                    </div>
                  )}

                  {activeCaptionTab === 'instagram' && project.socialContent.instagramCaption && (
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-[10px] text-[var(--color-text-muted)] uppercase">Instagram Caption</span>
                        <button onClick={() => copyToClipboard(project.socialContent!.instagramCaption!, 'instagram')} className="p-1 hover:bg-white/5 rounded">
                          {copiedField === 'instagram' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} className="text-[var(--color-text-muted)]" />}
                        </button>
                      </div>
                      <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-line leading-relaxed">{project.socialContent.instagramCaption}</p>
                    </div>
                  )}

                  {activeCaptionTab === 'twitter' && project.socialContent.twitterText && (
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-[10px] text-[var(--color-text-muted)] uppercase">X (Twitter) Paylaşımı</span>
                        <button onClick={() => copyToClipboard(project.socialContent!.twitterText!, 'twitter')} className="p-1 hover:bg-white/5 rounded">
                          {copiedField === 'twitter' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} className="text-[var(--color-text-muted)]" />}
                        </button>
                      </div>
                      <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-line leading-relaxed">{project.socialContent.twitterText}</p>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* ─── SEO Açıklama ─── */}
            {project.seoDescription && (
              <div className="mt-4 pt-4 border-t border-[var(--color-border-subtle)]">
                <div className="flex items-center justify-between mb-1.5">
                  <span className="text-[10px] text-[var(--color-text-muted)] uppercase">Meta Description</span>
                  <button onClick={() => copyToClipboard(project.seoDescription!, 'seo-desc')} className="p-1 hover:bg-white/5 rounded">
                    {copiedField === 'seo-desc' ? <Check size={10} className="text-emerald-400" /> : <Copy size={10} className="text-[var(--color-text-muted)]" />}
                  </button>
                </div>
                <p className="text-xs text-[var(--color-text-secondary)] leading-relaxed">{project.seoDescription}</p>
              </div>
            )}
          </div>
        </motion.div>
      )}

      {/* ── Boş durum (senaryo yok) ── */}
      {!hasScript && isEditable && (
        <motion.div variants={fadeUp} className="card-surface p-8 text-center">
          <div className="w-16 h-16 rounded-2xl bg-[var(--color-bg-elevated)] mx-auto mb-4 flex items-center justify-center">
            <Sparkles size={28} className="text-neutral-400" />
          </div>
          <h3 className="text-base font-semibold mb-1.5">Henüz senaryo üretilmedi</h3>
          <p className="text-sm text-[var(--color-text-muted)] mb-4 max-w-sm mx-auto">
            AI'ın projeniz için etkileyici bir video senaryosu oluşturmasını sağlayın.
          </p>
          <button
            onClick={handleGenerateScript}
            disabled={generateScriptMutation.isPending}
            className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] text-sm font-medium hover:bg-neutral-800 transition-colors disabled:opacity-50"
          >
            {generateScriptMutation.isPending ? (
              <Loader2 size={15} className="animate-spin" />
            ) : (
              <Sparkles size={15} />
            )}
            Senaryo Üret
          </button>
        </motion.div>
      )}

      {/* ── Render Geçmişi ── */}
      {project.renderJobs && project.renderJobs.length > 0 && (
        <motion.div variants={fadeUp}>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-semibold text-[var(--color-text-primary)] flex items-center gap-2">
              <Clock size={15} className="text-neutral-400" />
              Render Geçmişi
            </h2>
            {project.status === 'GENERATING_MEDIA' || project.renderJobs.some((j: any) => j.status === 'QUEUED' || j.status === 'PROCESSING') ? (
              <button
                onClick={handleCancelRender}
                disabled={cancelRenderMutation.isPending}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500/20 text-xs font-medium transition-colors"
              >
                {cancelRenderMutation.isPending ? <Loader2 size={13} className="animate-spin" /> : <X size={13} />}
                İptal Et
              </button>
            ) : null}
          </div>
          <div className="space-y-2">
            {project.renderJobs.map((job) => (
              <div key={job.id} className="card-surface p-3 flex flex-col gap-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2.5">
                    <div className={`w-2 h-2 rounded-full ${
                      job.status === 'COMPLETED' ? 'bg-neutral-100' :
                      job.status === 'FAILED' ? 'bg-neutral-500' :
                      job.status === 'CANCELLED' ? 'bg-neutral-600' :
                      'bg-neutral-300 animate-pulse'
                    }`} />
                    <span className="text-xs text-[var(--color-text-secondary)]">
                      Deneme #{job.attemptNumber}
                    </span>
                    <span className="text-[10px] text-[var(--color-text-ghost)]">
                      {job.status}
                    </span>
                  </div>
                  <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-ghost)]">
                    {job.processingTimeMs && (
                      <span>{(job.processingTimeMs / 1000).toFixed(1)}s</span>
                    )}
                    {mounted ? (
                      <span>
                        {new Date(job.createdAt).toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' })}
                      </span>
                    ) : (
                      <span>--:--</span>
                    )}
                  </div>
                </div>
                {(job.status === 'QUEUED' || job.status === 'PROCESSING') && (
                  <div className="w-full bg-[var(--color-bg-surface)] rounded-full h-1.5 mt-1 overflow-hidden">
                    <div 
                      className="bg-neutral-300 h-1.5 rounded-full transition-all duration-1000 ease-out relative" 
                      style={{ width: `${job.progress || (job.status === 'QUEUED' ? 5 : 50)}%` }}
                    >
                      <div className="absolute inset-0 bg-white/20 animate-pulse" />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </motion.div>
      )}

      {/* ─── Çeviri Modal ─── */}
      {mounted && createPortal(
        <div className="portal-container">
          <AnimatePresence>
            {showTranslateModal && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.15 }}
                className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
                onClick={() => !isTranslating && setShowTranslateModal(false)}
              >
                <motion.div
                  initial={{ opacity: 0, scale: 0.95, y: 10 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.95, y: 10 }}
                  transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
                  className="relative bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] rounded-2xl p-6 max-w-sm w-full mx-4 shadow-2xl"
                  onClick={(e) => e.stopPropagation()}
                >
                  {/* Kapatma butonu */}
                  <button
                    onClick={() => setShowTranslateModal(false)}
                    disabled={isTranslating}
                    className="absolute top-3 right-3 p-1 rounded-lg text-[var(--color-text-ghost)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-surface)] transition-colors disabled:opacity-50"
                  >
                    <X size={16} />
                  </button>

                  {/* Icon */}
                  <div className="flex items-center justify-center w-12 h-12 rounded-full bg-blue-500/10 mb-4">
                    <Languages size={22} className="text-blue-400" />
                  </div>

                  {/* İçerik */}
                  <h3 className="text-base font-semibold text-[var(--color-text-primary)] mb-1.5">
                    Projeyi Çevir
                  </h3>
                  <p className="text-sm text-[var(--color-text-muted)] mb-3">
                    "{project?.title}" projesini başka bir dile çevirin. (1 kredi)
                  </p>

                  <select
                    value={targetLanguage}
                    onChange={(e) => setTargetLanguage(e.target.value)}
                    disabled={isTranslating}
                    className="w-full bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl px-4 py-2.5 text-sm text-[var(--color-text-primary)] mb-5 outline-none focus:border-blue-500"
                  >
                    <option value="">Dil Seçin...</option>
                    {languages.map((lang) => (
                      <option key={lang.code} value={lang.code}>
                        {lang.flag} {lang.label}
                      </option>
                    ))}
                  </select>

                  {/* Butonlar */}
                  <div className="flex items-center gap-3">
                    <button
                      onClick={() => setShowTranslateModal(false)}
                      disabled={isTranslating}
                      className="flex-1 px-4 py-2.5 rounded-xl border border-[var(--color-border-default)] text-sm font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-surface)] transition-colors disabled:opacity-50"
                    >
                      İptal
                    </button>
                    <button
                      onClick={confirmTranslate}
                      disabled={isTranslating || !targetLanguage}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {isTranslating ? (
                        <>
                          <Loader2 size={14} className="animate-spin" />
                          Çevriliyor...
                        </>
                      ) : (
                        <>
                          <Languages size={14} />
                          Çevir (1 🪙)
                        </>
                      )}
                    </button>
                  </div>
                </motion.div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>,
        document.body
      )}
    </motion.div>
  );
}
