import { useState, useEffect, useCallback } from 'react'
import { FileText, Plus, Edit2, Archive, CheckCircle, Clock, Copy, Download, ChevronUp, ChevronDown, Eye } from 'lucide-react'
import api from '../utils/api'
import { generateLegalPdf, legalSectionNumber } from '../utils/legalPdfExport'
import LegalDocumentBody from '../components/LegalDocumentBody'
import { LegalPreviewModal } from '../components/LegalDocumentPreview'
const PDF_STATUS_META = { published: 'Gültig seit', draft: 'Entwurf — Stand', archived: 'Archiviert — Stand' }
// ─── Sub-components ──────────────────────────────────────────────────────────
const DOC_TYPES = [
{ key: 'impressum', label: 'Impressum', defaultTitle: 'Impressum' },
{ key: 'privacy_policy', label: 'Datenschutz', defaultTitle: 'Datenschutzerklärung' },
{ key: 'terms_of_use', label: 'Nutzungsbedingungen', defaultTitle: 'Nutzungsbedingungen' },
{ key: 'media_policy', label: 'Medienrichtlinie', defaultTitle: 'Medienrichtlinie' },
]
const STATUS_LABELS = {
draft: { label: 'Entwurf', color: 'var(--text3)' },
published: { label: 'Veröffentlicht', color: 'var(--accent)' },
archived: { label: 'Archiviert', color: 'var(--danger)' },
}
function StatusBadge({ status }) {
const s = STATUS_LABELS[status] || { label: status, color: 'var(--text3)' }
return (
{s.label}
)
}
function SectionEditor({ sections, onChange }) {
const update = (i, field, val) =>
onChange(sections.map((s, idx) => idx === i ? { ...s, [field]: val } : s))
const remove = (i) => onChange(sections.filter((_, idx) => idx !== i))
const move = (i, dir) => {
const next = [...sections]
const j = i + dir
if (j < 0 || j >= next.length) return
;[next[i], next[j]] = [next[j], next[i]]
onChange(next)
}
// Insert empty section after index i (-1 = prepend)
const insertAfter = (i) => {
const next = [...sections]
next.splice(i + 1, 0, { heading: '', content: '' })
onChange(next)
}
const InsertButton = ({ afterIndex }) => (
insertAfter(afterIndex)}
title="Neuen Abschnitt hier einfügen"
style={{
background: 'none', border: '1px dashed var(--border)', borderRadius: '6px',
color: 'var(--text3)', cursor: 'pointer', fontSize: '0.78rem',
padding: '2px 16px', lineHeight: 1.8,
}}
>
+ Abschnitt hier einfügen
)
return (
{sections.map((sec, i) => (
Abschnitt {i + 1}
move(i, -1)} disabled={i === 0}
title="Nach oben" className="btn btn-secondary"
style={{ padding: '2px 6px', opacity: i === 0 ? 0.3 : 1 }}
>
move(i, 1)} disabled={i === sections.length - 1}
title="Nach unten" className="btn btn-secondary"
style={{ padding: '2px 6px', opacity: i === sections.length - 1 ? 0.3 : 1 }}
>
remove(i)}
className="btn btn-secondary" style={{ fontSize: '0.75rem', padding: '2px 8px' }}
>
Entfernen
Überschrift
update(i, 'heading', e.target.value)}
placeholder="Abschnittsüberschrift"
/>
Inhalt
Einfache Markdown-Formatierung: **fett**, *kursiv*, Listen (- oder 1.), [Link](https://…), Zeilenumbruch mit Leerzeile.
Live-Vorschau
{sec.heading?.trim()
? `${legalSectionNumber(i)} ${sec.heading}`
: legalSectionNumber(i)}
{sec.content
?
: (noch kein Text) }
))}
{sections.length === 0 && (
Noch keine Abschnitte. Klicke auf „+ Abschnitt hier einfügen".
)}
)
}
function DocumentRow({ doc, onPublish, onArchive, onEdit, onCopy, onDownload, onViewAudit, onRenderedPreview }) {
const [downloading, setDownloading] = useState(false)
const handleDownload = async () => {
setDownloading(true)
try { await onDownload(doc) } finally { setDownloading(false) }
}
return (
{doc.title}{' '}
v{doc.version}
{doc.published_at && (
veröffentlicht {new Date(doc.published_at).toLocaleDateString('de-DE')}
)}
{doc.change_note && (
{doc.change_note}
)}
{doc.status === 'draft' && (
<>
onEdit(doc)} title="Bearbeiten">
onPublish(doc)} title="Veröffentlichen">
>
)}
{doc.status === 'published' && (
onArchive(doc)} title="Archivieren">
)}
onRenderedPreview(doc)} title="Gerenderte Vorschau">
onCopy(doc)} title="Als neuen Entwurf kopieren">
{downloading ? '…' : }
onViewAudit(doc)} title="Änderungslog">
)
}
function EditForm({ docType, editDoc, onSaved, onCancel, onShowRenderedPreview }) {
const [title, setTitle] = useState(editDoc ? editDoc.title : docType.defaultTitle)
const [sections, setSections] = useState([])
const [changeNote, setChangeNote] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState(null)
const [loadingDoc, setLoadingDoc] = useState(!!editDoc)
useEffect(() => {
if (editDoc) {
api.getLegalDocument(editDoc.id)
.then(d => {
setTitle(d.title)
setSections(d.content_sections || [])
setChangeNote(d.change_note || '')
})
.catch(e => setError(e.message))
.finally(() => setLoadingDoc(false))
}
}, [editDoc])
const handleSave = async () => {
setSaving(true)
setError(null)
try {
const payload = { title, content_sections: sections, change_note: changeNote || null }
if (editDoc) {
await api.updateLegalDocument(editDoc.id, payload)
} else {
await api.createLegalDocument({ document_type: docType.key, ...payload })
}
onSaved()
} catch (e) {
setError(e.message)
} finally {
setSaving(false)
}
}
if (loadingDoc) return
return (
{editDoc ? 'Entwurf bearbeiten' : 'Neuen Entwurf erstellen'}
{error && (
{error}
)}
Titel *
setTitle(e.target.value)} required />
Abschnitte
Änderungsnotiz (optional)
setChangeNote(e.target.value)}
placeholder="z. B. Erste Version nach juristischer Prüfung" />
{saving ? 'Speichern…' : 'Entwurf speichern'}
onShowRenderedPreview?.({
title,
sections,
metaLine: 'Aktueller Editorstand (nicht automatisch gespeichert)',
})}
style={{ display: 'flex', alignItems: 'center', gap: '0.35rem' }}
>
Vollständige Vorschau
Abbrechen
)
}
function AuditLog({ docId, onClose }) {
const [entries, setEntries] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
api.getLegalDocumentAudit(docId)
.then(setEntries)
.catch(() => setEntries([]))
.finally(() => setLoading(false))
}, [docId])
const ACTION_LABELS = { created: 'Erstellt', updated: 'Bearbeitet', published: 'Veröffentlicht', archived: 'Archiviert' }
return (
Änderungslog
Schließen
{loading ?
: entries.length === 0 ? (
Keine Einträge.
) : entries.map(e => (
{ACTION_LABELS[e.action] || e.action}
{e.previous_status && von {e.previous_status} }
{new Date(e.created_at).toLocaleString('de-DE')}
{e.changed_by_name && von {e.changed_by_name} }
{e.change_note && (
{e.change_note}
)}
))}
)
}
// ─── Main page ───────────────────────────────────────────────────────────────
export default function AdminLegalDocumentsPage() {
const [activeType, setActiveType] = useState(DOC_TYPES[0].key)
const [documents, setDocuments] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [showForm, setShowForm] = useState(false)
const [editDoc, setEditDoc] = useState(null)
const [auditDocId, setAuditDocId] = useState(null)
const [confirmPublish, setConfirmPublish] = useState(null)
const [legalPreview, setLegalPreview] = useState({
open: false,
loading: false,
title: '',
sections: [],
metaLine: '',
})
const activeDocType = DOC_TYPES.find(d => d.key === activeType)
const load = useCallback(() => {
setLoading(true)
setError(null)
api.listLegalDocuments(activeType)
.then(setDocuments)
.catch(e => setError(e.message))
.finally(() => setLoading(false))
}, [activeType])
useEffect(() => {
load()
setShowForm(false)
setEditDoc(null)
setAuditDocId(null)
setConfirmPublish(null)
}, [load])
const handlePublish = (doc) => setConfirmPublish(doc)
const confirmAndPublish = async () => {
if (!confirmPublish) return
try {
await api.publishLegalDocument(confirmPublish.id, null)
setConfirmPublish(null)
load()
} catch (e) { alert('Fehler: ' + e.message) }
}
const handleArchive = async (doc) => {
if (!confirm(`"${doc.title}" archivieren?`)) return
try { await api.archiveLegalDocument(doc.id); load() }
catch (e) { alert('Fehler: ' + e.message) }
}
const handleEdit = (doc) => { setEditDoc(doc); setShowForm(true); setAuditDocId(null) }
const handleViewAudit = (doc) => { setAuditDocId(doc.id); setShowForm(false); setEditDoc(null) }
const handleNew = () => { setEditDoc(null); setShowForm(true); setAuditDocId(null) }
const handleSaved = () => { setShowForm(false); setEditDoc(null); load() }
const handleCopy = async (doc) => {
try { await api.copyLegalDocumentAsDraft(doc.id); load() }
catch (e) { alert('Fehler: ' + e.message) }
}
const closeLegalPreview = () =>
setLegalPreview({ open: false, loading: false, title: '', sections: [], metaLine: '' })
const openLegalPreviewFromEditor = (payload) => {
setLegalPreview({
open: true,
loading: false,
title: payload.title,
sections: payload.sections,
metaLine: payload.metaLine || '',
})
}
const openLegalPreviewFromList = async (doc) => {
setLegalPreview({
open: true,
loading: true,
title: '',
sections: [],
metaLine: 'Laden…',
})
try {
const full = await api.getLegalDocument(doc.id)
setLegalPreview({
open: true,
loading: false,
title: full.title,
sections: full.content_sections || [],
metaLine: `Version ${full.version} · ${STATUS_LABELS[full.status]?.label || full.status}`,
})
} catch (e) {
closeLegalPreview()
alert('Fehler: ' + e.message)
}
}
const handleDownload = async (doc) => {
const full = await api.getLegalDocument(doc.id)
const dateStr = full.published_at
? new Date(full.published_at).toLocaleDateString('de-DE')
: new Date(full.updated_at || full.created_at).toLocaleDateString('de-DE')
const metaLine = `Version ${full.version} | ${PDF_STATUS_META[full.status] || full.status} ${dateStr}`
generateLegalPdf(full, metaLine)
}
const publishedDoc = documents.find(d => d.status === 'published')
return (
Rechtstexte verwalten
Versionierte Rechtstexte erstellen, bearbeiten und veröffentlichen.
Pro Dokumententyp kann immer nur ein Text veröffentlicht sein.
{/* Tab-Leiste */}
{DOC_TYPES.map(dt => (
setActiveType(dt.key)}
style={{ minWidth: '130px' }}
>
{dt.label}
))}
{/* Aktuell veröffentlicht */}
{publishedDoc && (
Aktuell live: {publishedDoc.title} (v{publishedDoc.version}
{publishedDoc.published_at && `, ${new Date(publishedDoc.published_at).toLocaleDateString('de-DE')}`})
)}
{/* Aktionen */}
{error && (
{error}
)}
{/* Bestätigung Veröffentlichen */}
{confirmPublish && (
„{confirmPublish.title}" veröffentlichen?
{publishedDoc && publishedDoc.id !== confirmPublish.id && (
<> Die aktuelle Version ({publishedDoc.title} v{publishedDoc.version}) wird dabei archiviert.>
)}
Ja, veröffentlichen
setConfirmPublish(null)}>Abbrechen
)}
{/* Dokumentenliste */}
{loading ?
: documents.length === 0 ? (
Noch keine Versionen für {activeDocType?.label}. Erstelle einen neuen Entwurf.
) : (
documents.map(doc => (
))
)}
{showForm && (
{ setShowForm(false); setEditDoc(null) }}
onShowRenderedPreview={openLegalPreviewFromEditor}
/>
)}
{auditDocId && (
setAuditDocId(null)} />
)}
)
}