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

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

export default codeBlock;
