import { EditorState } from "prosemirror-state"
import { EditorView } from "prosemirror-view"
import { describe, expect, test } from "vitest"
import { createMarkdownDecorationsPlugin } from "@/composables/useMarkdownDecorations"
import { schema } from "@/lib/schema"

const ITERATIONS = 50

const SAMPLES: Record<string, string> = {
  plain: "hello world",
  bold: "this is **bold** and **more bold** text",
  mixed:
    "**bold** *italic* `code` ~~strike~~ ^^highlight^^ and [[Page Ref]] ((block-id)) #tag",
  kitchenSink: [
    "# Documentation\n\n",
    "This is a **paragraph** with *multiple* `inline` ~~styles~~.\n\n",
    "## Features\n\n",
    "> [!TIP] Use callouts for **important** notes\n\n",
    "TODO Add [[Page Reference]] and ((block-123)) support\n\n",
    "priority:: high\nauthor:: John\n",
  ].join(""),
}

function makeDoc(content: string) {
  const textNode = content ? schema.text(content) : undefined
  const para = textNode
    ? schema.node("paragraph", {}, [textNode])
    : schema.node("paragraph")
  return schema.node("doc", {}, [para])
}

describe("per-keystroke pipeline budget", () => {
  for (const [name, content] of Object.entries(SAMPLES)) {
    test(`${name} averages under 16ms`, () => {
      const { plugin } = createMarkdownDecorationsPlugin()
      const state = EditorState.create({
        doc: makeDoc(content),
        schema,
        plugins: [plugin],
      })
      const view = new EditorView(document.createElement("div"), { state })

      const start = performance.now()
      for (let i = 0; i < ITERATIONS; i++) {
        const pos = view.state.doc.content.size
        view.dispatch(view.state.tr.insertText("x", pos))
      }
      const avg = (performance.now() - start) / ITERATIONS

      view.destroy()

      expect(avg).toBeLessThan(16)
    })
  }
})
