---
import { Commit, fetchGithub } from "../../utils/fetchGithub";

// fetch all commits for just this page's path
export interface Props {
  path: string;
}
const { path } = Astro.props;
const resolvedPath = `www/${path}`;
const url = `https://api.github.com/repos/t3-oss/create-t3-app/commits?path=${resolvedPath}`;
const commitsURL = `https://github.com/t3-oss/create-t3-app/commits/main/${resolvedPath}`;

async function getCommits(url: string) {
  try {
    const data = await fetchGithub(url, { fetchType: "commits" });
    return data;
  } catch (e) {
    console.warn(`[warn]  /src/components/AvatarList.astro 
    ${(e as Error)?.message ?? e}`);
    return [] as Commit[];
  }
}

function removeDups(arr: Commit[]): Pick<Commit["author"], "login" | "id">[] {
  const map = new Map<string, Pick<Commit["author"], "login" | "id">>();

  for (let item of arr) {
    const author = item.author;
    if (!author || !author.id || !author.login) continue;
    // Deduplicate based on author.id
    map.set(author.id.toString(), { login: author.login, id: author.id });
  }

  return [...map.values()];
}

const data = await getCommits(url);
const unique = removeDups(data ?? []);
const recentContributors = unique.slice(0, 3); // only show avatars for the 3 most recent contributors
const additionalContributors = unique.length - recentContributors.length; // list the rest of them as # of extra contributors
---

<div class="flex flex-col items-center justify-center gap-2 py-3">
  <span class="py-2">Recent Contributors To This Page</span>
  <ul class="flex gap-4">
    {
      recentContributors.map((item) => (
        <li>
          <a class="rounded-full" href={`https://github.com/${item.login}`}>
            <img
              class="h-8 w-8 rounded-full sm:h-10 sm:w-10"
              alt={`Contributor ${item.login}`}
              title={`Contributor
          ${item.login}`}
              width="64"
              height="64"
              src={`https://avatars.githubusercontent.com/u/${item.id}`}
            />
          </a>
        </li>
      ))
    }
  </ul>
  {
    additionalContributors > 0 && (
      <span>
        <a
          href={commitsURL}
        >{`and ${additionalContributors} additional contributor${
          additionalContributors > 1 ? "s" : ""
        }.`}</a>
      </span>
    )
  }
  {
    unique.length === 0 && (
      <a class="text-slate-900 dark:text-white" href={commitsURL}>
        Contributors
      </a>
    )
  }
</div>
