"use client";

import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { createForumReply } from "@/lib/forum-api";
import { motion, AnimatePresence } from "framer-motion";
import {
  MessageSquare, ArrowLeft, Pin, Lock, Eye, MessageCircle,
  ThumbsUp, Heart, CheckCircle, Clock, MoreHorizontal, Reply,
  Share2, Flag, Bookmark, ChevronLeft, ChevronRight, User,
  Shield, Award, Star, Image as ImageIcon, Smile, Bold, Italic,
  Link as LinkIcon, List, Code, Send, Loader2, Sparkles, ShieldCheck, Zap
} from "lucide-react";
import { communityService } from "@/lib/services/community-service";
import ForumAiAssistantWidget from "@/components/forum/ForumAiAssistantWidget";
import ForumKvkkBlurModal from "@/components/forum/ForumKvkkBlurModal";

interface ForumTopic {
  id: string;
  title: string;
  slug: string;
  type: "NORMAL" | "STICKY" | "ANNOUNCEMENT" | "SOLVED";
  status: "OPEN" | "CLOSED";
  author: {
    id: string;
    name: string;
    avatar?: string;
    title?: string;
    isStaff?: boolean;
    reputation: number;
    postCount: number;
    joinedAt: string;
  };
  board: {
    id: string;
    name: string;
    slug: string;
  };
  viewCount: number;
  replyCount: number;
  reactionCount: number;
  isWatching: boolean;
  createdAt: string;
  tags: string[];
}

interface ForumPost {
  id: string;
  postNumber: number;
  author: {
    id: string;
    name: string;
    avatar?: string;
    title?: string;
    isStaff?: boolean;
    isOnline: boolean;
    reputation: number;
    postCount: number;
    joinedAt: string;
    badges: string[];
    signature?: string;
  };
  content: string;
  contentHtml: string;
  createdAt: string;
  editedAt?: string;
  editCount: number;
  reactionCount: number;
  reactions: {
    type: "like" | "thanks" | "helpful" | "love";
    count: number;
    userReacted: boolean;
  }[];
  isBestAnswer?: boolean;
}

export default function ForumTopicPage() {
  const params = useParams();
  const slug = params?.slug as string || '';
  
  const [topic, setTopic] = useState<any>(null);
  const [posts, setPosts] = useState<any[]>([]);
  const [replyContent, setReplyContent] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showReplyEditor, setShowReplyEditor] = useState(false);
  const [isSubmittingReply, setIsSubmittingReply] = useState(false);
  const [replyError, setReplyError] = useState<string | null>(null);
  const [showReportModal, setShowReportModal] = useState(false);
  const [reportTarget, setReportTarget] = useState<{ postId?: string; topicId?: string } | null>(null);
  const [reportReason, setReportReason] = useState('spam');
  const [reportDescription, setReportDescription] = useState('');
  const [reportSubmitting, setReportSubmitting] = useState(false);
  const [isKvkkModalOpen, setIsKvkkModalOpen] = useState(false);
  const { data: session, status } = useSession();

  const openReport = (target: { postId?: string; topicId?: string }) => {
    if (!session) {
      window.location.href = `/signup?callbackUrl=${encodeURIComponent(`/forum/topic/${slug}`)}`;
      return;
    }
    setReportTarget(target);
    setReportReason('spam');
    setReportDescription('');
    setShowReportModal(true);
  };

  const submitReport = async () => {
    if (!reportTarget) return;
    setReportSubmitting(true);
    try {
      await communityService.submitReport({
        ...reportTarget,
        reason: reportReason,
        description: reportDescription,
      });
      setShowReportModal(false);
      alert('Raporunuz alındı. Teşekkürler.');
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Rapor gönderilemedi');
    } finally {
      setReportSubmitting(false);
    }
  };

  const fetchTopic = async () => {
    if (!slug) return;
    
    try {
      setLoading(true);
      const response = await fetch(`/api/community/topic/${slug}`);
      
      if (response.ok) {
        const data = await response.json();
        if (data && data.title) {
          setTopic(data);
          setPosts(data.posts || []);
          setError(null);
          return;
        }
      }
      
      // Fallback from seed data
      const { FORUM_TOPICS_BY_SLUG, FORUM_USERS_MAP, FORUM_BOARDS_MAP, FORUM_CATEGORIES_MAP } = await import('@/lib/forum-seed-data');
      const seedTopic = FORUM_TOPICS_BY_SLUG.get(slug);
      if (seedTopic) {
        const author = FORUM_USERS_MAP.get(seedTopic.authorId);
        const board = FORUM_BOARDS_MAP.get(seedTopic.boardId);
        const category = board ? FORUM_CATEGORIES_MAP.get(board.catId) : null;

        const formattedPosts = seedTopic.posts.map((post, index) => {
          const postAuthor = FORUM_USERS_MAP.get(post.authorId);
          const authorName = postAuthor?.displayName || 'Anonim Satıcı';
          const postNumber = index + 1;
          const isFirstPost = index === 0;

          return {
            id: `${seedTopic.id}-p${postNumber}`,
            postNumber,
            content: post.content,
            contentHtml: post.content
              .replace(/### (.*?)\n/g, '<h3 class="text-base font-bold text-slate-900 dark:text-white mt-4 mb-2">$1</h3>')
              .replace(/#### (.*?)\n/g, '<h4 class="text-sm font-bold text-slate-800 dark:text-slate-200 mt-3 mb-1.5">$1</h4>')
              .replace(/\*\*(.*?)\*\*/g, '<strong class="font-bold text-slate-900 dark:text-white">$1</strong>')
              .replace(/`([^`]+)`/g, '<code class="px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-orange-600 font-mono text-xs">$1</code>')
              .replace(/^\* (.*?)$/gm, '<li class="ml-4 list-disc text-slate-700 dark:text-slate-300 my-1">$1</li>')
              .replace(/^\d+\. (.*?)$/gm, '<li class="ml-4 list-decimal text-slate-700 dark:text-slate-300 my-1">$1</li>')
              .replace(/\n\n/g, '<br><br>')
              .replace(/\n/g, '<br>'),
            author: {
              id: post.authorId,
              name: authorName,
              avatar: postAuthor?.avatarUrl || authorName.slice(0, 2).toUpperCase(),
              level: postAuthor?.level || 1,
              title: postAuthor?.customTitle || 'Onaylı Satıcı',
              xp: (postAuthor?.reputation || 200) * 1.5,
              group: postAuthor?.isStaff ? 'Yönetici' : 'Satıcı',
              groupColor: postAuthor?.isStaff ? '#ef4444' : '#10b981',
              reputation: postAuthor?.reputation || 100,
              postCount: postAuthor?.postCount || 10,
              joinedAt: 'Oca 2024',
              isOnline: true,
              badges: postAuthor?.levelTitle ? [postAuthor.levelTitle] : [],
              signature: postAuthor?.signature,
            },
            createdAt: '1 gün önce',
            isBestAnswer: post.isBestAnswer || (!isFirstPost && index === 1),
            reactionCount: 6,
            reactions: [
              { type: 'like', count: 4, userReacted: false },
              { type: 'helpful', count: 2, userReacted: false },
            ],
          };
        });

        const fallbackTopic = {
          id: seedTopic.id,
          title: seedTopic.title,
          slug: seedTopic.slug,
          status: seedTopic.status,
          type: seedTopic.type,
          viewCount: seedTopic.viewCount || 1450,
          replyCount: seedTopic.posts.length - 1,
          reactionCount: 18,
          createdAt: new Date(Date.now() - 86400000 * 2).toISOString(),
          isSolved: seedTopic.status === 'SOLVED' || seedTopic.type === 'SOLVED',
          isPinned: seedTopic.type === 'STICKY' || seedTopic.type === 'ANNOUNCEMENT',
          isHot: (seedTopic.viewCount || 0) > 3000,
          author: {
            id: seedTopic.authorId,
            name: author?.displayName || 'Pazaryonetimi Satıcısı',
            avatar: author?.avatarUrl || (author?.displayName || 'S').slice(0, 2).toUpperCase(),
            title: author?.customTitle || 'Satıcı',
            reputation: author?.reputation || 500,
            postCount: author?.postCount || 20,
          },
          board: board ? {
            id: board.id,
            name: board.name,
            slug: board.slug,
            category: category?.name || 'Pazaryerleri',
          } : null,
          posts: formattedPosts,
          tags: seedTopic.tags || [],
        };

        setTopic(fallbackTopic);
        setPosts(fallbackTopic.posts);
        setError(null);
        return;
      }
      
      throw new Error('Konu bulunamadı');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Bir hata oluştu');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTopic();
  }, [slug]);

  const handleReplySubmit = async () => {
    if (!replyContent.trim() || !slug) return;
    setIsSubmittingReply(true);
    setReplyError(null);
    try {
      await createForumReply(slug, replyContent.trim());
      setReplyContent("");
      await fetchTopic();
    } catch (error) {
      setReplyError(error instanceof Error ? error.message : "Cevap gönderilemedi.");
    } finally {
      setIsSubmittingReply(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-[#FAFAF9] dark:bg-[#0B1120] flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-orange-600 animate-spin mx-auto mb-4" />
          <p className="text-slate-600 dark:text-slate-400">Konu yükleniyor...</p>
        </div>
      </div>
    );
  }

  if (error || !topic) {
    return (
      <div className="min-h-screen bg-[#FAFAF9] dark:bg-[#0B1120] flex items-center justify-center">
        <div className="text-center">
          <MessageSquare className="w-16 h-16 text-slate-300 dark:text-slate-600 mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">
            {error || 'Konu bulunamadı'}
          </h1>
          <Link 
            href="/forum" 
            className="text-orange-600 hover:underline inline-flex items-center gap-2"
          >
            <ChevronLeft size={18} />
            Foruma Dön
          </Link>
        </div>
      </div>
    );
  }

  const getReactionIcon = (type: string) => {
    switch (type) {
      case "like": return <ThumbsUp className="w-4 h-4" />;
      case "love": return <Heart className="w-4 h-4" />;
      case "thanks": return <Star className="w-4 h-4" />;
      case "helpful": return <CheckCircle className="w-4 h-4" />;
      default: return <ThumbsUp className="w-4 h-4" />;
    }
  };

  return (
    <div className="min-h-screen bg-slate-50">
      {/* Navigation */}
      <div className="bg-white border-b border-slate-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center gap-2 text-sm text-slate-500">
            <Link href="/forum" className="hover:text-orange-600">Forum</Link>
            <ChevronLeft className="w-4 h-4 rotate-180" />
            {topic ? (
              <>
                <Link href={`/forum`} className="hover:text-orange-600">{topic.board?.name || topic.category || 'Forum'}</Link>
                <ChevronLeft className="w-4 h-4 rotate-180" />
                <span className="text-slate-700 font-medium truncate">{topic.title}</span>
              </>
            ) : (
              <span className="text-slate-400">Yükleniyor...</span>
            )}
          </div>
        </div>
      </div>

      {!topic ? (
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
          <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
            <div className="animate-pulse flex flex-col items-center">
              <div className="w-12 h-12 bg-slate-200 rounded-full mb-4"></div>
              <div className="w-48 h-4 bg-slate-200 rounded mb-2"></div>
              <div className="w-32 h-4 bg-slate-200 rounded"></div>
            </div>
          </div>
        </div>
      ) : (
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* Topic Header */}
        <div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-3">
                {topic.type === "STICKY" && (
                  <span className="px-2 py-1 bg-red-100 text-red-700 text-xs rounded-full flex items-center gap-1">
                    <Pin className="w-3 h-3" /> Sabit
                  </span>
                )}
                {topic.type === "ANNOUNCEMENT" && (
                  <span className="px-2 py-1 bg-orange-100 text-orange-700 text-xs rounded-full flex items-center gap-1">
                    <Shield className="w-3 h-3" /> Duyuru
                  </span>
                )}
                {topic.type === "SOLVED" && (
                  <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full flex items-center gap-1">
                    <CheckCircle className="w-3 h-3" /> Çözüldü
                  </span>
                )}
                {topic.status === "CLOSED" && (
                  <span className="px-2 py-1 bg-slate-100 text-slate-600 text-xs rounded-full flex items-center gap-1">
                    <Lock className="w-3 h-3" /> Kapalı
                  </span>
                )}
              </div>
              <h1 className="text-2xl font-bold text-slate-900">{topic.title}</h1>
              <div className="flex items-center gap-4 mt-3 text-sm text-slate-500">
                <span className="flex items-center gap-1"><Eye className="w-4 h-4" /> {topic.viewCount.toLocaleString()} görüntülenme</span>
                <span className="flex items-center gap-1"><MessageCircle className="w-4 h-4" /> {topic.replyCount} cevap</span>
                <span className="flex items-center gap-1"><ThumbsUp className="w-4 h-4" /> {topic.reactionCount} beğeni</span>
              </div>
              <div className="flex flex-wrap gap-2 mt-3">
                {topic.tags?.map((tag: any, idx: number) => {
                  const tagName = typeof tag === 'string' ? tag : tag?.name || '';
                  const tagSlug = typeof tag === 'string' ? tag : tag?.slug || tag?.name || `tag-${idx}`;
                  return (
                    <span
                      key={tagSlug}
                      className="px-3 py-1 bg-orange-50 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400 rounded-full text-xs font-semibold"
                    >
                      #{tagName}
                    </span>
                  );
                })}
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button className="p-2 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg" title="Abone Ol">
                <Bookmark className="w-5 h-5 text-slate-400" />
              </button>
              <button className="p-2 hover:bg-slate-100 rounded-lg" title="Paylaş">
                <Share2 className="w-5 h-5 text-slate-400" />
              </button>
              <button
                type="button"
                className="p-2 hover:bg-slate-100 rounded-lg"
                title="Rapor Et"
                onClick={() => openReport({ topicId: topic.id })}
              >
                <Flag className="w-5 h-5 text-slate-400" />
              </button>
            </div>
          </div>
        </div>

        {/* Pazaryonetimi AI Bot Solution Widget */}
        <div className="mb-6">
          <ForumAiAssistantWidget
            topicTitle={topic.title}
            topicBoard={topic.board?.name}
            recommendedTool={{
              name: 'Dinamik Fiyat & Repricer Motoru',
              description: 'Kâr marjınızı ve taban fiyatınızı koruyarak otomatik fiyat güncelleyin.',
              url: '/features/repricer'
            }}
          />
        </div>

        {/* Posts */}
        <div className="space-y-4">
          {posts.map((post, index) => (
            <motion.div
              key={post.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.05 }}
              id={`post-${post.postNumber}`}
              className={`bg-white rounded-xl border ${post.isBestAnswer ? "border-green-500 ring-1 ring-green-500" : "border-slate-200"} overflow-hidden`}
            >
              {/* Best Answer Banner */}
              {post.isBestAnswer && (
                <div className="bg-green-500 text-white px-4 py-2 flex items-center gap-2">
                  <CheckCircle className="w-4 h-4" />
                  <span className="font-medium text-sm">En İyi Cevap</span>
                </div>
              )}

              <div className="flex">
                {/* Author Sidebar */}
                <div className="w-48 bg-slate-50 p-4 border-r border-slate-200 hidden sm:block">
                  <div className="text-center">
                    <div className="relative inline-block">
                      <div className={`w-16 h-16 mx-auto rounded-full flex items-center justify-center text-white text-xl font-bold ${
                        post.author.isStaff ? "bg-gradient-to-br from-red-500 to-orange-500" : "bg-gradient-to-br from-amber-500 to-purple-600"
                      }`}>
                        {post.author.name.charAt(0).toUpperCase()}
                      </div>
                      {post.author.isOnline && (
                        <div className="absolute bottom-0 right-0 w-4 h-4 bg-green-500 rounded-full border-2 border-white"></div>
                      )}
                    </div>
                    <Link href={`/forum/user/${post.author.id}`} className="block font-semibold text-slate-900 mt-3 hover:text-orange-600">
                      {post.author.name}
                    </Link>
                    {post.author.title && (
                      <p className="text-xs text-slate-500 mt-1">{post.author.title}</p>
                    )}
                    {post.author.isStaff && (
                      <span className="inline-block px-2 py-0.5 bg-red-100 text-red-700 text-xs rounded-full mt-2">
                        Yetkili
                      </span>
                    )}
                  </div>

                  <div className="mt-4 pt-4 border-t border-slate-200 space-y-2 text-xs">
                    <div className="flex justify-between">
                      <span className="text-slate-500">İtibar</span>
                      <span className="font-medium text-green-600">+{post.author.reputation}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">Mesaj</span>
                      <span className="font-medium">{post.author.postCount.toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">Katılım</span>
                      <span className="font-medium">{post.author.joinedAt}</span>
                    </div>
                  </div>

                  {post.author.badges?.length > 0 && (
                    <div className="mt-4 flex flex-wrap gap-1">
                      {post.author.badges.map((badge: string) => (
                        <span key={badge} className="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded" title={badge}>
                          <Award className="w-3 h-3" />
                        </span>
                      ))}
                    </div>
                  )}
                </div>

                {/* Post Content */}
                <div className="flex-1 p-4">
                  {/* Mobile Author */}
                  <div className="sm:hidden flex items-center gap-3 mb-4">
                    <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-bold ${
                      post.author.isStaff ? "bg-red-500" : "bg-orange-500"
                    }`}>
                      {post.author.name.charAt(0)}
                    </div>
                    <div>
                      <p className="font-semibold text-slate-900">{post.author.name}</p>
                      <p className="text-xs text-slate-500">{post.author.postCount} mesaj</p>
                    </div>
                  </div>

                  {/* Post Meta */}
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2 text-sm text-slate-500">
                      <Link href={`#post-${post.postNumber}`} className="font-medium text-slate-700 hover:text-orange-600">
                        #{post.postNumber}
                      </Link>
                      <span>•</span>
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" /> {post.createdAt}
                      </span>
                      {post.editedAt && (
                        <span className="text-slate-400">(düzenlendi: {post.editedAt})</span>
                      )}
                    </div>
                  </div>

                  {/* Content */}
                  <div 
                    className="prose prose-slate max-w-none"
                    dangerouslySetInnerHTML={{ __html: post.contentHtml }}
                  />

                  {/* Signature */}
                  {post.author.signature && (
                    <div className="mt-6 pt-4 border-t border-slate-200 text-sm text-slate-500 italic">
                      {post.author.signature}
                    </div>
                  )}

                  {/* Actions */}
                  <div className="flex items-center justify-between mt-6 pt-4 border-t border-slate-100">
                    <div className="flex items-center gap-2">
                      {post.reactions?.map((reaction: {type: string; count: number; userReacted?: boolean}) => (
                        <button
                          key={reaction.type}
                          className={`flex items-center gap-1 px-3 py-1.5 rounded-full text-sm ${
                            reaction.userReacted
                              ? "bg-orange-100 text-orange-700"
                              : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                          }`}
                        >
                          {getReactionIcon(reaction.type)}
                          <span>{reaction.count}</span>
                        </button>
                      ))}
                      <button className="p-2 hover:bg-slate-100 rounded-lg text-slate-400">
                        <Smile className="w-4 h-4" />
                      </button>
                    </div>
                    <div className="flex items-center gap-2">
                      <button className="flex items-center gap-1 px-3 py-1.5 text-slate-600 hover:bg-slate-100 rounded-lg text-sm">
                        <Reply className="w-4 h-4" /> Cevapla
                      </button>
                      <button className="flex items-center gap-1 px-3 py-1.5 text-slate-600 hover:bg-slate-100 rounded-lg text-sm">
                        <Share2 className="w-4 h-4" /> Alıntı
                      </button>
                      <button
                        type="button"
                        className="p-2 hover:bg-slate-100 rounded-lg text-slate-400"
                        title="Rapor et"
                        onClick={() => openReport({ postId: post.id })}
                      >
                        <Flag className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          ))}
        </div>

        {/* Reply Editor */}
        {topic.status === "OPEN" && (
          <div className="mt-6 bg-white rounded-xl border border-slate-200 p-4">
            <h3 className="font-bold text-slate-800 mb-4 flex items-center gap-2">
              <Reply className="w-5 h-5" /> Cevap Yaz
            </h3>
            {status === "unauthenticated" ? (
              <div className="text-center py-8">
                <p className="text-slate-600 mb-4">Cevap yazmak için giriş yapmalısınız.</p>
                <Link href={`/login?callbackUrl=/forum/topic/${slug}`} className="inline-flex px-5 py-2.5 bg-orange-600 text-white font-bold rounded-xl hover:bg-orange-500">
                  Giriş Yap
                </Link>
              </div>
            ) : (
            <div className="space-y-3">
              <div className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg border border-slate-200">
                <button className="p-1.5 hover:bg-slate-200 rounded" title="Kalın">
                  <Bold className="w-4 h-4 text-slate-600" />
                </button>
                <button className="p-1.5 hover:bg-slate-200 rounded" title="İtalik">
                  <Italic className="w-4 h-4 text-slate-600" />
                </button>
                <button className="p-1.5 hover:bg-slate-200 rounded" title="Bağlantı">
                  <LinkIcon className="w-4 h-4 text-slate-600" />
                </button>
                <button className="p-1.5 hover:bg-slate-200 rounded" title="Liste">
                  <List className="w-4 h-4 text-slate-600" />
                </button>
                <button className="p-1.5 hover:bg-slate-200 rounded" title="Kod">
                  <Code className="w-4 h-4 text-slate-600" />
                </button>
                <div className="w-px h-6 bg-slate-300 mx-1"></div>
                <button
                  type="button"
                  onClick={() => setIsKvkkModalOpen(true)}
                  className="px-2 py-1 bg-orange-50 hover:bg-orange-100 text-orange-700 text-xs font-bold rounded flex items-center gap-1 border border-orange-200 transition-colors"
                  title="Ekran Görüntüsü Yükle ve KVKK Gizle"
                >
                  <ShieldCheck className="w-3.5 h-3.5 text-orange-600" />
                  <span>KVKK Ekran Maskele</span>
                </button>
                <button className="p-1.5 hover:bg-slate-200 rounded" title="Emoji">
                  <Smile className="w-4 h-4 text-slate-600" />
                </button>
              </div>
              <textarea
                value={replyContent}
                onChange={(e) => setReplyContent(e.target.value)}
                placeholder="Cevabınızı buraya yazın..."
                className="w-full h-32 px-4 py-3 border border-slate-200 rounded-lg resize-none focus:ring-2 focus:ring-orange-500"
              />
              {replyError && (
                <p className="text-sm text-red-600">{replyError}</p>
              )}
              <div className="flex justify-between items-center">
                <p className="text-sm text-slate-500">{session?.user?.name || "Üye"} olarak cevaplıyorsunuz</p>
                <button
                  type="button"
                  onClick={handleReplySubmit}
                  disabled={!replyContent.trim() || isSubmittingReply}
                  className="flex items-center gap-2 px-6 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-500 font-medium disabled:opacity-50"
                >
                  {isSubmittingReply ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                  Gönder
                </button>
              </div>
            </div>
            )}
          </div>
        )}

        {/* Pagination */}
        <div className="mt-6 flex items-center justify-center gap-2">
          <button className="p-2 hover:bg-slate-200 rounded-lg disabled:opacity-50" disabled>
            <ChevronLeft className="w-5 h-5" />
          </button>
          {[1, 2, 3, "...", 10].map((page, i) => (
            <button
              key={i}
              className={`w-10 h-10 rounded-lg font-medium ${
                page === 1
                  ? "bg-orange-600 text-white"
                  : "hover:bg-slate-200 text-slate-700"
              }`}
            >
              {page}
            </button>
          ))}
          <button className="p-2 hover:bg-slate-200 rounded-lg">
            <ChevronRight className="w-5 h-5" />
          </button>
        </div>
      </div>
      )}

      {showReportModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
          <div className="bg-white rounded-2xl w-full max-w-md p-6 shadow-xl">
            <h3 className="text-lg font-bold text-slate-900 mb-4">İçeriği Rapor Et</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Neden</label>
                <select
                  value={reportReason}
                  onChange={(e) => setReportReason(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg"
                >
                  <option value="spam">Spam</option>
                  <option value="offensive">Hakaret / Ayrımcılık</option>
                  <option value="harassment">Taciz</option>
                  <option value="off_topic">Konu dışı</option>
                  <option value="duplicate">Tekrar</option>
                  <option value="other">Diğer</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Açıklama</label>
                <textarea
                  value={reportDescription}
                  onChange={(e) => setReportDescription(e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg"
                  placeholder="Kısa açıklama (opsiyonel)"
                />
              </div>
              <div className="flex gap-3">
                <button
                  type="button"
                  onClick={() => setShowReportModal(false)}
                  className="flex-1 py-2.5 border border-slate-200 rounded-lg font-medium"
                >
                  İptal
                </button>
                <button
                  type="button"
                  onClick={submitReport}
                  disabled={reportSubmitting}
                  className="flex-1 py-2.5 bg-orange-600 text-white rounded-lg font-medium disabled:opacity-60"
                >
                  {reportSubmitting ? 'Gönderiliyor...' : 'Raporla'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* KVKK Privacy Blur Modal */}
      <ForumKvkkBlurModal
        isOpen={isKvkkModalOpen}
        onClose={() => setIsKvkkModalOpen(false)}
        onImageMasked={(dataUrl) => {
          setReplyContent((prev) => prev + `\n\n![Maskelenmiş Ekran Görüntüsü](${dataUrl})\n`);
        }}
      />
    </div>
  );
}
