"use client";

import { useMemo } from "react";
import { MessageSquare } from "lucide-react";
import ShareButton from "@/components/common/ShareButton";

// WordPress lazy-loads images: the <img> ships a 1x1.png placeholder while the
// real image lives in the wrapping <a href="...jpg">. Promote that href into the
// img's src so the actual image renders. Only anchors pointing at an image file
// are touched, and only imgs whose src is the 1x1 placeholder.
const fixLazyImages = (html: string): string =>
  html.replace(
    /(<a\b[^>]*\bhref="([^"]+\.(?:jpe?g|png|gif|webp|svg|bmp)(?:\?[^"]*)?)"[^>]*>\s*<img\b[^>]*?)\bsrc="[^"]*1x1\.png[^"]*"([^>]*>)/gi,
    '$1src="$2"$3',
  );

// Expand the first FAQ item by default: add the `open` attribute to the first
// <details> inside each .blog-faq block.
const openFirstFaq = (html: string): string =>
  html.replace(
    /(<div\b[^>]*\bclass="[^"]*\bblog-faq\b[^"]*"[^>]*>\s*<details)\b/gi,
    "$1 open",
  );

interface BlogDetailProps {
  author: string;
  role: string;
  avatar?: string;
  title: string;
  description: string;
  date: string;
  commentsCount: number;
  details: string;
  featuredImage: string;
}

const BlogDetail: React.FC<BlogDetailProps> = ({
  title,
  author,
  commentsCount,
  date,
  details,
}) => {
  const content = useMemo(
    () => openFirstFaq(fixLazyImages(details)),
    [details],
  );

  return (
    <div className="self-stretch">
      {/* Title */}
      <h1 className="text-[32px] font-extrabold text-[#111827] leading-tight mb-3">
        {title}
      </h1>

      {/* Meta row */}
      <div className="flex items-start md:items-center gap-3 text-sm text-[#6b7280] mb-6">
        <span>
          Written by <span className="text-blue-500 font-medium">{author}</span>
          <span className="block sm:inline"> on {date}</span>
        </span>

        {/* Comments + share: pushed to the right on mobile, inline on sm+ */}
        <div className="flex items-center gap-3 ml-auto sm:ml-0">
          <a
            href="#comments"
            onClick={(e) => {
              e.preventDefault();
              document
                .getElementById("comments")
                ?.scrollIntoView({ behavior: "smooth", block: "start" });
            }}
            className="flex items-center gap-1 cursor-pointer hover:text-[#374151] transition-colors"
          >
            <MessageSquare className="h-4 w-4" />
            {commentsCount}
          </a>

          <ShareButton title={title} />
        </div>
      </div>

      {/* Blog Content */}
      <div
        className="blog-content self-stretch"
        dangerouslySetInnerHTML={{ __html: content }}
      />
    </div>
  );
};

export default BlogDetail;
