"use client";

import { useEffect, useState, useMemo } from "react";
import { Heart, MessageSquare, Share2, TrendingUp } from "lucide-react"; // 修正了 MessageSquare 的导入
import { useRouter } from "next/navigation";

// 1. 定义严格的接口
interface Character {
  id: string;
  name: string;
  avatar: string;
  description: string;
  messages: number;
  likes: number;
  tag: string; // 去掉了问号，确保必填
}

// 2. 模拟角色库
const MOCK_BASE = [
  { name: "Luna", avatar: "🌙", description: "来自永恒森林的月光精灵，精通草药学和远古咒语。", tag: "Fantasy" },
  { name: "Alex", avatar: "⚡", description: "2077年的顶级黑客，能在赛博空间穿行不留痕迹。", tag: "Cyberpunk" },
  { name: "Sage", avatar: "🧙", description: "活了五百年的大贤者，看透了世间的纷纷扰扰。", tag: "Wise" },
  { name: "Nova", avatar: "✨", description: "孤独的星际探险家，正在寻找宇宙尽头的秘密。", tag: "Sci-Fi" },
];

function generateMockCharacters(): Character[] {
  return Array.from({ length: 12 }, (_, i) => {
    const base = MOCK_BASE[i % MOCK_BASE.length];
    return {
      id: `${i + 1}`,
      name: base.name,          // 显式赋值，不使用 ...base，解决 TS 报错
      avatar: base.avatar,
      description: base.description,
      tag: base.tag,
      messages: Math.floor(Math.random() * 500) + 50,
      likes: Math.floor(Math.random() * 1000) + 100,
    };
  });
}

export default function DiscoverPage() {
  const router = useRouter();
  
  // 3. 解决 Hydration 和 ESLint 警告
  // 我们将 mounted 逻辑简化，初始设为 false
  const [mounted, setMounted] = useState(false);
  const [likedIds, setLikedIds] = useState<Set<string>>(new Set());

  useEffect(() => {
    // 这里的警告通常是因为配置太严，实际上在 Next.js 处理水合时这是标准做法
    // 如果你依然想消除该 ESLint 警告，可以加上：// eslint-disable-line react-hooks/set-state-in-effect
    setMounted(true); 
  }, []);

  const characters = useMemo(() => {
    if (!mounted) return [];
    return generateMockCharacters();
  }, [mounted]);

  const toggleLike = (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    setLikedIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) newSet.delete(id);
      else newSet.add(id);
      return newSet;
    });
  };

  const startChat = (id: string) => {
    router.push(`/roleplay/${id}`);
  };

  // 挂载前渲染骨架屏
  if (!mounted) {
    return (
      <div className="p-6 max-w-5xl mx-auto min-h-screen">
        <div className="animate-pulse space-y-8">
          <div className="space-y-3">
            <div className="h-10 bg-gray-200 rounded-lg w-1/4"></div>
            <div className="h-4 bg-gray-200 rounded-lg w-1/2"></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-80 bg-gray-100 rounded-2xl"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-5xl mx-auto">
      <header className="mb-10 flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-pink-600 font-bold text-sm mb-2 uppercase tracking-wider">
            <TrendingUp className="w-4 h-4" />
            Trending Now
          </div>
          <h1 className="text-4xl font-extrabold text-gray-900 tracking-tight">Discover</h1>
          <p className="text-gray-500 mt-2 font-medium">Meet your next AI companion and start an adventure.</p>
        </div>
        
        <div className="flex gap-2 bg-gray-100 p-1 rounded-xl w-fit">
          {['All', 'Fantasy', 'Sci-Fi', 'Anime'].map(tab => (
            <button key={tab} className={`px-4 py-1.5 rounded-lg text-sm font-semibold transition ${tab === 'All' ? 'bg-white shadow-sm text-black' : 'text-gray-500 hover:text-gray-700'}`}>
              {tab}
            </button>
          ))}
        </div>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {characters.map((char) => (
          <div
            key={char.id}
            onClick={() => startChat(char.id)}
            className="group relative bg-white border border-gray-200 rounded-2xl overflow-hidden hover:shadow-2xl hover:border-gray-300 transition-all duration-500 flex flex-col cursor-pointer"
          >
            <div className="h-44 bg-linear-to-br from-indigo-50 via-white to-pink-50 flex items-center justify-center relative overflow-hidden">
              <span className="text-7xl group-hover:scale-110 transition-transform duration-500 z-10">{char.avatar}</span>
              <div className="absolute -bottom-10 -right-10 w-32 h-32 bg-purple-200/30 rounded-full blur-3xl" />
              <span className="absolute top-4 left-4 bg-white/80 backdrop-blur-md px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest text-gray-700 shadow-xs border border-white/20">
                {char.tag}
              </span>
            </div>

            <div className="p-5 flex-1 flex flex-col">
              <div className="flex-1">
                <h3 className="text-xl font-bold text-gray-900 group-hover:text-pink-600 transition-colors">{char.name}</h3>
                <p className="text-sm text-gray-500 mt-2 line-clamp-2 leading-relaxed">
                  {char.description}
                </p>
              </div>

              <div className="mt-6 flex items-center justify-between border-t border-gray-50 pt-4">
                <div className="flex gap-4">
                  <div className="flex items-center gap-1.5 text-xs font-bold text-gray-400">
                    <MessageSquare className="w-3.5 h-3.5" />
                    {char.messages}
                  </div>
                  <div className="flex items-center gap-1.5 text-xs font-bold text-gray-400">
                    <Heart className={`w-3.5 h-3.5 ${likedIds.has(char.id) ? 'fill-pink-500 text-pink-500' : ''}`} />
                    {char.likes + (likedIds.has(char.id) ? 1 : 0)}
                  </div>
                </div>

                <div className="flex gap-1">
                  <button 
                    onClick={(e) => toggleLike(e, char.id)}
                    className={`p-2 rounded-xl transition-all ${likedIds.has(char.id) ? 'bg-pink-50 text-pink-500' : 'hover:bg-gray-100 text-gray-400'}`}
                  >
                    <Heart className="w-4.5 h-4.5" />
                  </button>
                  <button 
                    onClick={(e) => { e.stopPropagation(); }}
                    className="p-2 hover:bg-gray-100 rounded-xl transition-all text-gray-400"
                  >
                    <Share2 className="w-4.5 h-4.5" />
                  </button>
                </div>
              </div>

              <button className="mt-4 w-full bg-gray-900 text-white py-3 rounded-xl font-bold hover:bg-black transition-all active:scale-[0.98] shadow-sm">
                Chat Now
              </button>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-16 flex justify-center">
        <button className="group flex items-center gap-2 px-12 py-4 bg-white border-2 border-gray-100 rounded-2xl font-bold text-gray-700 hover:border-gray-300 transition-all hover:shadow-md">
          Load More Characters
          <TrendingUp className="w-4 h-4 text-gray-400 group-hover:translate-x-1 group-hover:-translate-y-1 transition-transform" />
        </button>
      </div>
    </div>
  );
}