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

function BlogDetail({
  title,
  postedOn,
  postedBy,
  tag,
  readTime,
  img,
  content,
}: any) {
  const renderText = (node: any) => {
    let text = node.text;
    if (node.bold) text = <strong>{text}</strong>;
    if (node.italic) text = <em>{text}</em>;
    if (node.underline) text = <u>{text}</u>;
    return text;
  };

  const renderChildren = (children: any[]) =>
    children.map((child, idx) => {
      if (child.type === "text") {
        return <span key={idx}>{renderText(child)}</span>;
      }
      return null;
    });

  const renderNode = (node: any, idx: number) => {
    switch (node.type) {
      case "heading":
        const HeadingTag: any = `h${node.level}`;
        return (
          <HeadingTag key={idx}>{renderChildren(node.children)}</HeadingTag>
        );

      case "paragraph":
        return <p key={idx}>{renderChildren(node.children)}</p>;

      case "list":
        const ListTag = node.format === "unordered" ? "ul" : "ol";
        return (
          <ListTag key={idx}>
            {node.children.map((item: any, i: number) => (
              <li key={i}>{renderChildren(item.children)}</li>
            ))}
          </ListTag>
        );

      default:
        return null;
    }
  };

  return (
    <article>
      <section className={styles["title-section"]}>
        <p>{title}</p>
        <div className={styles["meta-container"]}>
          <div>
            Posted on <span>{postedOn}</span>
          </div>
          <div>
            By <span>{postedBy}</span>
          </div>
          <div>Published in {tag}</div>
          <div>
            <span>{readTime} min read</span>
          </div>
        </div>
      </section>

      <section className={styles["img-section"]}>
        <img src={img || "https://picsum.photos/1000/400"} alt={title} />
      </section>

      <section className={styles["markdown-section"]}>
        {content?.map((node: any, idx: number) => renderNode(node, idx))}
      </section>
    </article>
  );
}

export default BlogDetail;
