import { useEffect, useState } from 'react';

const API = import.meta.env.VITE_API_URL;

const GRADES = [
  { id: 'G3', label: 'Grade 3' },
  { id: 'G6', label: 'Grade 6' },
  { id: 'G9', label: 'Grade 9' },
];

function fmtTime(seconds) {
  if (seconds == null) return '—';
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${m}:${String(s).padStart(2, '0')}`;
}

function TrophyIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" />
      <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
      <path d="M4 22h16" />
      <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" />
      <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" />
      <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" />
    </svg>
  );
}

export default function LeaderboardModal({ isOpen, onClose }) {
  const [selectedGrade, setSelectedGrade] = useState('G3');
  const [leaderboard, setLeaderboard] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!isOpen) return;
    setLoading(true);
    fetch(`${API}/leaderboard?grade=${selectedGrade}&sortBy=bestTime&limit=10`)
      .then(res => res.json())
      .then(data => setLeaderboard(Array.isArray(data) ? data : []))
      .catch(() => setLeaderboard([]))
      .finally(() => setLoading(false));
  }, [isOpen, selectedGrade]);

  useEffect(() => {
    if (!isOpen) return;
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const MEDALS = ['🥇', '🥈', '🥉'];

  return (
    <div className="lb-modal-overlay" onClick={onClose}>
      <div className="lb-modal" onClick={e => e.stopPropagation()}>
        <div className="lb-modal__hd">
          <div className="lb-modal__title-row">
            <span className="lb-modal__icon">
              <TrophyIcon />
            </span>
            <h2 className="lb-modal__title">Best Times</h2>
          </div>
          <button className="lb-modal__close" onClick={onClose}>✕</button>
        </div>

        <div className="lb-modal__grade-tabs">
          {GRADES.map(g => (
            <button
              key={g.id}
              className={`lb-modal__grade-tab${selectedGrade === g.id ? ' lb-modal__grade-tab--active' : ''}`}
              onClick={() => setSelectedGrade(g.id)}
            >
              {g.label}
            </button>
          ))}
        </div>

        <div className="lb-modal__body">
          {loading ? (
            <div className="lb-skeleton">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="lb-skel-row" style={{ animationDelay: `${i * 0.07}s` }} />
              ))}
            </div>
          ) : leaderboard.length === 0 ? (
            <div className="dash-empty">
              <span className="dash-empty__icon">🏆</span>
              <p className="dash-empty__text">No scores yet</p>
              <p className="dash-empty__sub">Be the first to set a record</p>
            </div>
          ) : (
            <div className="lb-table">
              {leaderboard.map(entry => (
                <div key={entry.rank} className="lb-row">
                  <span className={`lb-rank${entry.rank > 3 ? ' lb-rank--num' : ''}`}>
                    {entry.rank <= 3 ? MEDALS[entry.rank - 1] : entry.rank}
                  </span>
                  <div className="lb-user">
                    {entry.avatarUrl
                      ? <img className="lb-avatar" src={entry.avatarUrl} alt={entry.displayName} referrerPolicy="no-referrer" />
                      : <div className="lb-avatar lb-avatar--fallback">{entry.displayName[0]?.toUpperCase() ?? '?'}</div>
                    }
                    <span className="lb-name">{entry.displayName}</span>
                  </div>
                  <span className="lb-score">{fmtTime(entry.bestTime)}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}