import React from "react";
import { Page } from './_util';
import { useParams } from 'react-router-dom';
import { LegalMarkdown } from '../components/legal-markdown';

export default function LegalPage() {
  const { page } = useParams();
  const [loading, setLoading] = React.useState(true);
  const [title, setTitle] = React.useState('');
  const [body, setBody] = React.useState('');
  const [html, setHtml] = React.useState('');

  React.useEffect(() => {
    if (!page) {
      return;
    }
    const slug = page;
    const controller = new AbortController();

    async function loadLegal() {
      try {
        setLoading(true);
        const res = await fetch(`/api/v1/legal/${encodeURIComponent(slug)}?lang=de`, {
          headers: { 'Cache-Control': 'no-store' },
          signal: controller.signal,
        });
        if (!res.ok) {
          throw new Error('failed');
        }
        const data = await res.json();
        setTitle(data.title || '');
        setBody(data.body_markdown || '');
        setHtml(data.body_html || '');
      } catch (error) {
        if (!controller.signal.aborted) {
          console.error('Failed to load legal page', error);
          setTitle('');
          setBody('');
          setHtml('');
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    loadLegal();
    return () => controller.abort();
  }, [page]);

  const fallbackTitle = page ? `Rechtliches: ${page}` : 'Rechtliche Informationen';

  return (
    <Page title={title || fallbackTitle}>
      {loading ? <p>Laedt...</p> : <LegalMarkdown markdown={body} html={html} />}
    </Page>
  );
}
