/**
 * Bold Mark Extension
 * 粗体标记
 */

import type { MarkSpec, Schema, Command, ToolbarItem, InputRule } from '../../core/types';
import { MarkExtension } from '../../core/Extension';
import { toggleMark } from 'prosemirror-commands';
import { markInputRule } from '../utils/markInputRule';
import { Bold as BoldIcon } from 'lucide-react';

export class Bold extends MarkExtension {
  get name(): string {
    return 'bold';
  }

  get schema(): MarkSpec {
    return {
      parseDOM: [
        { tag: 'strong' },
        { tag: 'b', getAttrs: (node: HTMLElement) => node.style.fontWeight !== 'normal' && null },
        {
          style: 'font-weight',
          getAttrs: (value: string) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null,
        },
      ],
      toDOM() {
        return ['strong', { class: 'editor-bold' }, 0];
      },
    };
  }

  inputRules(schema: Schema): InputRule[] {
    return [
      // **text** -> bold
      markInputRule(/\*\*([^*]+)\*\*$/, schema.marks.bold),
      // __text__ -> bold
      markInputRule(/__([^_]+)__$/, schema.marks.bold),
    ];
  }

  keys(schema: Schema): Record<string, Command> {
    return {
      'Mod-b': toggleMark(schema.marks.bold),
      'Mod-B': toggleMark(schema.marks.bold),
    };
  }

  toolbarItems(schema: Schema): ToolbarItem[] {
    return [
      {
        name: 'bold',
        title: '粗体',
        icon: BoldIcon,
        command: toggleMark(schema.marks.bold),
        isActive: (state) => {
          const { from, $from, to, empty } = state.selection;
          if (empty) {
            return !!schema.marks.bold.isInSet(state.storedMarks || $from.marks());
          }
          return state.doc.rangeHasMark(from, to, schema.marks.bold);
        },
        group: 'format',
        priority: 100,
      },
    ];
  }
}
