---
import type { CollectionEntry } from 'astro:content';
import { getEntry } from 'astro:content';
import EntryThumbnail from './EntryThumbnail.astro';
import ProjectLinks from './ProjectLinks.astro';
import { articlePath, projectAnchor } from '../lib/site';

interface Props {
  projects: CollectionEntry<'projects'>[];
}

const { projects } = Astro.props;
type ProjectLink = CollectionEntry<'projects'>['data']['links'][number];

// The `essay` field is a `reference('posts')`, so when present it's always a
// `{ collection, id }` shape that `getEntry` resolves to a CollectionEntry.
const essayHrefs = new Map<string, string>();
for (const project of projects) {
  const essay = project.data.essay;
  if (!essay) continue;
  const resolved = await getEntry(essay);
  if (resolved) essayHrefs.set(project.id, articlePath(resolved));
}
---

<ol class="project-list">
  {
    projects.map((project, index) => {
      const anchor = projectAnchor(project);
      const titleId = `${anchor}-title`;
      const essayHref = essayHrefs.get(project.id);
      const primaryHref = essayHref ?? project.data.links[0]?.url;
      const links: ProjectLink[] = project.data.links;
      const isFirst = index === 0;

      return (
        <li class="project-card" id={anchor}>
          <EntryThumbnail
            src={project.data.thumbnail.src}
            alt={project.data.thumbnail.alt}
            href={primaryHref}
            class="project-thumbnail"
            widths={[240, 320, 480, 640, 800]}
            sizes="(max-width: 700px) 7rem, (max-width: 960px) clamp(7rem, 18vw, 9.5rem), 19rem"
            loading={isFirst ? 'eager' : 'lazy'}
            fetchpriority={isFirst ? 'high' : undefined}
          />
          <article class="project-card__summary">
            <h3 id={titleId}>
              {primaryHref ? (
                <a href={primaryHref}>{project.data.title}</a>
              ) : (
                project.data.title
              )}
              {essayHref && <span class="project-essay-badge">Article</span>}
            </h3>
            <p class="project-description">{project.data.description}</p>
            <p class="project-meta">
              {project.data.period} · {project.data.technologies.join(', ')}
            </p>
            {links.length > 0 && <ProjectLinks links={links} />}
          </article>
        </li>
      );
    })
  }
</ol>
