"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";
import TextSizeControl from "./TextSizeControl";

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

interface BlogArticleContentProps {
  content: string;
  lang: "ar" | "en";
  showTextSizeControl?: boolean;
}

export default function BlogArticleContent({
  content,
  lang,
  showTextSizeControl = true,
}: BlogArticleContentProps) {
  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);
    }
  }, []);

  const handleSizeChange = (size: TextSize) => {
    setTextSize(size);
  };

  return (
    <div className="flex flex-col lg:flex-row gap-12">
      {/* Main Article Content */}
      <div className="flex-1 min-w-0 max-w-3xl mx-auto lg:mx-0">
        <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>
      </div>

      {/* Sidebar with Text Size Control */}
      {showTextSizeControl && (
        <aside className="w-full lg:w-80 flex-shrink-0">
          <TextSizeControl lang={lang} onSizeChange={handleSizeChange} />
        </aside>
      )}
    </div>
  );
}
