/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 * Copyright (c) 2024 Kristóf Marussy <kristof@marussy.com>
 *
 * SPDX-License-Identifier: MIT
 */

import Link from '@docusaurus/Link';
import type { Props } from '@theme/BlogListPage';
import type { Content } from '@theme/BlogPostPage';
import Translate from '@docusaurus/Translate';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import clsx from 'clsx';

import Section from '@site/src/components/landing/Section';
import Subtitle from '@site/src/components/landing/Subtitle';

import styles from './Blog.module.css';

function Column({
  items,
}: {
  items: { readonly content: Content }[];
}): React.ReactNode {
  // Date time format based on
  // https://github.com/facebook/docusaurus/blob/6f17d5493877ba38d8b4e0b0d468f44401375c30/packages/docusaurus-theme-common/src/utils/IntlUtils.ts
  const {
    i18n: { currentLocale, localeConfigs },
  } = useDocusaurusContext();
  const calendar = localeConfigs[currentLocale]!.calendar;
  const dateTimeFormat = new Intl.DateTimeFormat(currentLocale, {
    calendar,
    day: 'numeric',
    month: 'long',
    year: 'numeric',
    timeZone: 'UTC',
  });

  if (items.length === 0) {
    return null;
  }

  return (
    <div className="col col-6">
      <ul className={styles['recent-posts']}>
        {items.map(({ content }) => (
          <li key={content.metadata.date}>
            <Link to={content.metadata.permalink}>
              {content.metadata.title}
            </Link>{' '}
            <span className={styles.date}>
              on {dateTimeFormat.format(new Date(content.metadata.date))}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default function Blog(props: Props) {
  const {
    items,
    metadata: { nextPage },
  } = props;
  const columnLength = Math.max(1, Math.ceil(items.length / 2));
  return (
    <Section id="blog" title="Blog">
      <div className="container">
        <Subtitle icon="🗓️">Recent posts</Subtitle>
        <div className={clsx('row', styles.row)}>
          <Column items={items.slice(0, columnLength)} />
          <Column items={items.slice(columnLength)} />
        </div>
        {nextPage && (
          <p>
            <Link to={nextPage} className={styles.prev}>
              <Translate
                id="theme.blog.paginator.olderEntries"
                description="The label used to navigate to the older blog posts page (next page)"
              >
                Older Entries
              </Translate>
            </Link>
          </p>
        )}
      </div>
    </Section>
  );
}
