import { fetchPage } from '@/lib/api';
import { formatRichText } from '@/lib/format-rich-text';

/**
 * Renders the CMS template content (if a published page exists for the slug)
 * as an intro/content block. Returns null when no CMS page is configured so
 * pages keep their default layout.
 */
export async function CmsBlock({
  slug,
  variant = 'intro',
}: {
  slug: string;
  variant?: 'intro' | 'section';
}) {
  const page = await fetchPage(slug).catch(() => null);
  if (!page?.body) return null;

  if (variant === 'section') {
    return (
      <section className="py-12 bg-white">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          {page.title && (
            <h2
              className="text-2xl font-bold text-gray-900 mb-4 text-center"
              style={{ fontFamily: 'var(--font-heading)' }}
            >
              {page.title}
            </h2>
          )}
          <div
            className="rich-text text-gray-600 leading-relaxed"
            dangerouslySetInnerHTML={{ __html: formatRichText(page.body) }}
          />
        </div>
      </section>
    );
  }

  return (
    <div
      className="rich-text mt-3 mb-6 max-w-3xl text-gray-600 leading-relaxed"
      dangerouslySetInnerHTML={{ __html: formatRichText(page.body) }}
    />
  );
}
