"use server";

import Image from "next/image";
import parse from "html-react-parser";
import { headers } from "next/headers";

const RichContent = async ({ html }) => {
  const headersList = await headers();
  const host = headersList.get("host");
  const protocol = headersList.get("x-forwarded-proto") || "http";
  const origin = `${protocol}://${host}`;

  const options = {
    replace: (domNode) => {
      if (domNode.name === "img") {
        const { src, alt, width, height } = domNode.attribs;
        return (
          <Image
            src={`${origin}/api${src}`} // replace with your API endpoint
            alt={alt || ""}
            width={width ? parseInt(width) : 800}
            height={height ? parseInt(height) : 600}
            // size for optimization
            sizes="(max-width: 768px) 100vw, 800px"
            style={{ height: "auto" }}
          />
        );
      }
    },
  };

  return <>{parse(html, { ...options, trim: true })}</>;
};

export default RichContent;
