import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';

export const dynamic = 'force-dynamic';
import { Calendar, User, Clock, Facebook, Twitter, MessageCircle, ArrowLeft, Eye } from 'lucide-react';
import { SITE_CONFIG } from '@/lib/constants';
import Sidebar from '@/components/Sidebar';
import VanAssistant from '@/components/VanAssistant';
import ArticleContent from '@/components/ArticleContent';
import InstagramFeaturedShowcase from '@/components/InstagramFeaturedShowcase';
import CategoryWidgets from '@/components/CategoryWidgets';
import RelatedInContent from '@/components/RelatedInContent';

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

async function getArticle(slug: string) {
  try {
    const prisma = (await import('@/lib/db')).default;
    const article = await prisma.article.findUnique({
      where: { slug },
    });

    if (article) {
      // Görüntülenme sayısını artır
      await prisma.article.update({
        where: { id: article.id },
        data: { viewCount: { increment: 1 } },
      });
    }

    return article;
  } catch {
    return null;
  }
}

async function getRelatedArticles(category: string, currentId: number) {
  try {
    const prisma = (await import('@/lib/db')).default;
    return prisma.article.findMany({
      where: {
        category,
        isPublished: true,
        id: { not: currentId },
      },
      orderBy: { publishedAt: 'desc' },
      take: 4,
    });
  } catch {
    return [];
  }
}

async function getPopularArticles() {
  try {
    const prisma = (await import('@/lib/db')).default;
    return prisma.article.findMany({
      where: { isPublished: true },
      orderBy: { viewCount: 'desc' },
      take: 5,
    });
  } catch {
    return [];
  }
}

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

  let article = null;
  try {
    const prisma = (await import('@/lib/db')).default;
    article = await prisma.article.findUnique({
      where: { slug },
      select: { title: true, summary: true, imageUrl: true, publishedAt: true },
    });
  } catch {
    // DB error
  }

  if (!article) {
    return { title: 'Haber Bulunamadı' };
  }

  // Description max 155 karakter (SEO için ideal)
  const metaDescription = article.summary.length > 155
    ? article.summary.substring(0, 152) + '...'
    : article.summary;

  // Canonical URL
  const canonicalUrl = `${SITE_CONFIG.url}/haber/${slug}`;

  return {
    title: article.title,
    description: metaDescription,
    alternates: {
      canonical: canonicalUrl,
    },
    openGraph: {
      title: article.title,
      description: metaDescription,
      type: 'article',
      publishedTime: article.publishedAt.toISOString(),
      images: article.imageUrl ? [{ url: article.imageUrl, width: 1200, height: 630 }] : [],
      siteName: SITE_CONFIG.name,
      url: canonicalUrl,
    },
    twitter: {
      card: 'summary_large_image',
      title: article.title,
      description: metaDescription,
      images: article.imageUrl ? [article.imageUrl] : [],
    },
  };
}

function formatDate(date: Date): string {
  return new Date(date).toLocaleDateString('tr-TR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function estimateReadTime(content: string): string {
  const words = content.split(/\s+/).length;
  const minutes = Math.ceil(words / 200);
  return `${minutes} dk`;
}

export default async function ArticlePage({ params }: Props) {
  const { slug } = await params;
  const [article, popularArticles] = await Promise.all([
    getArticle(slug),
    getPopularArticles(),
  ]);

  if (!article) {
    notFound();
  }

  const relatedArticles = await getRelatedArticles(article.category, article.id);

  // JSON-LD Schema
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'NewsArticle',
    headline: article.title,
    description: article.summary,
    image: article.imageUrl,
    datePublished: article.publishedAt.toISOString(),
    dateModified: article.updatedAt.toISOString(),
    author: {
      '@type': 'Organization',
      name: SITE_CONFIG.name,
      url: SITE_CONFIG.url,
    },
    publisher: {
      '@type': 'Organization',
      name: SITE_CONFIG.name,
      logo: {
        '@type': 'ImageObject',
        url: `${SITE_CONFIG.url}/images/logo.png`,
      },
    },
    mainEntityOfPage: {
      '@type': 'WebPage',
      '@id': `${SITE_CONFIG.url}/haber/${article.slug}`,
    },
  };

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

      <article className="max-w-7xl mx-auto px-4 py-8">
        {/* Breadcrumb */}
        <nav className="flex items-center gap-2 text-sm text-gray-500 mb-6">
          <Link href="/" className="hover:text-red-600 flex items-center gap-1">
            <ArrowLeft size={16} />
            Ana Sayfa
          </Link>
          <span>/</span>
          <Link href={`/kategori/${article.category.toLowerCase()}`} className="hover:text-red-600">
            {article.category}
          </Link>
        </nav>

        <div className="flex flex-col lg:flex-row gap-12">
          <div className="lg:w-2/3">
            {/* Header */}
            <header className="mb-8">
              <div className="flex items-center gap-3 mb-4">
                <span className="inline-block px-4 py-1.5 bg-red-600 text-white text-xs font-bold uppercase rounded-full">
                  {article.category}
                </span>
                <span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 text-gray-600 text-xs font-medium rounded-full">
                  <Eye size={14} />
                  {article.viewCount.toLocaleString('tr-TR')} görüntülenme
                </span>
              </div>
              <h1 className="text-3xl md:text-4xl lg:text-5xl font-extrabold text-gray-900 leading-tight mb-6">
                {article.title}
              </h1>
              <div className="flex flex-wrap items-center gap-4 text-gray-500 text-sm pb-6 border-b border-gray-100">
                <span className="flex items-center gap-2">
                  <Calendar size={16} />
                  {formatDate(article.publishedAt)}
                </span>
                <span className="flex items-center gap-2">
                  <User size={16} />
                  <span className="font-medium text-gray-700">{article.source}</span>
                </span>
                <span className="flex items-center gap-2">
                  <Clock size={16} />
                  {estimateReadTime(article.content)} okuma
                </span>
              </div>
            </header>

            {/* Featured Image - CLS önleme için aspect-ratio kullanıyoruz */}
            {article.imageUrl && (
              <div className="relative w-full aspect-video rounded-2xl overflow-hidden mb-8 bg-gray-100">
                <Image
                  src={article.imageUrl}
                  alt={article.title}
                  fill
                  className="object-cover"
                  priority
                  sizes="(max-width: 1024px) 100vw, 66vw"
                  placeholder="blur"
                  blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAoDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAUH/8QAIhAAAgEDAwUBAAAAAAAAAAAAAQIDAAQRBRIhBhMxQVFh/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAZEQACAwEAAAAAAAAAAAAAAAABAgADESH/2gAMAwEAAhEDEQA/AKuo9V6jqNy1zdXssk0m0O7EZbaMDOPQwB+UpSq1szDSCxm5Z//Z"
                />
              </div>
            )}

            {/* Article Content with AI Tools */}
            <ArticleContent
              content={article.content}
              summary={article.summary}
              title={article.title}
            />

            {/* İçerik içi ilgili haber önerisi */}
            <RelatedInContent
              currentCategory={article.category}
              currentId={article.id}
            />

            <aside aria-label="Europatrans Kurumsal Sosyal Medya ve Hizmetler" className="my-8"><p>Tanıtım · Europatrans</p><div className="relative z-10" aria-label="Europatrans tanıtımı" dangerouslySetInnerHTML={{ __html: "<style>\n#europatrans-google-profile{display:block;box-sizing:border-box;width:calc(100% - 2rem);max-width:699px;min-width:0;margin:2rem auto;padding:0;border:0;background:transparent;container-type:inline-size}\n#europatrans-google-profile .ep-handshake{display:block;width:100%;max-width:100%;height:auto;aspect-ratio:699 / 461;object-fit:contain;border:0;border-radius:16px}\n#europatrans-google-profile figcaption{position:static;box-sizing:border-box;display:block;margin:16px 0 0;padding:0;border:0;background:transparent;text-align:left}\n#europatrans-google-profile .ep-follow-card{display:flex;align-items:center;gap:16px;box-sizing:border-box;width:100%;max-width:100%;min-width:0;margin:0;padding:16px 20px;background:#fff;color:#202124;border:1px solid #e3e6ea;border-radius:16px;box-shadow:0 4px 18px rgba(0,0,0,.08);font:normal 400 16px/1.35 Arial,Helvetica,sans-serif;text-align:left;text-transform:none;text-decoration:none;letter-spacing:normal;transition:box-shadow .2s}\n#europatrans-google-profile .ep-follow-card:hover{box-shadow:0 6px 24px rgba(0,0,0,.14)}\n#europatrans-google-profile .ep-follow-card:focus-visible{outline:3px solid #1659ad;outline-offset:3px}\n#europatrans-google-profile .ep-follow-avatar{display:block;width:64px;height:64px;box-sizing:border-box;max-width:64px;flex:0 0 64px;border-radius:50%;border:1px solid #eee;object-fit:cover}\n#europatrans-google-profile .ep-follow-text{display:flex;min-width:0;flex:1;flex-direction:column;gap:4px}\n#europatrans-google-profile .ep-follow-label{display:flex;align-items:center;gap:6px;color:#5f6368;font-size:13px;line-height:1.35}\n#europatrans-google-profile .ep-follow-label svg{display:block;width:16px;height:16px;flex:0 0 16px}\n#europatrans-google-profile .ep-follow-name{display:block;color:#202124;font-size:17px;font-weight:700;line-height:1.25;letter-spacing:normal}\n#europatrans-google-profile .ep-follow-description{display:block;color:#5f6368;font-size:13px;line-height:1.35}\n#europatrans-google-profile .ep-follow-cta{display:block;box-sizing:border-box;flex-shrink:0;margin:0;padding:9px 14px;border-radius:20px;background:#1a73e8;color:#fff;font-size:13px;font-weight:600;line-height:1.35;white-space:nowrap;text-align:center}\n@container(max-width:480px){#europatrans-google-profile .ep-follow-card{flex-wrap:wrap}#europatrans-google-profile .ep-follow-cta{width:100%}}\n@media(max-width:480px){#europatrans-google-profile .ep-follow-card{flex-wrap:wrap}#europatrans-google-profile .ep-follow-cta{width:100%}}\n@media(prefers-reduced-motion:reduce){#europatrans-google-profile .ep-follow-card{transition:none}}\n</style>\n<figure id=\"europatrans-google-profile\"><img class=\"ep-handshake\" src=\"https://www.europatrans.com.tr/wp-content/themes/europatrans2026/img/kurumsal.avif\" alt=\"Europatrans ta\u015f\u0131ma g\u00f6r\u00fc\u015fmesinde masan\u0131n iki yan\u0131nda tokala\u015fan iki ki\u015fi.\" width=\"699\" height=\"461\" loading=\"lazy\" decoding=\"async\"><figcaption><a class=\"ep-follow-card\" href=\"https://profile.google.com/@europatransnakliyat\" target=\"_blank\" rel=\"me noopener\"><img class=\"ep-follow-avatar\" src=\"https://lh3.googleusercontent.com/a-/ALV-UjUTXz_BLQDhz_M67k5kSAMrjdBRpSs9C2N3DAwAr4MM6blgLMg\" alt=\"\" width=\"64\" height=\"64\" loading=\"lazy\" decoding=\"async\"><span class=\"ep-follow-text\"><span class=\"ep-follow-label\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 48 48\" aria-hidden=\"true\"><path fill=\"#EA4335\" d=\"M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.8 2.4 30.3 0 24 0 14.6 0 6.6 5.4 2.6 13.3l7.9 6.1C12.4 13.7 17.7 9.5 24 9.5z\"/><path fill=\"#4285F4\" d=\"M46.1 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.4c-.5 2.9-2.2 5.3-4.6 6.9l7.4 5.7c4.3-4 6.9-9.9 6.9-17.1z\"/><path fill=\"#FBBC05\" d=\"M10.5 28.6c-.5-1.4-.8-3-.8-4.6s.3-3.2.8-4.6l-7.9-6.1C1 16.6 0 20.2 0 24s1 7.4 2.6 10.7l7.9-6.1z\"/><path fill=\"#34A853\" d=\"M24 48c6.5 0 11.9-2.1 15.9-5.8l-7.4-5.7c-2.1 1.4-4.8 2.3-8.5 2.3-6.3 0-11.6-4.2-13.5-10l-7.9 6.1C6.6 42.6 14.6 48 24 48z\"/></svg>Google Arama Profili</span><strong class=\"ep-follow-name\">Europatrans Nakliyat</strong><span class=\"ep-follow-description\">1995\u2019ten beri evden eve nakliyat, uluslararas\u0131 ta\u015f\u0131mac\u0131l\u0131k ve e\u015fya depolama</span></span><span class=\"ep-follow-cta\">Google\u2019da Takip Et</span></a></figcaption></figure>" }} />
      </aside>{/* Share Buttons */}
            <div className="py-8 border-t border-b border-gray-100 flex flex-wrap items-center gap-4 mb-12">
              <span className="text-sm font-bold text-gray-500 uppercase">Haberi Paylaş:</span>
              <div className="flex gap-2">
                <a
                  href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(`${SITE_CONFIG.url}/haber/${article.slug}`)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-10 h-10 rounded-full bg-[#1877F2] text-white flex items-center justify-center hover:opacity-90 transition-opacity"
                  aria-label="Facebook'ta Paylaş"
                >
                  <Facebook size={20} />
                </a>
                <a
                  href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(`${SITE_CONFIG.url}/haber/${article.slug}`)}&text=${encodeURIComponent(article.title)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-10 h-10 rounded-full bg-[#1DA1F2] text-white flex items-center justify-center hover:opacity-90 transition-opacity"
                  aria-label="Twitter'da Paylaş"
                >
                  <Twitter size={20} />
                </a>
                <a
                  href={`https://wa.me/?text=${encodeURIComponent(`${article.title} - ${SITE_CONFIG.url}/haber/${article.slug}`)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-10 h-10 rounded-full bg-[#25D366] text-white flex items-center justify-center hover:opacity-90 transition-opacity"
                  aria-label="WhatsApp'ta Paylaş"
                >
                  <MessageCircle size={20} />
                </a>
              </div>
            </div>

            {/* Related Articles */}
            {relatedArticles.length > 0 && (
              <section>
                <h2 className="text-2xl font-black mb-6 border-l-4 border-red-600 pl-4 uppercase">
                  İlgili Haberler
                </h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {relatedArticles.map((related) => (
                    <Link
                      key={related.id}
                      href={`/haber/${related.slug}`}
                      className="group flex gap-4"
                    >
                      {related.imageUrl && (
                        <div className="relative w-24 h-24 flex-shrink-0 rounded-lg overflow-hidden bg-gray-100">
                          <Image
                            src={related.imageUrl}
                            alt={related.title}
                            fill
                            className="object-cover"
                            sizes="96px"
                            placeholder="blur"
                            blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAoDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAUH/8QAIhAAAgEDAwUBAAAAAAAAAAAAAQIDAAQRBRIhBhMxQVFh/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAZEQACAwEAAAAAAAAAAAAAAAABAgADESH/2gAMAwEAAhEDEQA/AKuo9V6jqNy1zdXssk0m0O7EZbaMDOPQwB+UpSq1szDSCxm5Z//Z"
                          />
                        </div>
                      )}
                      <div>
                        <h3 className="font-bold text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2">
                          {related.title}
                        </h3>
                        <span className="text-xs text-gray-500">
                          {formatDate(related.publishedAt)}
                        </span>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}
          </div>

          <aside className="lg:w-1/3 space-y-6">
            {/* Kategori bazlı widget */}
            <CategoryWidgets category={article.category} />

            {/* Genel sidebar */}
            <Sidebar popularNews={popularArticles} />
          </aside>
        </div>
      </article>

      <VanAssistant />
    </>
  );
}

