import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import api from '../api/client.js';
import Spinner from '../components/Spinner.jsx';

export default function Vendors() {
  const [vendors, setVendors] = useState(null);

  useEffect(() => {
    api.get('/vendors').then(({ data }) => setVendors(data.vendors)).catch(() => setVendors([]));
  }, []);

  if (!vendors) return <Spinner />;

  return (
    <div className="container page">
      <h1>Choose a vendor</h1>
      <p className="muted">Pick a certification vendor to see available exams.</p>
      <div className="grid mt-3" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))' }}>
        {vendors.map((v) => (
          <Link to={`/vendors/${v.slug}`} key={v.id} className="card card-hover tile">
            <div className="tile-top">
              <span className="tile-mark">{(v.name || '?').charAt(0).toUpperCase()}</span>
              <span className="badge">{v._count?.courses || 0} exams</span>
            </div>
            <h3 className="tile-title">{v.name}</h3>
            <p className="muted tile-desc">{v.description || 'Certification exams'}</p>
            <span className="tile-cta">View exams →</span>
          </Link>
        ))}
        {vendors.length === 0 && <p className="muted">No vendors available yet.</p>}
      </div>
    </div>
  );
}
