const RankingTab = ({ achStats, currentUser, player }) => {
  const [allRankings, setAllRankings] = React.useState([]);
  const myBest = achStats.maxFloor || 1;
  const myName = player?.userName || currentUser?.email?.split('@')[0] || 'OPERATOR-01';

  React.useEffect(() => {
    const fetchRankings = async () => {
      const data = await getTopRankings(20); // 上位20件取得
      // 自分の現在の記録がまだDBにない場合や、DBの記録より高い場合を考慮してマージ
      let displayData = data.map((item, idx) => ({ ...item, rank: idx + 1, isMe: item.userName === myName }));
      
      const myEntryInDb = displayData.find(d => d.userName === myName);
      if (!myEntryInDb || myBest > myEntryInDb.floor) {
        // DBにないか、現在のプレイが最高記録ならリストを更新して並び替え
        const filtered = displayData.filter(d => d.userName !== myName);
        displayData = [...filtered, { userName: myName, maxFloor: myBest, timestamp: Date.now(), isMe: true }]
          .sort((a, b) => b.maxFloor - a.maxFloor)
          .map((item, idx) => ({ ...item, rank: idx + 1, name: item.userName, floor: item.maxFloor, date: new Date(item.timestamp).toLocaleDateString() }));
      } else {
        displayData = displayData.map(d => ({ ...d, name: d.userName, floor: d.maxFloor, date: new Date(d.timestamp).toLocaleDateString() }));
      }

      setAllRankings(displayData);
    };
    fetchRankings();
  }, [myBest, myName]);

  return (
    <div className="p-10 lg:p-16 max-w-4xl mx-auto w-full space-y-10 animate-fade-in-up">
      {/* ヘッダー */}
      <div>
        <h2 className="text-2xl font-bold border-b border-gray-700 pb-4 text-cyan-400 flex items-center gap-3">
          <Globe size={28} /> 全世界ランキング - GLOBAL RANKING
        </h2>
        <p className="text-gray-500 text-sm mt-3 font-bold uppercase tracking-widest">
          JUNK CODE ネットワークに接続された全機体の最高到達階層を表示します。
        </p>
      </div>

      {/* 自分の記録 */}
      <div className="bg-cyan-900/10 border border-cyan-700/30 rounded-2xl p-8 flex flex-col md:flex-row items-center justify-between shadow-[0_0_30px_rgba(6,182,212,0.1)] relative overflow-hidden group">
        <div className="absolute top-0 right-0 w-64 h-64 bg-cyan-500/5 rounded-full -mr-32 -mt-32 blur-3xl group-hover:bg-cyan-500/10 transition-colors"></div>
        <div className="relative z-10">
          <div className="text-xs font-black text-cyan-500 uppercase tracking-widest mb-2">Your Personal Best</div>
          <div className="text-4xl font-black text-white">{myBest} <span className="text-sm text-gray-500">FLOORS</span></div>
        </div>
        <div className="text-right relative z-10 mt-6 md:mt-0">
          <div className="text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Estimated Rank</div>
          <div className="text-2xl font-black text-cyan-400">TOP {Math.max(1, Math.floor(100 - (myBest / 2.5)))}%</div>
        </div>
      </div>

      {/* ランキングテーブル */}
      <div className="bg-gray-800 border border-gray-700 rounded-3xl overflow-hidden shadow-2xl">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-gray-900/50 border-b border-gray-700">
              <th className="p-5 text-[10px] font-black text-gray-500 uppercase tracking-[0.3em] w-20">Rank</th>
              <th className="p-5 text-[10px] font-black text-gray-500 uppercase tracking-[0.3em]">Operator</th>
              <th className="p-5 text-[10px] font-black text-gray-500 uppercase tracking-[0.3em] text-right">Max Floor</th>
              <th className="p-5 text-[10px] font-black text-gray-500 uppercase tracking-[0.3em] text-right">Record Date</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-700/50">
            {allRankings.map((user) => (
              <tr 
                key={user.name + user.floor} 
                className={`transition-colors ${user.isMe ? 'bg-cyan-500/10' : 'hover:bg-white/5'}`}
              >
                <td className="p-5">
                  <div className={`w-8 h-8 rounded-lg flex items-center justify-center font-black text-xs ${
                    user.rank === 1 ? 'bg-yellow-500/20 text-yellow-500 border border-yellow-500/50' :
                    user.rank === 2 ? 'bg-gray-300/20 text-gray-300 border border-gray-300/50' :
                    user.rank === 3 ? 'bg-orange-500/20 text-orange-500 border border-orange-500/50' :
                    'bg-gray-900 text-gray-500'
                  }`}>
                    {user.rank}
                  </div>
                </td>
                <td className="p-5">
                  <div className="flex items-center gap-3">
                    <div className={`w-2 h-2 rounded-full ${user.isMe ? 'bg-cyan-500 animate-pulse' : 'bg-gray-700'}`}></div>
                    <span className={`font-bold text-sm ${user.isMe ? 'text-cyan-400' : 'text-gray-200'}`}>
                      {user.name}
                      {user.isMe && <span className="ml-2 text-[8px] bg-cyan-900 text-cyan-400 px-1 rounded uppercase">YOU</span>}
                    </span>
                  </div>
                </td>
                <td className="p-5 text-right font-mono text-white font-black">{user.floor}F</td>
                <td className="p-5 text-right text-[10px] font-bold text-gray-600 uppercase tracking-widest">{user.date}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="p-6 bg-gray-900/50 border border-dashed border-gray-700 rounded-2xl text-center">
        <p className="text-xs text-gray-600 font-bold italic uppercase tracking-widest">
          ランキングデータは24時間ごとに同期されます。
        </p>
      </div>
    </div>
  );
};
