import { getNewsTermsByYear, getNewsYears } from "lib/news";
import { GetStaticProps } from "next";
import React from "react";

import { Link } from "@/components/Link";

import styles from "./archive.module.css";

interface Props {
  items: {
    year: string;
    terms: string[];
  }[];
}

export default function NewsArchive({ items }: Props) {
  return (
    <div className={styles.page}>
      <h1>News Archive</h1>
      <ul className={styles.list}>
        {items.map(({ year, terms }) =>
          terms.map((term) => (
            <li key={`${year}-${term}`}>
              <Link href={`/news/${year}/${term}`}>
                {capitalize(term)} {year}
              </Link>
            </li>
          ))
        )}
      </ul>
    </div>
  );
}

export const getStaticProps: GetStaticProps<Props> = async () => {
  const years = (await getNewsYears()).reverse();
  const yearsWithTerms = await Promise.all(
    years.map(async (year) => ({
      year,
      terms: (await getNewsTermsByYear(year)).reverse(),
    }))
  );

  return { props: { items: yearsWithTerms } };
};

function capitalize(str: string) {
  return str.slice(0, 1).toUpperCase() + str.slice(1);
}
