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

function price(course) {
  if (course.isFree || course.priceCents === 0) return 'Free';
  return `$${(course.priceCents / 100).toFixed(2)}`;
}

export default function VendorCourses() {
  const { slug } = useParams();
  const [vendor, setVendor] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    api
      .get(`/vendors/${slug}`)
      .then(({ data }) => setVendor(data.vendor))
      .catch((e) => setError(e.message));
  }, [slug]);

  if (error) return <div className="container page"><div className="alert alert-error">{error}</div></div>;
  if (!vendor) return <Spinner />;

  return (
    <div className="container page">
      <Link to="/vendors" className="muted">← All vendors</Link>
      <h1 className="mt-2">{vendor.name}</h1>
      <p className="muted">{vendor.description}</p>

      <div className="grid mt-3" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))' }}>
        {vendor.courses.map((c) => (
          <Link to={`/courses/${c.slug}`} key={c.id} className="card card-hover tile">
            <div className="tile-top">
              {c.code ? <span className="badge">{c.code}</span> : <span />}
              <span className={`badge ${c.isFree || c.priceCents === 0 ? 'badge-free' : ''}`}>{price(c)}</span>
            </div>
            <h3 className="tile-title">{c.title}</h3>
            <p className="muted tile-desc">{c._count?.questions || 0} questions</p>
            <span className="tile-cta">Start exam →</span>
          </Link>
        ))}
        {vendor.courses.length === 0 && <p className="muted">No exams published for this vendor yet.</p>}
      </div>
    </div>
  );
}
