'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { ArrowLeft, Calendar, User, Tag, Clock, Share2, BookOpen, Anchor } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { LandingHeader, LandingFooter } from '@/components/layout';
import { getBlogPost, type BlogPost } from '@/lib/api/blog';
import DOMPurify from 'isomorphic-dompurify';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';

function resolveUrl(url: string | null | undefined): string | undefined {
  if (!url) return undefined;
  if (url.startsWith('http')) return url;
  return `${API_BASE_URL}${url}`;
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('fr-FR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}

function estimateReadingTime(content: string): number {
  const text = content.replace(/<[^>]*>/g, '');
  const words = text.trim().split(/\s+/).length;
  return Math.max(1, Math.ceil(words / 200));
}

const CATEGORY_LABELS: Record<string, string> = {
  industry: 'Industrie',
  technology: 'Technologie',
  guides: 'Guides',
  news: 'Actualités',
};

function LoadingSkeleton() {
  return (
    <div className="min-h-screen bg-white">
      <LandingHeader />
      <div className="max-w-4xl mx-auto px-6 pt-32 pb-20">
        <div className="animate-pulse space-y-6">
          <div className="h-4 bg-gray-200 rounded w-24" />
          <div className="h-10 bg-gray-200 rounded w-3/4" />
          <div className="h-5 bg-gray-200 rounded w-1/2" />
          <div className="h-72 bg-gray-200 rounded-2xl mt-8" />
          <div className="space-y-3 mt-8">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-4 bg-gray-200 rounded" style={{ width: `${85 + (i % 3) * 5}%` }} />
            ))}
          </div>
        </div>
      </div>
      <LandingFooter />
    </div>
  );
}

function NotFoundView() {
  return (
    <div className="min-h-screen bg-white">
      <LandingHeader />
      <div className="max-w-4xl mx-auto px-6 pt-32 pb-20 text-center">
        <Anchor className="w-24 h-24 text-gray-200 mx-auto mb-6" />
        <h1 className="text-3xl font-bold text-brand-navy mb-4">Article introuvable</h1>
        <p className="text-gray-600 mb-8">
          Cet article n&apos;existe pas ou n&apos;est pas encore publié.
        </p>
        <Link href="/blog">
          <span className="inline-flex items-center space-x-2 px-6 py-3 bg-brand-turquoise text-white rounded-lg hover:bg-brand-turquoise/90 transition-all font-semibold">
            <ArrowLeft className="w-4 h-4" />
            <span>Retour au blog</span>
          </span>
        </Link>
      </div>
      <LandingFooter />
    </div>
  );
}

export default function BlogPostContent({ slug }: { slug: string }) {
  const [post, setPost] = useState<BlogPost | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    if (!slug) return;
    let cancelled = false;

    getBlogPost(slug)
      .then(p => {
        if (!cancelled) setPost(p);
      })
      .catch(() => {
        if (!cancelled) setNotFound(true);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => { cancelled = true; };
  }, [slug]);

  if (loading) return <LoadingSkeleton />;
  if (notFound || !post) return <NotFoundView />;

  const readingTime = estimateReadingTime(post.content);
  // Sanitize the admin-authored HTML before rendering (stored-XSS defense in depth)
  const processedContent = DOMPurify.sanitize(
    post.content.replace(/src="(\/api\/v1\/blog\/images\/[^"]+)"/g, `src="${API_BASE_URL}$1"`)
  );

  const handleShare = () => {
    if (navigator.share) {
      navigator.share({ title: post.title, url: window.location.href });
    } else {
      navigator.clipboard.writeText(window.location.href);
    }
  };

  return (
    <div className="min-h-screen bg-white">
      <LandingHeader />

      {/* Hero */}
      <section className="relative pt-32 pb-20 bg-gradient-to-br from-brand-navy via-brand-navy to-[#1a2a5e]">
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute top-20 left-20 w-96 h-96 bg-brand-turquoise/10 rounded-full blur-3xl" />
          <div className="absolute bottom-10 right-20 w-64 h-64 bg-blue-400/10 rounded-full blur-3xl" />
        </div>

        <div className="relative z-10 max-w-4xl mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
          >
            <Link href="/blog">
              <span className="inline-flex items-center space-x-2 text-white/60 hover:text-white transition-colors mb-8 text-sm group">
                <ArrowLeft className="w-4 h-4 group-hover:-translate-x-0.5 transition-transform" />
                <span>Retour au blog</span>
              </span>
            </Link>

            <div className="flex items-center flex-wrap gap-3 mb-6">
              <span className="px-3 py-1 bg-brand-turquoise text-white text-sm font-medium rounded-full">
                {CATEGORY_LABELS[post.category] ?? post.category}
              </span>
              {post.isFeatured && (
                <span className="px-3 py-1 bg-white/15 text-white text-sm font-medium rounded-full border border-white/20">
                  À la une
                </span>
              )}
            </div>

            <h1 className="text-3xl lg:text-5xl font-bold text-white mb-6 leading-tight tracking-tight">
              {post.title}
            </h1>

            <p className="text-lg text-white/75 mb-10 leading-relaxed max-w-2xl">{post.excerpt}</p>

            <div className="flex flex-wrap items-center gap-x-6 gap-y-3 text-white/55 text-sm">
              <div className="flex items-center space-x-2">
                <User className="w-4 h-4" />
                <span>{post.authorName}</span>
              </div>
              {post.publishedAt && (
                <div className="flex items-center space-x-2">
                  <Calendar className="w-4 h-4" />
                  <span>{formatDate(post.publishedAt)}</span>
                </div>
              )}
              <div className="flex items-center space-x-2">
                <Clock className="w-4 h-4" />
                <span>{readingTime} min de lecture</span>
              </div>
              {post.tags.length > 0 && (
                <div className="flex items-center space-x-2">
                  <Tag className="w-4 h-4" />
                  <span>{post.tags.join(', ')}</span>
                </div>
              )}
            </div>
          </motion.div>
        </div>

        <div className="absolute bottom-0 left-0 right-0">
          <svg className="w-full h-16" viewBox="0 0 1440 64" preserveAspectRatio="none">
            <path d="M0,32 C360,64 720,0 1080,32 C1260,48 1380,24 1440,32 L1440,64 L0,64 Z" fill="white" />
          </svg>
        </div>
      </section>

      {/* Cover Image */}
      {post.coverImageUrl && (
        <div className="max-w-4xl mx-auto px-6 lg:px-8 -mt-6 relative z-10 mb-4">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
          >
            <img
              src={resolveUrl(post.coverImageUrl)}
              alt={post.title}
              className="w-full h-72 lg:h-[420px] object-cover rounded-2xl shadow-2xl"
            />
          </motion.div>
        </div>
      )}

      {/* Content + Sidebar */}
      <section className="py-12">
        <div className="max-w-4xl mx-auto px-6 lg:px-8">
          {/* En bref (AI summary / TL;DR) */}
          {post.aiSummary && (
            <div className="mb-10 rounded-2xl border border-brand-turquoise/30 bg-brand-turquoise/5 p-6">
              <p className="text-xs font-semibold uppercase tracking-wide text-brand-turquoise mb-2">
                En bref
              </p>
              <p className="text-gray-700 leading-relaxed">{post.aiSummary}</p>
            </div>
          )}

          <div className="lg:grid lg:grid-cols-[1fr_80px] lg:gap-8 items-start">
            {/* Article body */}
            <motion.article
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.3 }}
              className="prose prose-lg prose-slate max-w-none
                prose-headings:font-bold prose-headings:text-brand-navy prose-headings:tracking-tight
                prose-h2:text-2xl prose-h2:mt-10 prose-h2:mb-4 prose-h2:border-l-4 prose-h2:border-brand-turquoise prose-h2:pl-4
                prose-h3:text-xl prose-h3:mt-8 prose-h3:mb-3
                prose-p:text-gray-700 prose-p:leading-relaxed prose-p:mb-5
                prose-a:text-brand-turquoise prose-a:font-medium hover:prose-a:underline
                prose-strong:text-brand-navy
                prose-blockquote:not-italic
                prose-ul:text-gray-700 prose-ol:text-gray-700
                prose-img:rounded-xl prose-img:shadow-lg"
              dangerouslySetInnerHTML={{ __html: processedContent }}
            />

            {/* Floating share button (desktop) */}
            <div className="hidden lg:block sticky top-24">
              <button
                onClick={handleShare}
                className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-full shadow-sm text-gray-400 hover:text-brand-turquoise hover:border-brand-turquoise transition-colors"
                title="Partager l'article"
              >
                <Share2 className="w-4 h-4" />
              </button>
            </div>
          </div>

          {/* À retenir (key takeaways) */}
          {post.keyTakeaways && post.keyTakeaways.length > 0 && (
            <div className="mt-12 rounded-2xl border border-gray-200 bg-gray-50 p-6">
              <h2 className="text-lg font-bold text-brand-navy mb-4">À retenir</h2>
              <ul className="space-y-2">
                {post.keyTakeaways.map((item, i) => (
                  <li key={i} className="flex items-start gap-3 text-gray-700">
                    <span className="mt-2 w-1.5 h-1.5 rounded-full bg-brand-turquoise flex-shrink-0" />
                    <span className="leading-relaxed">{item}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* FAQ */}
          {post.faq && post.faq.length > 0 && (
            <div className="mt-12">
              <h2 className="text-2xl font-bold text-brand-navy mb-6">Questions fréquentes</h2>
              <div className="space-y-4">
                {post.faq.map((item, i) => (
                  <details
                    key={i}
                    className="group rounded-xl border border-gray-200 bg-white p-5 open:shadow-sm"
                  >
                    <summary className="cursor-pointer font-semibold text-brand-navy list-none flex items-center justify-between gap-4">
                      <span>{item.question}</span>
                      <span className="text-brand-turquoise transition-transform group-open:rotate-45 text-xl leading-none">
                        +
                      </span>
                    </summary>
                    <p className="mt-3 text-gray-700 leading-relaxed">{item.answer}</p>
                  </details>
                ))}
              </div>
            </div>
          )}

          {/* Tags */}
          {post.tags.length > 0 && (
            <div className="flex flex-wrap gap-2 mt-12 pt-8 border-t border-gray-100">
              {post.tags.map(tag => (
                <span
                  key={tag}
                  className="px-3 py-1.5 bg-gray-100 text-gray-600 text-sm rounded-full hover:bg-gray-200 transition-colors"
                >
                  #{tag}
                </span>
              ))}
            </div>
          )}

          {/* CTA */}
          <div className="mt-16 rounded-2xl bg-gradient-to-br from-brand-navy to-[#1a2a5e] p-8 lg:p-10 text-center">
            <BookOpen className="w-8 h-8 text-brand-turquoise mx-auto mb-4" />
            <h2 className="text-xl lg:text-2xl font-bold text-white mb-3">
              Prêt à tester Xpeditis ?
            </h2>
            <p className="text-white/70 mb-6 max-w-md mx-auto text-sm leading-relaxed">
              Créez votre compte en 2 minutes et lancez votre premier chiffrage maritime instantané.
              C&apos;est gratuit et sans engagement.
            </p>
            <a
              href="/register"
              className="inline-flex items-center gap-2 px-6 py-3 bg-brand-turquoise text-white rounded-xl font-semibold hover:bg-brand-turquoise/90 transition-all shadow-lg hover:shadow-xl hover:-translate-y-0.5"
            >
              Créer mon compte gratuitement
            </a>
          </div>

          {/* Back + Share */}
          <div className="mt-10 flex items-center justify-between">
            <Link href="/blog">
              <span className="inline-flex items-center space-x-2 px-5 py-2.5 bg-brand-navy text-white rounded-xl hover:bg-brand-navy/90 transition-all font-medium text-sm group">
                <ArrowLeft className="w-4 h-4 group-hover:-translate-x-0.5 transition-transform" />
                <span>Retour au blog</span>
              </span>
            </Link>
            <button
              onClick={handleShare}
              className="lg:hidden inline-flex items-center space-x-2 px-4 py-2.5 border border-gray-200 rounded-xl text-gray-600 hover:border-brand-turquoise hover:text-brand-turquoise transition-colors text-sm"
            >
              <Share2 className="w-4 h-4" />
              <span>Partager</span>
            </button>
          </div>
        </div>
      </section>

      <LandingFooter />
    </div>
  );
}
