import type { ReactNode } from "react";
import { format } from "date-fns";
import { typographicText } from "@/lib/typography";

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: ReactNode;
}) => {
  const { title, image, pubDate } = post.data;
  const displayTitle = typographicText(title);
  const readingTime = getReadingTime(post.body);

  return (
    <section className="blog-post-shell">
      <article className="blog-article">
        <header className="blog-post-header">
          <div className="blog-post-meta">
            <time dateTime={pubDate.toISOString()}>
              {format(pubDate, "MMMM d, yyyy")}
            </time>
            <span>{readingTime} min read</span>
          </div>
          <h1 className="blog-post-title">{displayTitle}</h1>
        </header>

        {image ? (
          <figure className="blog-post-hero-image">
            <img src={image} alt={displayTitle} />
          </figure>
        ) : null}

        <div className="article-content">{children}</div>
      </article>
    </section>
  );
};

export { BlogPost };
