// Comments in English
"use client";

import React, { useEffect, useRef } from "react";
import { EditorView, basicSetup } from "codemirror";
import { keymap } from "@codemirror/view";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data"; // language detection for fenced blocks
import { oneDark } from "@codemirror/theme-one-dark";
import { syntaxHighlighting, HighlightStyle } from "@codemirror/language";
import { useMantineColorScheme } from "@mantine/core";
import { Prec } from "@codemirror/state";

import { headingHighlight, headingLineClasses, headingLineTheme } from "./extensions/headings";
import { codeBlockLineNumbers, codeBlockCopyButtons, fenceKeydownFallback } from "./extensions/fencedCode";
import { liveLinkTheme, liveLinkHandlers, liveLinkKeybind } from "./extensions/liveLinks";
import { hideMarkdownDelimiters } from "./extensions/emphasis"; // includes emphasis reveal & hiding
import { myMarkdownKeymap } from "./keymap";

export type MarkdownEditorProps = {
  mode?: "live" | "source"; // live = Live Preview, source = Source Mode
};

export default function MarkdownEditor({ mode = "live" }: MarkdownEditorProps) {
  const editorRef = useRef<HTMLDivElement | null>(null);
  const { colorScheme } = useMantineColorScheme();

  useEffect(() => {
    if (!editorRef.current) return;

    const extensions = [
      basicSetup,
      markdown({ base: markdownLanguage, codeLanguages: languages }),
      codeBlockLineNumbers(),
      codeBlockCopyButtons(),
      colorScheme === "dark" ? oneDark : EditorView.theme({}, { dark: false }),
  Prec.highest(keymap.of(myMarkdownKeymap)), // keybindings
      fenceKeydownFallback(),
    ];

    if (mode === "live") {
      // Visual Live Preview enhancements
      extensions.push(
        syntaxHighlighting(headingHighlight as HighlightStyle),
        headingLineClasses,
        headingLineTheme,
        hideMarkdownDelimiters(), // hide emphasis marks, headers, and link delimiters when not editing them
        liveLinkTheme,
        liveLinkHandlers(),
  Prec.highest(keymap.of([liveLinkKeybind]))
      );
    }

    const view = new EditorView({
      doc: "# Hello Markdown\n\n## Subtítulo\n\n```js\nconsole.log('Hola');\n```\n\n\n---\n\n\n[Google](https://google.com)\n\n\n- [x] Tarea completada",
      extensions,
      parent: editorRef.current,
    });

    return () => view.destroy();
  }, [colorScheme, mode]);

  return (
    <div ref={editorRef} style={{ borderRadius: "8px" }} />
  );
}
