import { useEffect, useState } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { api, formatCredits } from '../api';
import { useAuth } from '../AuthContext';

export default function CasesPage() {
  const { user, loading } = useAuth();
  const [cases, setCases] = useState([]);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!user || user.role === 'admin') return;
    let cancelled = false;
    (async () => {
      try {
        const cs = await api.cases();
        if (!cancelled) setCases(cs.cases);
      } catch (err) {
        if (!cancelled) setError(err.message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [user]);

  if (loading) return <p className="muted">Loading…</p>;
  if (!user) return <Navigate to="/login" replace />;
  if (user.role === 'admin') return <Navigate to="/admin" replace />;

  return (
    <section className="section">
      {error && <div className="error">{error}</div>}
      <div className="grid case-grid">
        {cases.map((c) => (
          <Link key={c.id} to={`/cases/${c.id}`} className="case-tile">
            <div className={`case-visual${c.imageUrl ? ' has-img' : ''}`} style={{ color: 'var(--accent)' }}>
              {c.imageUrl ? <img src={c.imageUrl} alt="" loading="lazy" /> : '▣'}
            </div>
            <div className="case-name">{c.name}</div>
            <div className="case-meta case-price">{formatCredits(c.price)} cr</div>
            <div className="case-meta">{c.items.length} possible drops</div>
            {c.keyProgress && (
              <div className="case-meta case-key-badge">
                {c.keyProgress.keys} key{c.keyProgress.keys === 1 ? '' : 's'} · x
                {c.keyProgress.maxOpens}
              </div>
            )}
          </Link>
        ))}
      </div>
      {cases.length === 0 && !error && <div className="empty">No active cases.</div>}
    </section>
  );
}
