/**
 * Underline Mark Extension
 * 下划线标记
 */

import type { MarkSpec, Schema, Command, ToolbarItem } from '../../core/types';
import { MarkExtension } from '../../core/Extension';
import { toggleMark } from 'prosemirror-commands';
import { Underline as UnderlineIcon } from 'lucide-react';

export class Underline extends MarkExtension {
  get name(): string {
    return 'underline';
  }

  get schema(): MarkSpec {
    return {
      parseDOM: [
        { tag: 'u' },
        {
          style: 'text-decoration',
          getAttrs: (value: string) => value.includes('underline') && null,
        },
      ],
      toDOM() {
        return ['u', { class: 'editor-underline' }, 0];
      },
    };
  }

  keys(schema: Schema): Record<string, Command> {
    return {
      'Mod-u': toggleMark(schema.marks.underline),
      'Mod-U': toggleMark(schema.marks.underline),
    };
  }

  toolbarItems(schema: Schema): ToolbarItem[] {
    return [
      {
        name: 'underline',
        title: '下划线',
        icon: UnderlineIcon,
        command: toggleMark(schema.marks.underline),
        isActive: (state) => {
          const { from, $from, to, empty } = state.selection;
          if (empty) {
            return !!schema.marks.underline.isInSet(state.storedMarks || $from.marks());
          }
          return state.doc.rangeHasMark(from, to, schema.marks.underline);
        },
        group: 'format',
        priority: 80,
      },
    ];
  }
}
