"use client"

import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"
import { useTranslations } from "next-intl"

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    blank: {
      /** 插入填空占位(下划线空) */
      insertBlank: () => ReturnType
    }
  }
}

const BlankView = ({ selected }: NodeViewProps) => {
  const t = useTranslations("examHomework")
  return (
    <NodeViewWrapper as="span" className="inline-block align-baseline">
      <span
        data-blank="true"
        className="mx-1 inline-block border-b border-current align-baseline"
        style={{
          minWidth: "80px",
          height: "1.2em",
          display: "inline-block",
          boxShadow: selected ? "0 0 0 2px rgb(var(--primary) / 0.4))" : undefined,
        }}
        contentEditable={false}
        aria-label={t("exam.editorExtensions.blank.ariaLabel")}
      />
    </NodeViewWrapper>
  )
}

/**
 * 填空占位节点 —— 原子节点,渲染为下划线空。
 * 用于看拼音写词语、填反义词、补充词语、古诗词默写等多空填空题。
 */
export const BlankNode = Node.create({
  name: "blank",
  group: "inline",
  inline: true,
  atom: true,
  selectable: true,
  parseHTML: () => [{ tag: "span[data-blank]" }],
  renderHTML: ({ HTMLAttributes }) => [
    "span",
    mergeAttributes(HTMLAttributes, { "data-blank": "true" }),
  ],
  addNodeView() {
    return ReactNodeViewRenderer(BlankView)
  },
  addCommands() {
    return {
      insertBlank:
        () =>
        ({ commands }) =>
          commands.insertContent({ type: "blank" }),
    }
  },
})
