import { format } from "date-fns";

const getReadingTime = (body: string | undefined) => {
  const words = (body ?? "")
    .replace(/```[\s\S]*?```/g, " ")
    .replace(/<[^>]+>/g, " ")
    .match(/\b[\w'-]+\b/g);

  return Math.max(1, Math.ceil((words?.length ?? 0) / 220));
};

const BlogPost = ({
  post,
  children,
}: {
  post: any;
  children: React.ReactNode;
}) => {
  const { title, pubDate } = post.data;
  const readingTime = getReadingTime(post.body);

  return (
    <section className="container px-6 py-2 md:py-6">
      <article className="poetry-post mx-auto">
        <h1 className="poetry-post-title">{title}</h1>
        <div className="poetry-post-meta">
          <time dateTime={pubDate.toISOString()}>
            {format(pubDate, "MMMM d, yyyy")}
          </time>
          <span>{readingTime} min read</span>
        </div>
        <div className="poetry-post-body">{children}</div>
      </article>
    </section>
  );
};

export { BlogPost };
