"use client";

import { useRef } from "react";
import "@fontsource-variable/fira-code";
import { createHighlighter } from "shiki";
import type { editor } from "monaco-editor";
import { shikiToMonaco } from "@shikijs/monaco";
import { useCodeEditorStore } from "@/store/codeEditorStore";
import MonacoEditor, { type Monaco } from "@monaco-editor/react";

export function CodeEditor() {
  const monacoRef = useRef<Monaco | null>(null);
  const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
  const { lang, theme, value, isLigature } = useCodeEditorStore();
  return (
    <MonacoEditor
      language={lang}
      theme="vs-dark"
      options={{
        minimap: { enabled: false },
        fontSize: 14,
        fontFamily: "Fira Code Variable, monospace",
        tabSize: 4,
        showFoldingControls: "always",
        fontLigatures: isLigature,
        automaticLayout: true,
      }}
      value={value}
      onMount={(editor, monaco) => {
        editorRef.current = editor;
        monacoRef.current = monaco;
        void (async () => {
          const ADDITIONAL_LANGUAGES = [
            "c",
            "java",
          ] as const satisfies Parameters<typeof createHighlighter>[0]["langs"];

          for (const lang of ADDITIONAL_LANGUAGES) {
            monacoRef.current?.languages.register({ id: lang });
          }

          const highlighter = await createHighlighter({
            themes: [theme],
            langs: ADDITIONAL_LANGUAGES,
          });

          shikiToMonaco(highlighter, monacoRef.current);
        })();
      }}
    />
  );
}
