import React from 'react'
import { useParams, Link } from 'react-router-dom'
import { useContent } from '../hooks/useContent'
import SEOHead from '../components/SEOHead'
import { decodeHtml } from '../utils/decodeHtml'

export default function ArticleSingle() {
  const { slug } = useParams()
  const { items: posts } = useContent('posts', { pageSize: 1000 })
  const post = posts.find((p) => p.slug === slug)

  if (!post) {
    return (
      <main className="page-container app-container" style={{ textAlign: 'center', paddingTop: '150px' }}>
        <h2>Artikel nicht gefunden</h2>
        <Link to="/artikel" className="primary-button" style={{ marginTop: '20px' }}>Zurück zur Übersicht</Link>
      </main>
    )
  }

  const formattedDate = post.date 
    ? new Date(post.date).toLocaleDateString('de-DE', { year: 'numeric', month: 'long', day: 'numeric' })
    : ''

  return (
    <main className="page-container article-single-page">
      <SEOHead
        url={`/artikel/${post.slug}`}
        type="article"
        title={`${post.title} | Dr. André Knie`} 
        description={post.excerpt || post.title}
      />
      <div className="app-container" style={{ maxWidth: '800px', margin: '0 auto', paddingTop: '120px' }}>
        <Link to="/artikel" style={{ color: 'var(--primary-color)', textDecoration: 'none', marginBottom: '20px', display: 'inline-block' }}>
          ← Zurück zur Übersicht
        </Link>
        <article className="glass-panel" style={{ padding: '40px' }}>
          <header style={{ marginBottom: '30px' }}>
            {formattedDate && <p style={{ color: 'var(--text-secondary)', marginBottom: '10px' }}>{formattedDate}</p>}
            <h1 style={{ fontSize: '2.5rem', marginBottom: '20px' }}>{decodeHtml(post.title)}</h1>
            {post.url && (
              <a href={post.url} target={post.url.startsWith('/') ? "_self" : "_blank"} rel="noopener noreferrer" className="secondary-button" style={{ display: 'inline-block', marginBottom: '20px' }}>
                {post.url.includes('/podcast') ? 'Zum Podcast' : (post.linkText || 'Auf LinkedIn ansehen')}
              </a>
            )}
          </header>
          <div 
            className="article-body content-body"
            dangerouslySetInnerHTML={{ __html: post.body }} 
          />
        </article>
      </div>
    </main>
  )
}
