import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import SEOHead from '../components/seo/SEOHead';
import { useLanguage } from '../contexts/LanguageContext';
import { loadContent, type ContentItem } from '../lib/content';

export default function DocDetailPage() {
  const { slug } = useParams<{ slug: string }>();
  const { language } = useLanguage();
  const [content, setContent] = useState<ContentItem | null>(null);

  useEffect(() => {
    if (slug) {
      loadContent('docs', language, slug)
        .then(setContent)
        .catch(() => setContent(null));
    }
  }, [slug, language]);

  if (!content) {
    return (
      <div className="max-w-3xl mx-auto py-20 px-6">
        <div className="animate-pulse space-y-4">
          <div className="h-4 bg-cream-200 rounded w-24" />
          <div className="h-8 bg-cream-200 rounded w-3/4" />
          <div className="h-4 bg-cream-200 rounded w-full" />
        </div>
      </div>
    );
  }

  return (
    <>
      <SEOHead
        title={content.meta.title}
        description={content.meta.description}
        path={`/docs/${slug}`}
      />
      <div className="max-w-3xl mx-auto py-16 lg:py-20 px-6">
        {/* Back link */}
        <Link
          to="/docs"
          className="inline-flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink transition-colors mb-8"
        >
          <ArrowLeft size={14} />
          {language === 'en' ? 'All docs' : '所有文档'}
        </Link>

        {/* Doc body */}
        <article
          className="prose prose-lg prose-warm max-w-none
            prose-headings:font-display prose-headings:tracking-tight
            prose-h1:text-3xl prose-h1:font-bold
            prose-h2:text-2xl prose-h2:font-semibold prose-h2:mt-10
            prose-a:text-sage-700 prose-a:no-underline hover:prose-a:underline
            prose-code:text-sage-700 prose-code:bg-sage-50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded-md prose-code:text-sm
            prose-pre:bg-ink prose-pre:text-cream-100 prose-pre:rounded-xl
            prose-img:rounded-xl
            prose-blockquote:border-sage-300 prose-blockquote:bg-sage-50/30 prose-blockquote:rounded-r-xl prose-blockquote:py-1"
          dangerouslySetInnerHTML={{ __html: content.html }}
        />
      </div>
    </>
  );
}
