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

const blockquote: BlockDefinition = {
  label: '引用',
  icon: 'format_quote',
  description: '引用',
  isTextMenu: false,
  aliases: ['quote'],
  createActions: (cmd, ctx) => ({
    action: (editor) => {
      ctx.recordUsage(cmd);
      editor.chain().focus().setBlockquote().run();
      const { $from } = editor.state.selection;
      // カーソル位置から上へ順に探索して `blockquote` を見つける
      for (let { depth } = $from; depth > 0; depth--) {
        const node = $from.node(depth);
        if (node.type.name === 'blockquote') {
          const pos = $from.before(depth);
          editor.chain().focus().setBlockAttrs(pos, { class: cmd.class }).run();
          break;
        }
      }
    },
    convert: (editor, pos) => {
      const chain = editor.chain();
      chain.setNodeSelection(pos);
      chain.setBlockquote().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('blockquote', { class: cmd.class })
        : editor.isActive('blockquote', { class: null }) || editor.isActive('blockquote', { class: '' });
      // 同じ要素 + class なら disable
      if (isSame) {
        return true;
      }
      // 同じ要素だが class が違う場合 → enable
      if (editor.isActive('blockquote')) {
        return false;
      }
      // それ以外は通常の can 判定
      return true;
    },
    isActive: (editor) => editor.isActive('blockquote'),
  }),
};

export default blockquote;
