"use client";

import { useState, useEffect } from "react";
import { MDXRemote } from "next-mdx-remote/rsc";
import { getProseClasses } from "./ProseConfig";
import Callout from "./Callout";
import CodeBlock from "./CodeBlock";
import DataTable from "./DataTable";
import SectionDivider from "./SectionDivider";
import StatCard from "./StatCard";
import InfoBox from "./InfoBox";

type TextSize = "small" | "medium" | "large";

interface DynamicProseContentProps {
  content: string;
}

export default function DynamicProseContent({
  content,
}: DynamicProseContentProps) {
  const [textSize, setTextSize] = useState<TextSize>("medium");

  // Load saved preference from localStorage
  useEffect(() => {
    const saved = localStorage.getItem("blog-text-size") as TextSize;
    if (saved && ["small", "medium", "large"].includes(saved)) {
      setTextSize(saved);
    }

    // Listen for text size changes from the control
    const handleTextSizeChange = (event: CustomEvent<TextSize>) => {
      setTextSize(event.detail);
    };

    window.addEventListener("textSizeChange" as any, handleTextSizeChange);
    return () =>
      window.removeEventListener("textSizeChange" as any, handleTextSizeChange);
  }, []);

  return (
    <div className={getProseClasses(textSize)}>
      <MDXRemote
        source={content}
        options={{
          mdxOptions: {
            remarkPlugins: [require("remark-gfm")],
            rehypePlugins: [
              [
                require("rehype-raw"),
                { passThrough: ["mdxJsxFlowElement", "mdxJsxTextElement"] },
              ],
            ],
          },
        }}
        components={{
          Callout,
          CodeBlock,
          DataTable,
          SectionDivider,
          StatCard,
          InfoBox,
        }}
      />
    </div>
  );
}
