import DOMPurify from "dompurify";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import { getPageBySlug } from "@modules/content/api/contentApi";

const ALLOWED_TAGS = ["p", "h1", "h2", "h3", "h4", "ul", "ol", "li", "a", "strong", "em", "br", "img"];

export function ContentPage(): JSX.Element {
  const { slug } = useParams();
  const { data, isLoading, isError } = useQuery({
    queryKey: ["content-page", slug],
    queryFn: () => getPageBySlug(slug ?? ""),
    enabled: Boolean(slug)
  });

  if (isLoading) {
    return (
      <main>
        <p>Loading...</p>
      </main>
    );
  }

  if (isError || !data) {
    return (
      <main>
        <h1>Page not found</h1>
      </main>
    );
  }

  const safeHtml = DOMPurify.sanitize(data.body, { ALLOWED_TAGS });

  return (
    <main>
      <h1>{data.title}</h1>
      <article dangerouslySetInnerHTML={{ __html: safeHtml }} />
    </main>
  );
}
