"use client";

import { useEffect } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import TextAlign from "@tiptap/extension-text-align"
import Highlight from "@tiptap/extension-highlight"
import StarterKit from "@tiptap/starter-kit";
import MenuBar from "./menuBar";

interface TiptapProps {
  content: string;
  onUpdate: (content: string) => void;
}

const Tiptap = ({ content, onUpdate }: TiptapProps) => {
  const editor = useEditor({
    extensions: [
        StarterKit.configure({
          bulletList: {
            HTMLAttributes: {
              class: "list-disc ml-3",
            },
          },
          orderedList: {
            HTMLAttributes: {
              class: "list-decimal ml-3",
            },
          },
        }),
        TextAlign.configure({
          types: ["heading", "paragraph"],
        }),
        Highlight,
      ],
      content: content,
      editorProps: {
        attributes: {
          class: "min-h-[156px] border rounded-md bg-slate-50 py-2 px-3",
        },
      },
    onUpdate: ({ editor }) => {
      onUpdate(editor.getHTML());
    },
    immediatelyRender: false
  });

  // ✅ Update editor content when `content` changes
  useEffect(() => {
    if (editor && content !== editor.getHTML()) {
      editor.commands.setContent(content);
    }
  }, [content, editor]);

  if (!editor) return <p>Loading editor...</p>; // ✅ Prevents errors

  return (
    <div>
      <MenuBar editor={editor} />
      <EditorContent editor={editor} />
    </div>
  )
};

export default Tiptap;
