import { useEffect, useState } from "react";

export default function NowPlaying() {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchProjectData = async () => {
            try {
                const res = await fetch(
                    "https://pds.indexx.dev/xrpc/com.atproto.repo.listRecords?repo=did%3Aplc%3Asfjxpxxyvewb2zlxwoz2vduw&collection=dev.indexx.www.project&limit=100&reverse=false",
                );
                if (!res.ok) throw new Error(`HTTP ${res.status}`);

                const data = await res.json();
                const projects = data.records.map((record) => record.value);

                setData(projects.map((project) => ({
                    title: project.name,
                    description: project.description,
                    date: project.dateLabel,
                    href: project.url,
                    note: project.note ?? "",
                })));
            } catch (err) {
                console.error("Fetch failed:", err);
                setError(err.message);
            }
        };

        fetchProjectData();
    }, []);

    if (error) return <span>Error: {error}</span>;
    if (!data) return null;

    return (
        <section id="projects-pane" data-bs-theme="dark">
            <h6
                className="text-muted text-center"
                style={{ textTransform: "uppercase", letterSpacing: "5px" }}
            >
                My Recent Projects
            </h6>

            <ul className="list-unstyled">
                {data.map((project) => (
                    <li>
                        <a
                            href={project.href}
                            target="_blank"
                            className="text-reset"
                        >
                            <div
                                className="project-card"
                                style={{ color: "#fff" }}
                            >
                                <small className="text-muted">
                                    {project.date}
                                </small>
                                <h4>{project.title}</h4>
                                {project.description}
                                {project.note && (
                                    <>
                                        <br />
                                        <small className="text-muted">
                                            {project.note}
                                        </small>
                                    </>
                                )}
                            </div>
                        </a>
                    </li>
                ))}
            </ul>
        </section>
    );
}
