import { useEffect, useState } from 'react';
import { api } from '../api';
import { GAME_CATEGORIES } from '../lib/format';
import GameCard from '../components/GameCard';

export default function Games() {
  const [games, setGames] = useState([]);
  const [cat, setCat] = useState('all');
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    api('/games')
      .then((d) => {
        const list = Array.isArray(d) ? d : d?.games || [];
        setGames(list);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoaded(true));
  }, []);

  const filtered = cat === 'all' ? games : games.filter((g) => g.category === cat);

  return (
    <div className="container">
      <h1 className="section-title">Oyunlar</h1>
      <p className="section-sub">Dört ulusun kader oyunları. Bahis cüzdana yansır, sonuç şeffaf.</p>

      <div className="filter-chips">
        {GAME_CATEGORIES.map((c) => (
          <button
            key={c.id}
            className={`chip ${cat === c.id ? 'active' : ''}`}
            onClick={() => setCat(c.id)}
          >
            {c.label}
          </button>
        ))}
      </div>

      {error && <div className="alert alert-error">Oyunlar yüklenemedi: {error}</div>}
      {!loaded && (
        <div className="game-grid">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="skeleton" style={{ height: 240 }} />
          ))}
        </div>
      )}
      {loaded && filtered.length === 0 && (
        <div className="empty">
          <span className="empty-icon">🎰</span>
          Bu kategoride oyun bulunamadı.
        </div>
      )}
      <div className="game-grid stagger" key={cat}>
        {filtered.map((g, i) => (
          <GameCard key={g.slug} game={g} index={i} />
        ))}
      </div>
    </div>
  );
}
