import { useEffect, useState } from "react";
import api from "../services/api.js";

export default function Dashboard() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState("");

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        // Demo: trae usuarios desde la API configurada
        const { data } = await api.get("/users");
        if (mounted) setUsers(data);
      } catch (e) {
        setErr("No se pudo cargar el Dashboard");
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  if (loading) return <p>Cargando...</p>;
  if (err) return <p className="alert alert--error">{err}</p>;

  return (
    <section>
      <h2>Dashboard</h2>
      <p>Usuarios demo desde la API:</p>
      <div className="grid">
        {users.map((u) => (
          <div key={u.id} className="card">
            <h3>{u.name}</h3>
            <p>{u.email}</p>
            <small>{u.username}</small>
          </div>
        ))}
      </div>
    </section>
  );
}
