// src/app/blog/[slug]/page.tsx

import { Metadata } from "next";
import Image from "next/image";
import { getClient } from "@/lib/apolloClient";
import { SINGLE_BLOG_QUERY } from "@/lib/singleBlogQuery";
import BlogHeroSingle from "@/components/blog/BlogHeroSingle";
import BlogSidebar from "@/components/blog/BlogSidebar";
import RelatedPosts from "@/components/blog/RelatedPosts";
import CTABox from "@/components/home/CTABox";
import PrevNextPost from "@/components/blog/PrevNextPost";
import FAQSection from "@/components/FAQSectionBlog";
import { getFaqsByAccordionId } from "@/lib/getFaqs";

export const dynamic = "force-dynamic";
type PageProps = {
  params: Promise<{ slug: string }>;
};
type BlogPostSummary = {
  id: string;
  slug: string;
  title: string;
  date?: string;
  featuredImage?: {
    node?: {
      sourceUrl: string;
      altText?: string;
    };
  };
};
type YoastSEO = {
  title?: string | null;
  metaDesc?: string | null;
  canonical?: string | null;
  opengraphTitle?: string | null;
  opengraphDescription?: string | null;
  opengraphImage?: {
    sourceUrl?: string | null;
  } | null;
};
type SingleBlogQueryResult = {
  post: {
    id: string;
    title: string;
    excerpt: string;
    content: string;
    date: string;
    slug: string;

    blogFaqSection?: {
      easyAccordionId?: string | null;
    } | null;

    seo?: YoastSEO | null;

    rmpAvgRating?: number | null;
    rmpVoteCount?: number | null;

    author?: {
      node?: {
        name?: string;
        avatar?: {
          url?: string;
        };
      };
    };

    featuredImage?: {
      node?: {
        sourceUrl: string;
        altText?: string;
      };
    };
  } | null;

  allPosts: {
    nodes: BlogPostSummary[];
  };

  relatedPosts: {
    nodes: BlogPostSummary[];
  };
};


function calculateReadTime(html: string) {
  const text = html.replace(/<[^>]+>/g, "");
  const words = text.trim().split(/\s+/).length;
  const minutes = Math.ceil(words / 200); // 200 WPM
  return `${minutes} min read`;
}

/* ---------------- METADATA ---------------- */
export async function generateMetadata(
  { params }: PageProps
): Promise<Metadata> {
  const { slug } = await params;

  const { data } = await getClient().query<SingleBlogQueryResult>({
    query: SINGLE_BLOG_QUERY,
    variables: { slug },
  });

  const post = data?.post;
  const seo = post?.seo;

  if (!post) {
    return { title: "Blog Not Found" };
  }

  // ✅ Canonical fallback (Yoast → self URL)
  const canonical =
    seo?.canonical && seo.canonical.trim() !== ""
      ? seo.canonical
      : `/blog/${post.slug}/`;

  return {
    metadataBase: new URL("https://www.togwe.com"),

    title: seo?.title || post.title,
    description: seo?.metaDesc || undefined,

    alternates: {
      canonical,
    },

    openGraph: {
      title: seo?.opengraphTitle || seo?.title || post.title,
      description:
        seo?.opengraphDescription || seo?.metaDesc || undefined,
      images: seo?.opengraphImage?.sourceUrl
        ? [{ url: seo.opengraphImage.sourceUrl }]
        : [],
    },
  };
}


/* ---------------- PAGE ---------------- */
export default async function BlogDetailsPage(
  { params }: PageProps
) {
  const { slug } = await params; // ✅ FIX

  const { data } = await getClient().query<SingleBlogQueryResult>({
    query: SINGLE_BLOG_QUERY,
    variables: { slug },
    fetchPolicy: "no-cache",
  });

  if (!data || !data.post) {
    return <h1 className="text-center py-20">Blog not found</h1>;
  }

  const post = data.post;
  // Extract FAQ ID from GraphQL
  const faqAccordionId = post?.blogFaqSection?.easyAccordionId
    ? Number(post.blogFaqSection.easyAccordionId)
    : null;

  // Fetch FAQs dynamically
  const faqs = faqAccordionId
    ? await getFaqsByAccordionId(faqAccordionId)
    : [];

  const allPosts = data.allPosts.nodes;

  const currentIndex = allPosts.findIndex(
    (p: BlogPostSummary) => p.slug === slug
  );


  const previousPost =
    currentIndex < allPosts.length - 1
      ? allPosts[currentIndex + 1]
      : null;

  const nextPost =
    currentIndex > 0
      ? allPosts[currentIndex - 1]
      : null;

  if (!post) {
    return <h1 className="text-center py-20">Blog not found </h1>;
  }

  return (
    <>
      <BlogHeroSingle title={post.title} />

      <section className="py-10 md:py-20 bg-[#F3F3F3]">
        <div className="container mx-auto px-4">

          {/* Section Header */}
          <div className="text-center md:px-20 mx-auto mb-16">
            <h2 className="text-2xl md:text-[40px] font-medium text-[#202020] font-mono mb-4">
              {post.title}
            </h2>
            {/* <div
              className="prose prose-lg text-lg font-medium text-[#202020]/70"
              dangerouslySetInnerHTML={{ __html: post.excerpt || "" }}
            /> */}
            {/* POST META */}
            <div className="mb-10 mx-auto mt-6 max-w-2xl">
              <div className="grid grid-cols-1 md:grid-cols-3 items-center gap-2 rounded-xl border border-[#202020]/15 bg-transparent px-6 py-4">

                {/* AUTHOR */}
                <div className="flex items-center gap-4">
                  {post.author?.node?.avatar?.url && (
                    <Image
                      src={post.author.node.avatar.url}
                      alt={post.author?.node?.name || "Author"}
                      width={64}
                      height={64}
                      className="h-16 w-16 rounded-full object-cover"
                    />
                  )}

                  <div className="leading-tight text-left">
                    <p className="text-sm font-medium text-[#202020]/50">
                      Written By
                    </p>
                    <p className="text-lg font-mono font-medium text-[#202020]">
                      {post.author?.node?.name}
                    </p>
                  </div>
                </div>

                {/* READ TIME */}
                <div className="text-left">
                  <p className="text-sm font-medium text-[#202020]/50">
                    Read Time
                  </p>
                  <p className="text-lg font-mono font-medium text-[#202020]">
                    {calculateReadTime(post.content)}
                  </p>
                </div>

                {/* DATE */}
                <div className="text-left">
                  <p className="text-sm font-medium text-[#202020]/50">
                    Posted on
                  </p>
                  <p className="text-lg font-mono font-medium text-[#202020]">
                    {new Date(post.date).toLocaleDateString("en-US", {
                      month: "long",
                      day: "numeric",
                      year: "numeric",
                    })}
                  </p>
                </div>

              </div>
            </div>

          </div>
          {/* FEATURED IMAGE */}
          <div className="mb-12 rounded-lg overflow-hidden bg-white p-3 border border-[#202020]/15">
            {post.featuredImage?.node?.sourceUrl && (
                <Image
                  src={post.featuredImage.node.sourceUrl}
                  alt={post.featuredImage.node.altText || post.title}
                  width={1200}
                  height={600}
                  unoptimized
                  className="w-full h-full object-cover object-center rounded-lg"
                />
            )}
          </div>
        </div>
        <div className="container mx-auto px-4 grid lg:grid-cols-3 gap-12">

          {/* CONTENT */}
          <article className="lg:col-span-2">
            {typeof post.rmpAvgRating === "number" && (
              <div className="mb-4 flex items-center gap-2 text-lg">
                <div className="flex items-center gap-1">
                  {/* Stars visual – quick/simple */}
                  <div className="flex">
                    {Array.from({ length: 5 }).map((_, i) => {
                      const filled = i + 1 <= Math.round(post.rmpAvgRating || 0);
                      return (
                        <span
                          key={i}
                          className={filled ? "text-yellow-400" : "text-[#202020]/70"}
                        >
                          ★
                        </span>
                      );
                    })}
                  </div>
                  <span className="font-semibold font-mono text-[#202020]">
                    {post.rmpAvgRating?.toFixed(1)}
                  </span>
                </div>

                <span className="text-[#202020]/70">
                  ({post.rmpVoteCount || 0} votes)
                </span>
              </div>
            )}

            {/* CONTENT BODY */}
            <div
              className="prose prose-lg max-w-none text-[#202020] text-lg md:text-justify"
              dangerouslySetInnerHTML={{ __html: post.content }}
            />
            {faqs.length > 0 && <FAQSection faqs={faqs} />}
            <PrevNextPost
              previousPost={previousPost}
              nextPost={nextPost}
            />
          </article>

          {/* SIDEBAR */}
          <div className="lg:col-span-1">
            <div className="sticky top-28">
              <BlogSidebar post={post} />
            </div>
          </div>
        </div>
      </section>

      {/* RELATED POSTS */}
      <RelatedPosts posts={data.relatedPosts.nodes} />

      <CTABox />
    </>
  );
}
