/**
 * Blog Article Detail Page (/blog/[slug])
 *
 * Full responsive article reader with server-side data hydration,
 * rich typography, BlogPosting & BreadcrumbList JSON-LD structured data,
 * and related booking CTAs.
 */

import { type Metadata } from 'next';
import { notFound } from 'next/navigation';
import Link from 'next/link';
import {
  Calendar,
  User,
  Clock,
  ArrowLeft,
  ChevronRight,
  Sparkles,
  Share2,
} from 'lucide-react';
import { getBlogs, getBlogBySlug, slugify } from '@/lib/api/client';
import { ImageWithFallback } from '@/components/ui/ImageWithFallback';
import { Footer } from '@/components/layout/Footer';
import { stripHtml } from '@/lib/utils';
import { type Locale, locales } from '@/i18n';

interface BlogPageProps {
  params: Promise<{ locale: Locale; slug: string }>;
}

export const revalidate = 60;

export async function generateStaticParams() {
  const result = await getBlogs();
  if (!result.ok) return [];

  const params: { locale: Locale; slug: string }[] = [];
  result.data.forEach((blog) => {
    const slug = blog.slug || slugify(blog.title);
    if (slug) {
      locales.forEach((locale) => {
        params.push({ locale, slug });
      });
    }
  });

  return params;
}

export async function generateMetadata({ params }: BlogPageProps): Promise<Metadata> {
  const { locale, slug } = await params;
  const isAr = locale === 'ar';

  const blogResult = await getBlogBySlug(slug);
  if (!blogResult.ok || !blogResult.data) {
    return { title: 'Article Not Found | ShineCode' };
  }

  const blog = blogResult.data;
  const title = blog.title;
  const cleanDescription = stripHtml(blog.excerpt || blog.description || blog.content || '', 160);
  
  let image = 'https://shinecode.ae/images/frontend/socialP.webp';
  if (blog.featured_image) {
    image = blog.featured_image;
  } else if (Array.isArray(blog.attchments) && blog.attchments.length > 0) {
    image = blog.attchments[0] || image;
  }

  const pageTitle = isAr
    ? `${title} | مدونة ShineCode دبي`
    : `${title} | ShineCode Beauty Blog`;

  return {
    title: pageTitle,
    description: cleanDescription,
    alternates: {
      canonical: `https://shinecode.ae/${locale}/blog/${slug}`,
      languages: {
        en: `https://shinecode.ae/en/blog/${slug}`,
        ar: `https://shinecode.ae/ar/blog/${slug}`,
        'x-default': `https://shinecode.ae/en/blog/${slug}`,
      },
    },
    openGraph: {
      title: pageTitle,
      description: cleanDescription,
      url: `https://shinecode.ae/${locale}/blog/${slug}`,
      siteName: 'ShineCode',
      images: [
        {
          url: image,
          width: 1200,
          height: 630,
          alt: title,
        },
      ],
      type: 'article',
      publishedTime: blog.publish_date || blog.created_at,
      modifiedTime: blog.updated_at || blog.created_at,
      authors: [blog.author_name || blog.author || 'ShineCode Team'],
      locale: isAr ? 'ar_AE' : 'en_AE',
    },
    twitter: {
      card: 'summary_large_image',
      title: pageTitle,
      description: cleanDescription,
      images: [image],
    },
  };
}

export default async function BlogDetailPage({ params }: BlogPageProps) {
  const { locale, slug } = await params;
  const isAr = locale === 'ar';

  const [blogResult, allBlogsResult] = await Promise.all([
    getBlogBySlug(slug),
    getBlogs(),
  ]);

  if (!blogResult.ok || !blogResult.data) {
    notFound();
  }

  const blog = blogResult.data;
  const allBlogs = allBlogsResult.ok ? allBlogsResult.data : [];
  const relatedBlogs = allBlogs
    .filter((b) => b.id !== blog.id)
    .slice(0, 3);

  const cleanDescription = stripHtml(blog.excerpt || blog.description || blog.content || '', 160);
  const blogImage =
    blog.featured_image ||
    (Array.isArray(blog.attchments) && blog.attchments.length > 0
      ? blog.attchments[0]
      : 'https://shinecode.ae/images/frontend/socialP.webp');

  const authorName = blog.author_name || blog.author || (isAr ? 'فريق ShineCode' : 'ShineCode Editorial Team');
  const publishDate = blog.publish_date || (blog.created_at ? new Date(blog.created_at).toLocaleDateString(isAr ? 'ar-AE' : 'en-US', { dateStyle: 'medium' }) : '');

  // Estimate reading time based on content length
  const wordCount = (blog.description || blog.content || '').replace(/<[^>]*>/g, '').split(/\s+/).length;
  const readingTimeMins = Math.max(1, Math.ceil(wordCount / 200));

  // Structured Data: BlogPosting Schema
  const blogPostingSchema = {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    headline: blog.title,
    description: cleanDescription,
    image: blogImage ? [blogImage] : undefined,
    datePublished: blog.publish_date || blog.created_at,
    dateModified: blog.updated_at || blog.created_at || blog.publish_date,
    author: {
      '@type': 'Person',
      name: authorName,
      image: blog.author_image || undefined,
    },
    publisher: {
      '@type': 'Organization',
      name: 'ShineCode',
      url: 'https://shinecode.ae',
      logo: {
        '@type': 'ImageObject',
        url: 'https://shinecode.ae/images/logo.png',
      },
    },
    mainEntityOfPage: {
      '@type': 'WebPage',
      '@id': `https://shinecode.ae/${locale}/blog/${slug}`,
    },
  };

  // Structured Data: BreadcrumbList Schema
  const breadcrumbSchema = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      {
        '@type': 'ListItem',
        position: 1,
        name: isAr ? 'الرئيسية' : 'Home',
        item: `https://shinecode.ae/${locale}`,
      },
      {
        '@type': 'ListItem',
        position: 2,
        name: isAr ? 'المدونة' : 'Blog',
        item: `https://shinecode.ae/${locale}/blog`,
      },
      {
        '@type': 'ListItem',
        position: 3,
        name: blog.title,
        item: `https://shinecode.ae/${locale}/blog/${slug}`,
      },
    ],
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(blogPostingSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />

      <div className="min-h-screen bg-background flex flex-col">
        <main id="main-content" className="flex-1">
          {/* Breadcrumb Bar */}
          <section className="bg-zinc-50 dark:bg-zinc-900/50 border-b border-zinc-200/80 dark:border-zinc-800 py-3.5">
            <div className="container mx-auto px-4 lg:px-8">
              <nav aria-label="Breadcrumb" className="flex items-center gap-2 text-xs text-zinc-500 dark:text-zinc-400">
                <Link href={`/${locale}`} className="hover:text-brand-500 transition-colors">
                  {isAr ? 'الرئيسية' : 'Home'}
                </Link>
                <ChevronRight className="w-3.5 h-3.5 rtl:rotate-180" />
                <Link href={`/${locale}/blog`} className="hover:text-brand-500 transition-colors">
                  {isAr ? 'المدونة' : 'Blog'}
                </Link>
                <ChevronRight className="w-3.5 h-3.5 rtl:rotate-180" />
                <span className="text-zinc-900 dark:text-white font-medium truncate max-w-xs sm:max-w-md">
                  {blog.title}
                </span>
              </nav>
            </div>
          </section>

          {/* Article Header & Hero */}
          <article className="py-10 md:py-16">
            <div className="container mx-auto px-4 lg:px-8 max-w-4xl">
              {/* Back to Blog */}
              <Link
                href={`/${locale}/blog`}
                className="inline-flex items-center gap-2 text-xs font-semibold text-zinc-500 hover:text-brand-500 dark:text-zinc-400 dark:hover:text-brand-400 transition-colors mb-6"
              >
                <ArrowLeft className="w-4 h-4 rtl:rotate-180" />
                <span>{isAr ? 'العودة إلى المدونة' : 'Back to all articles'}</span>
              </Link>

              {/* Title (H1) */}
              <h1 className="text-3xl sm:text-4xl md:text-5xl font-extrabold text-zinc-900 dark:text-white tracking-tight leading-tight mb-6">
                {blog.title}
              </h1>

              {/* Meta details bar */}
              <div className="flex flex-wrap items-center gap-4 sm:gap-6 text-sm text-zinc-600 dark:text-zinc-400 pb-8 mb-8 border-b border-zinc-200 dark:border-zinc-800">
                <div className="flex items-center gap-2.5">
                  {blog.author_image ? (
                    <img
                      src={blog.author_image}
                      alt={authorName}
                      className="w-9 h-9 rounded-full object-cover border border-zinc-200 dark:border-zinc-700"
                    />
                  ) : (
                    <div className="w-9 h-9 rounded-full bg-brand-50 dark:bg-brand-950/60 border border-brand-200 dark:border-brand-900/40 flex items-center justify-center text-brand-600 font-bold">
                      <User className="w-4 h-4" />
                    </div>
                  )}
                  <div>
                    <div className="font-semibold text-zinc-900 dark:text-white">{authorName}</div>
                    <div className="text-xs text-zinc-500">{isAr ? 'مستشار العناية والجمال' : 'Beauty & Wellness Specialist'}</div>
                  </div>
                </div>

                {publishDate && (
                  <div className="flex items-center gap-1.5 text-xs">
                    <Calendar className="w-4 h-4 text-zinc-400" />
                    <span>{publishDate}</span>
                  </div>
                )}

                <div className="flex items-center gap-1.5 text-xs">
                  <Clock className="w-4 h-4 text-zinc-400" />
                  <span>
                    {isAr ? `${readingTimeMins} دقائق قراءة` : `${readingTimeMins} min read`}
                  </span>
                </div>
              </div>

              {/* Featured Image */}
              {blogImage && (
                <div className="relative aspect-[16/9] w-full rounded-2xl overflow-hidden mb-10 shadow-lg border border-zinc-100 dark:border-zinc-800">
                  <ImageWithFallback
                    src={blogImage}
                    alt={blog.title}
                    fill
                    sizes="(max-width: 1024px) 100vw, 896px"
                    priority
                    className="object-cover"
                  />
                </div>
              )}

              {/* Article Rich Content */}
              <div
                className="prose prose-lg dark:prose-invert max-w-none text-zinc-800 dark:text-zinc-200 leading-relaxed prose-headings:font-bold prose-headings:text-zinc-900 dark:prose-headings:text-white prose-a:text-brand-600 dark:prose-a:text-brand-400 prose-img:rounded-xl prose-img:shadow-md"
                dangerouslySetInnerHTML={{ __html: blog.description || blog.content || `<p>${cleanDescription}</p>` }}
              />

              {/* In-Article Doorstep Booking Banner */}
              <div className="mt-14 p-8 rounded-2xl bg-gradient-to-br from-zinc-900 to-zinc-950 text-white border border-zinc-800 relative overflow-hidden shadow-xl">
                <div className="absolute top-0 end-0 w-64 h-64 bg-brand-500/10 rounded-full blur-3xl pointer-events-none" />
                <div className="relative z-10 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
                  <div>
                    <div className="inline-flex items-center gap-1.5 text-xs font-bold text-brand-400 uppercase tracking-widest mb-2">
                      <Sparkles className="w-3.5 h-3.5" />
                      <span>{isAr ? 'خدمة صالون وسبا منزلية' : 'Doorstep Luxury Experience'}</span>
                    </div>
                    <h3 className="text-2xl font-black text-white tracking-tight mb-2">
                      {isAr ? 'جاهزة لتجربة تدليل فاخرة في منزلك؟' : 'Ready for premium at-home pampering?'}
                    </h3>
                    <p className="text-sm text-zinc-400 max-w-md">
                      {isAr
                        ? 'أخصائيات معتمدات ومعدات معقمة بالكامل، نصلك في دبي والشارقة وعجمان خلال دقائق.'
                        : 'Certified professionals and hospital-grade equipment arrive at your doorstep in Dubai, Sharjah, & Ajman.'}
                    </p>
                  </div>
                  <Link
                    href={`/${locale}/services`}
                    className="shrink-0 px-6 py-3.5 bg-brand-500 hover:bg-brand-600 text-white font-bold rounded-xl shadow-lg hover:shadow-brand-500/25 transition-all text-sm flex items-center gap-2"
                  >
                    <span>{isAr ? 'احجزي خدمتك الآن' : 'Book Your Treatment'}</span>
                    <span className="text-xs rtl:rotate-180">→</span>
                  </Link>
                </div>
              </div>

              {/* Related Articles Carousel / Grid */}
              {relatedBlogs.length > 0 && (
                <div className="mt-16 pt-12 border-t border-zinc-200 dark:border-zinc-800">
                  <h3 className="text-2xl font-bold text-zinc-900 dark:text-white mb-8">
                    {isAr ? 'مقالات ذات صلة قد تهمك' : 'Related Articles'}
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    {relatedBlogs.map((item) => {
                      const itemSlug = item.slug || slugify(item.title);
                      const itemImg =
                        item.featured_image ||
                        (Array.isArray(item.attchments) && item.attchments.length > 0
                          ? item.attchments[0]
                          : 'https://shinecode.ae/images/frontend/socialP.webp');

                      return (
                        <Link
                          key={item.id}
                          href={`/${locale}/blog/${itemSlug}`}
                          className="group flex flex-col bg-surface-card dark:bg-zinc-900/60 rounded-xl overflow-hidden border border-zinc-200/80 dark:border-zinc-800 hover:shadow-md transition-all"
                        >
                          <div className="relative aspect-[16/10] w-full overflow-hidden bg-zinc-100 dark:bg-zinc-800">
                            <ImageWithFallback
                              src={itemImg}
                              alt={item.title}
                              fill
                              sizes="(max-width: 768px) 100vw, 300px"
                              className="object-cover group-hover:scale-105 transition-transform duration-300"
                            />
                          </div>
                          <div className="p-4 flex-1 flex flex-col justify-between">
                            <h4 className="font-bold text-sm text-zinc-900 dark:text-white group-hover:text-brand-500 transition-colors line-clamp-2 mb-2">
                              {item.title}
                            </h4>
                            <p className="text-xs text-zinc-500 dark:text-zinc-400 line-clamp-2">
                              {stripHtml(item.excerpt || item.description || '', 100)}
                            </p>
                          </div>
                        </Link>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          </article>
        </main>
        <Footer locale={locale} />
      </div>
    </>
  );
}
