// Comments in English
import { HighlightStyle } from "@codemirror/language";
import { tags } from "@lezer/highlight";
import { Decoration, DecorationSet, EditorView, ViewPlugin } from "@codemirror/view";
import type { Range } from "@codemirror/state";
import { RangeSetBuilder } from "@codemirror/state";
import { syntaxTree } from "@codemirror/language";

export const headingHighlight = HighlightStyle.define([
  { tag: tags.heading1, fontSize: "1.8rem", fontWeight: "700" },
  { tag: tags.heading2, fontSize: "1.5rem", fontWeight: "700" },
  { tag: tags.heading3, fontSize: "1.3rem", fontWeight: "600" },
  { tag: tags.heading4, fontSize: "1.1rem", fontWeight: "600" },
  { tag: tags.heading5, fontSize: "1rem",  fontWeight: "600" },
  { tag: tags.heading6, fontSize: "0.9rem", fontWeight: "600" },
]);

export const headingLineClasses = ViewPlugin.fromClass(
  class {
    decorations: DecorationSet;
    constructor(view: EditorView) { this.decorations = this.compute(view); }
    update(update: any) {
      if (update.docChanged || update.viewportChanged) this.decorations = this.compute(update.view);
    }
    compute(view: EditorView) {
      const decos: Range<Decoration>[] = [];
      const tree = syntaxTree(view.state);
      const { from, to } = view.viewport;
      tree.iterate({
        from, to,
        enter: (node) => {
          if (node.name === "ATXHeading") {
            const line = view.state.doc.lineAt(node.from);
            const match = /^#{1,6}\s/.exec(line.text);
            const level = match ? match[0].trim().length : 1;
            const cls = level === 1 ? "cm-h1-line" :
                        level === 2 ? "cm-h2-line" :
                        level === 3 ? "cm-h3-line" :
                        level === 4 ? "cm-h4-line" :
                        level === 5 ? "cm-h5-line" :
                        level === 6 ? "cm-h6-line" : null;
            if (cls) {
              decos.push(Decoration.line({ attributes: { class: cls } }).range(line.from, line.from));
            }
          }
        }
      });
      return Decoration.set(decos, true);
    }
  },
  { decorations: (v: any) => v.decorations }
);

export const headingLineTheme = EditorView.theme({
  ".cm-h1-line": { lineHeight: "2.4rem", paddingTop: "0.35rem", paddingBottom: "0.15rem" },
  ".cm-h2-line": { lineHeight: "2.0rem", paddingTop: "0.25rem", paddingBottom: "0.1rem" },
  ".cm-h3-line": { lineHeight: "1.8rem", paddingTop: "0.2rem",  paddingBottom: "0.1rem" },
  ".cm-h4-line": { lineHeight: "1.6rem", paddingTop: "0.15rem", paddingBottom: "0.1rem" },
  ".cm-h5-line": { lineHeight: "1.4rem", paddingTop: "0.1rem",  paddingBottom: "0.05rem" },
  ".cm-h6-line": { lineHeight: "1.2rem", paddingTop: "0.05rem", paddingBottom: "0.05rem" },
  ".cm-strong": { fontWeight: "bold" },
  ".cm-emphasis": { fontStyle: "italic" },
  ".cm-link": { textDecoration: "underline" },
  ".cm-strikethrough": { textDecoration: "line-through" },
});
