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

export default function CatalogPage() {
  const { user, loading } = useAuth();
  const [chapters, setChapters] = useState([]);
  const [luckPercent, setLuckPercent] = useState(0);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(true);

  useEffect(() => {
    if (!user || user.role === 'admin') return undefined;
    let cancelled = false;
    (async () => {
      try {
        const data = await api.catalog();
        if (cancelled) return;
        setChapters(data.chapters || []);
        setLuckPercent(data.luckPercent || 0);
      } catch (err) {
        if (!cancelled) setError(err.message);
      } finally {
        if (!cancelled) setBusy(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [user?.id, user?.role]);

  if (loading || busy) 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">
      <div className="section-head">
        <div>
          <h1>Catalog</h1>
          <p className="muted">
            Fill every slot in a case chapter. Each completed chapter grants +1% catalog luck on
            opens.
          </p>
        </div>
        <div className="catalog-luck-pill">
          {luckPercent > 0 ? `+${luckPercent}% luck` : 'No luck bonus yet'}
        </div>
      </div>

      {error && <div className="error">{error}</div>}

      {chapters.length === 0 && !error && (
        <div className="empty">No active cases to collect.</div>
      )}

      <div className="catalog-chapters">
        {chapters.map((ch) => (
          <article
            key={ch.caseId}
            className={`catalog-chapter${ch.completed ? ' completed' : ''}`}
          >
            <div className="catalog-chapter-head">
              <div className="catalog-chapter-title">
                {ch.imageUrl ? (
                  <img src={ch.imageUrl} alt="" className="catalog-case-thumb" />
                ) : (
                  <span className="catalog-case-thumb placeholder">▣</span>
                )}
                <div>
                  <h2>
                    <Link to={`/cases/${ch.caseId}`}>{ch.name}</Link>
                  </h2>
                  <p className="muted">
                    {ch.filled}/{ch.total} slots · {formatCredits(ch.price)} cr
                  </p>
                </div>
              </div>
              {ch.completed ? (
                <span className="catalog-complete-badge">Complete · +1%</span>
              ) : (
                <div className="catalog-progress-bar" aria-hidden>
                  <div
                    className="catalog-progress-fill"
                    style={{
                      width: `${ch.total ? Math.round((ch.filled / ch.total) * 100) : 0}%`,
                    }}
                  />
                </div>
              )}
            </div>

            <div className="catalog-slots">
              {ch.slots.map((slot) => (
                <div
                  key={slot.itemId}
                  className={`catalog-slot${slot.filled ? ' filled' : ' empty'}`}
                  style={slot.filled ? { '--rarity': rarityColor(slot.rarity) } : undefined}
                  title={slot.filled ? slot.name : 'Not collected yet'}
                >
                  {slot.filled ? (
                    <>
                      {slot.imageUrl ? (
                        <img src={slot.imageUrl} alt="" loading="lazy" />
                      ) : (
                        <span className="catalog-slot-fallback">
                          {slot.name.slice(0, 2).toUpperCase()}
                        </span>
                      )}
                      <span className="catalog-slot-name">{slot.name}</span>
                    </>
                  ) : (
                    <span className="catalog-slot-empty">?</span>
                  )}
                </div>
              ))}
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}
