import type { BlockDefinition } from '../../types';

const paragraph: BlockDefinition = {
  label: '段落',
  icon: 'title',
  description: '段落',
  isTextMenu: true,
  aliases: ['p', 'paragraph', 'text'],
  createActions: (cmd, ctx) => ({
    action: (editor) => {
      ctx.recordUsage(cmd);
      editor.chain().focus().setParagraph().run();
      const { $from } = editor.state.selection;
      const pos = $from.before($from.depth);
      editor.chain().focus().setBlockAttrs(pos, { class: cmd.class }).run();
    },
    convert: (editor, pos) => {
      const chain = editor.chain();
      chain.setNodeSelection(pos);
      chain.removeList(pos).removeBlockquote(pos).setParagraph().run();
      const { $from } = editor.state.selection;
      const newPos = $from.before(1);
      editor.chain().focus().setBlockAttrs(newPos, { class: cmd.class }).run();
    },
    isDisabled: (editor) => {
      const isSame = cmd.class
        ? editor.isActive('paragraph', { class: cmd.class })
        : editor.isActive('paragraph', { class: null }) || editor.isActive('paragraph', { class: '' });
      // 同じ要素 + class なら disable
      if (isSame) {
        return true;
      }
      // 同じ要素だが class が違う場合 → enable
      if (editor.isActive('paragraph')) {
        return false;
      }
      // それ以外は通常の can 判定
      return !editor.can().setParagraph();
    },
    isActive: (editor) => {
      if (cmd.class) {
        return editor.isActive('paragraph', { class: cmd.class });
      }
      return editor.isActive('paragraph', { class: null }) || editor.isActive('paragraph', { class: '' });
    },
  }),
};

export default paragraph;
