import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { 
  Clock, Calendar, ArrowRight, ChevronRight, CheckCircle2, 
  HelpCircle, Info, AlertTriangle, Lightbulb, PlaySquare, 
  Wrench, ExternalLink, User, Share2
} from "lucide-react";
import { blogPosts, getBlogPostBySlug, getRelatedPosts } from "@/lib/blog-data";

interface PageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  return blogPosts.map((post) => ({
    slug: post.slug,
  }));
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const post = getBlogPostBySlug(slug);

  if (!post) {
    return {
      title: "Article Not Found | YTToolkits Blog",
      description: "The requested YouTube creator guide could not be found.",
    };
  }

  const url = `https://yttoolkits.site/blog/${post.slug}`;

  return {
    title: `${post.title} | YTToolkits`,
    description: post.excerpt,
    keywords: post.keywords,
    alternates: {
      canonical: url,
    },
    openGraph: {
      title: post.title,
      description: post.excerpt,
      url: url,
      siteName: "YTToolkits",
      locale: "en_US",
      type: "article",
      publishedTime: post.publishedAt,
      authors: [post.author.name],
    },
    twitter: {
      card: "summary_large_image",
      title: post.title,
      description: post.excerpt,
    },
  };
}

const categoryColors: Record<string, { bg: string; text: string; border: string }> = {
  "Monetization": { bg: "bg-emerald-500/10", text: "text-emerald-400", border: "border-emerald-500/20" },
  "Creator Guides": { bg: "bg-blue-500/10", text: "text-blue-400", border: "border-blue-500/20" },
  "YouTube SEO": { bg: "bg-amber-500/10", text: "text-amber-400", border: "border-amber-500/20" },
  "Algorithm Secrets": { bg: "bg-purple-500/10", text: "text-purple-400", border: "border-purple-500/20" },
  "Video Tips": { bg: "bg-rose-500/10", text: "text-rose-400", border: "border-rose-500/20" },
};

export default async function BlogPostPage({ params }: PageProps) {
  const { slug } = await params;
  const post = getBlogPostBySlug(slug);

  if (!post) {
    notFound();
  }

  const relatedPosts = getRelatedPosts(post.slug, 3);
  const color = categoryColors[post.category] || categoryColors["Creator Guides"];

  // Schemas
  const articleSchema = {
    "@context": "https://schema.org",
    "@type": "Article",
    "headline": post.title,
    "description": post.excerpt,
    "image": "https://yttoolkits.site/logo.png",
    "datePublished": post.publishedAt,
    "dateModified": post.publishedAt,
    "author": {
      "@type": "Person",
      "name": post.author.name,
      "jobTitle": post.author.role,
      "url": "https://yttoolkits.site/about",
    },
    "publisher": {
      "@type": "Organization",
      "name": "YTToolkits",
      "url": "https://yttoolkits.site",
      "logo": {
        "@type": "ImageObject",
        "url": "https://yttoolkits.site/logo.png",
      },
    },
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": `https://yttoolkits.site/blog/${post.slug}`,
    },
  };

  const faqSchema = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "mainEntity": post.faqs.map((faq) => ({
      "@type": "Question",
      "name": faq.question,
      "acceptedAnswer": {
        "@type": "Answer",
        "text": faq.answer,
      },
    })),
  };

  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [
      {
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": "https://yttoolkits.site",
      },
      {
        "@type": "ListItem",
        "position": 2,
        "name": "Creator Blog",
        "item": "https://yttoolkits.site/blog",
      },
      {
        "@type": "ListItem",
        "position": 3,
        "name": post.title,
        "item": `https://yttoolkits.site/blog/${post.slug}`,
      },
    ],
  };

  return (
    <article className="min-h-screen bg-zinc-950 text-zinc-100 pb-20">
      {/* Structured Data Schemas */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(articleSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(faqSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />

      {/* Hero / Header Area */}
      <header className="border-b border-zinc-800/80 bg-gradient-to-b from-zinc-900/60 via-zinc-950 to-zinc-950 pt-8 pb-12 sm:pt-12 sm:pb-16">
        <div className="container mx-auto px-4 max-w-4xl">
          {/* Breadcrumbs */}
          <nav aria-label="Breadcrumb" className="flex items-center flex-wrap gap-2 text-xs text-zinc-400 mb-6">
            <Link href="/" className="hover:text-zinc-200 transition-colors">Home</Link>
            <ChevronRight className="w-3.5 h-3.5 text-zinc-600" />
            <Link href="/blog" className="hover:text-zinc-200 transition-colors">Creator Blog</Link>
            <ChevronRight className="w-3.5 h-3.5 text-zinc-600" />
            <span className="text-zinc-300 truncate max-w-xs">{post.category}</span>
          </nav>

          {/* Category & Read Time Badges */}
          <div className="flex flex-wrap items-center gap-3 mb-5">
            <span className={`text-xs font-semibold px-3 py-1 rounded-full border ${color.bg} ${color.text} ${color.border}`}>
              {post.category}
            </span>
            <div className="flex items-center gap-1.5 text-xs text-zinc-400">
              <Clock className="w-3.5 h-3.5" />
              <span>{post.readTime}</span>
            </div>
            <div className="flex items-center gap-1.5 text-xs text-zinc-400">
              <Calendar className="w-3.5 h-3.5" />
              <span>{post.publishedAt}</span>
            </div>
          </div>

          {/* H1 Title */}
          <h1 className="text-2xl sm:text-4xl md:text-5xl font-extrabold tracking-tight text-white mb-6 leading-tight">
            {post.title}
          </h1>

          {/* Excerpt Lead */}
          <p className="text-base sm:text-xl text-zinc-400 leading-relaxed mb-8">
            {post.excerpt}
          </p>

          {/* Author Bar */}
          <div className="flex flex-wrap items-center justify-between gap-4 pt-6 border-t border-zinc-800">
            <div className="flex items-center gap-3">
              <div className="w-11 h-11 rounded-full bg-red-600/20 border border-red-500/30 flex items-center justify-center font-bold text-red-400 text-sm">
                AR
              </div>
              <div>
                <div className="text-sm font-semibold text-zinc-200">{post.author.name}</div>
                <div className="text-xs text-zinc-500">{post.author.role}</div>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <span className="text-xs text-zinc-500 flex items-center gap-1 bg-zinc-900 border border-zinc-800 px-3 py-1.5 rounded-lg">
                <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" />
                Verified for 2026
              </span>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content Layout */}
      <div className="container mx-auto px-4 max-w-4xl pt-10">
        {/* Table of Contents Box */}
        <div className="mb-12 p-6 bg-zinc-900/60 border border-zinc-800 rounded-2xl">
          <h2 className="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-4 flex items-center gap-2">
            <PlaySquare className="w-4 h-4 text-red-500" />
            Table of Contents
          </h2>
          <nav>
            <ol className="space-y-2.5 text-sm text-zinc-400">
              {post.sections.map((section, idx) => (
                <li key={section.id}>
                  <a
                    href={`#${section.id}`}
                    className="hover:text-red-400 transition-colors flex items-start gap-2"
                  >
                    <span className="text-zinc-600 font-mono text-xs mt-0.5">{idx + 1}.</span>
                    <span>{section.heading}</span>
                  </a>
                </li>
              ))}
              <li>
                <a
                  href="#frequently-asked-questions"
                  className="hover:text-red-400 transition-colors flex items-start gap-2"
                >
                  <span className="text-zinc-600 font-mono text-xs mt-0.5">{post.sections.length + 1}.</span>
                  <span>Frequently Asked Questions</span>
                </a>
              </li>
              <li>
                <a
                  href="#recommended-creator-tools"
                  className="hover:text-red-400 transition-colors flex items-start gap-2"
                >
                  <span className="text-zinc-600 font-mono text-xs mt-0.5">{post.sections.length + 2}.</span>
                  <span>Recommended Creator Tools</span>
                </a>
              </li>
            </ol>
          </nav>
        </div>

        {/* Structured Sections */}
        <div className="space-y-16">
          {post.sections.map((section, sIdx) => (
            <section key={section.id} id={section.id} className="scroll-mt-24">
              <h2 className="text-2xl sm:text-3xl font-extrabold text-zinc-100 mb-6 flex items-baseline gap-3">
                <span className="text-red-500 font-mono text-lg sm:text-xl">0{sIdx + 1}.</span>
                <span>{section.heading}</span>
              </h2>

              {/* Body Paragraphs */}
              <div className="space-y-4 text-zinc-300 text-base sm:text-lg leading-relaxed mb-6">
                {section.content.split("\n\n").map((para, pIdx) => (
                  <p key={pIdx}>{para}</p>
                ))}
              </div>

              {/* Callout Box (if present) */}
              {section.callout && (
                <div className={`my-6 p-5 rounded-2xl border ${
                  section.callout.type === "warning"
                    ? "bg-rose-500/10 border-rose-500/30 text-rose-200"
                    : section.callout.type === "success"
                    ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-200"
                    : section.callout.type === "tip"
                    ? "bg-amber-500/10 border-amber-500/30 text-amber-200"
                    : "bg-blue-500/10 border-blue-500/30 text-blue-200"
                }`}>
                  <div className="flex items-center gap-2 font-bold mb-1.5 text-sm sm:text-base">
                    {section.callout.type === "warning" ? (
                      <AlertTriangle className="w-4 h-4 text-rose-400" />
                    ) : section.callout.type === "success" ? (
                      <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                    ) : section.callout.type === "tip" ? (
                      <Lightbulb className="w-4 h-4 text-amber-400" />
                    ) : (
                      <Info className="w-4 h-4 text-blue-400" />
                    )}
                    <span>{section.callout.title}</span>
                  </div>
                  <p className="text-sm sm:text-base leading-relaxed opacity-90">
                    {section.callout.text}
                  </p>
                </div>
              )}

              {/* Table (if present) */}
              {section.table && (
                <div className="my-8 overflow-x-auto rounded-2xl border border-zinc-800 bg-zinc-900/40">
                  <table className="w-full text-left text-xs sm:text-sm text-zinc-300 border-collapse">
                    <thead>
                      <tr className="bg-zinc-900 border-b border-zinc-800 text-zinc-100">
                        {section.table.headers.map((h, i) => (
                          <th key={i} className="p-3.5 sm:p-4 font-semibold whitespace-nowrap">
                            {h}
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-zinc-800/60">
                      {section.table.rows.map((row, rIdx) => (
                        <tr key={rIdx} className="hover:bg-zinc-800/30 transition-colors">
                          {row.map((cell, cIdx) => (
                            <td key={cIdx} className="p-3.5 sm:p-4 whitespace-nowrap sm:whitespace-normal">
                              {cell}
                            </td>
                          ))}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {/* Bullets (if present) */}
              {section.bullets && (
                <ul className="my-6 space-y-2.5">
                  {section.bullets.map((bullet, bIdx) => (
                    <li key={bIdx} className="flex items-start gap-3 text-sm sm:text-base text-zinc-300">
                      <CheckCircle2 className="w-4 h-4 text-red-500 shrink-0 mt-1" />
                      <span>{bullet}</span>
                    </li>
                  ))}
                </ul>
              )}
            </section>
          ))}
        </div>

        {/* Inline Related Tools Banner */}
        <section id="recommended-creator-tools" className="mt-16 pt-12 border-t border-zinc-800 scroll-mt-24">
          <div className="mb-6">
            <span className="text-xs font-bold text-red-400 uppercase tracking-widest bg-red-500/10 px-3 py-1 rounded-full border border-red-500/20 inline-block mb-2">
              Free YTToolkits Utility
            </span>
            <h2 className="text-2xl sm:text-3xl font-extrabold text-white flex items-center gap-2">
              <Wrench className="w-6 h-6 text-red-500" />
              Recommended Free Tools for This Strategy
            </h2>
            <p className="text-zinc-400 text-sm mt-1">
              Complement your implementation with these 100% free creator tools:
            </p>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {post.relatedTools.map((tool, i) => (
              <Link
                key={i}
                href={tool.href}
                className="flex flex-col p-5 bg-zinc-900/50 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700 rounded-2xl transition-all group"
              >
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-bold text-zinc-100 group-hover:text-red-400 transition-colors text-base flex items-center gap-1.5">
                    {tool.name}
                  </h3>
                  <ExternalLink className="w-4 h-4 text-zinc-500 group-hover:text-red-400 transition-colors" />
                </div>
                <p className="text-zinc-400 text-xs sm:text-sm leading-relaxed">
                  {tool.desc}
                </p>
              </Link>
            ))}
          </div>
        </section>

        {/* FAQ Accordion Section */}
        <section id="frequently-asked-questions" className="mt-16 pt-12 border-t border-zinc-800 scroll-mt-24">
          <div className="mb-8">
            <span className="text-xs font-bold text-emerald-400 uppercase tracking-widest bg-emerald-500/10 px-3 py-1 rounded-full border border-emerald-500/20 inline-block mb-2">
              Expert Answers
            </span>
            <h2 className="text-2xl sm:text-3xl font-extrabold text-white flex items-center gap-2">
              <HelpCircle className="w-6 h-6 text-emerald-400" />
              Frequently Asked Questions
            </h2>
            <p className="text-zinc-400 text-sm mt-1">
              Direct answers to common questions regarding {post.title.toLowerCase()}
            </p>
          </div>

          <div className="space-y-4">
            {post.faqs.map((faq, fIdx) => (
              <details
                key={fIdx}
                className="group bg-zinc-900/40 border border-zinc-800 rounded-2xl p-5 hover:border-zinc-700 transition-all [&_summary::-webkit-details-marker]:hidden"
              >
                <summary className="flex items-center justify-between cursor-pointer list-none font-semibold text-zinc-100 group-open:text-red-400 transition-colors text-base sm:text-lg">
                  <span className="pr-4">{faq.question}</span>
                  <span className="shrink-0 text-zinc-500 group-open:rotate-180 transition-transform">
                    &darr;
                  </span>
                </summary>
                <div className="mt-4 pt-4 border-t border-zinc-800/70 text-zinc-300 text-sm sm:text-base leading-relaxed">
                  {faq.answer}
                </div>
              </details>
            ))}
          </div>
        </section>

        {/* Author Bio Card */}
        <div className="mt-16 p-6 sm:p-8 bg-zinc-900/60 border border-zinc-800 rounded-3xl flex flex-col sm:flex-row items-start sm:items-center gap-5">
          <div className="w-16 h-16 rounded-2xl bg-red-600/20 border border-red-500/30 flex items-center justify-center font-bold text-red-400 text-2xl shrink-0">
            AR
          </div>
          <div>
            <div className="text-xs font-bold text-zinc-500 uppercase tracking-wider mb-1">
              Written By
            </div>
            <h3 className="text-lg font-bold text-white mb-1">
              {post.author.name}
            </h3>
            <p className="text-xs text-red-400 mb-2">{post.author.role}</p>
            <p className="text-zinc-400 text-xs sm:text-sm leading-relaxed">
              Alex has managed, optimized, and consulted for channels exceeding 50M+ combined monthly views. He specializes in YouTube search engine mechanics, CTR psychology, and monetization optimization for independent creators.
            </p>
          </div>
        </div>

        {/* More Articles Section */}
        <div className="mt-20 pt-12 border-t border-zinc-800">
          <div className="flex items-center justify-between mb-8">
            <div>
              <h2 className="text-2xl font-bold text-white">
                Continue Reading
              </h2>
              <p className="text-xs sm:text-sm text-zinc-400 mt-1">
                More in-depth strategies from the Creator Academy
              </p>
            </div>
            <Link
              href="/blog"
              className="text-xs font-semibold text-red-400 hover:text-red-300 flex items-center gap-1"
            >
              All Guides &rarr;
            </Link>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {relatedPosts.map((related) => {
              const rColor = categoryColors[related.category] || categoryColors["Creator Guides"];
              return (
                <article
                  key={related.slug}
                  className="flex flex-col bg-zinc-900/40 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700 rounded-2xl p-5 transition-all group"
                >
                  <div className="flex items-center justify-between gap-2 mb-2.5">
                    <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${rColor.bg} ${rColor.text} ${rColor.border}`}>
                      {related.category}
                    </span>
                    <span className="text-[10px] text-zinc-500">{related.readTime}</span>
                  </div>

                  <Link href={`/blog/${related.slug}`} className="block flex-1 mb-3">
                    <h3 className="font-bold text-zinc-100 group-hover:text-red-400 transition-colors text-sm line-clamp-2 leading-snug">
                      {related.title}
                    </h3>
                  </Link>

                  <Link
                    href={`/blog/${related.slug}`}
                    className="text-xs font-semibold text-red-400 hover:text-red-300 flex items-center gap-1 mt-auto pt-3 border-t border-zinc-800/70"
                  >
                    Read Guide <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
                  </Link>
                </article>
              );
            })}
          </div>
        </div>
      </div>
    </article>
  );
}
