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

const numberedList: BlockDefinition = {
  label: '番号付きリスト',
  icon: 'format_list_numbered',
  description: '番号付きリスト',
  isTextMenu: true,
  aliases: ['ol', 'ordered list'],
  createActions: (cmd, ctx) => ({
    action: (editor) => {
      ctx.recordUsage(cmd);
      editor.chain().focus().toggleOrderedList().run();
      const { $from } = editor.state.selection;
      // カーソル位置から上へ順に探索して `orderedList` を見つける
      for (let { depth } = $from; depth > 0; depth--) {
        const node = $from.node(depth);
        if (node.type.name === 'orderedList') {
          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).splitOrderedList(pos).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('orderedList', { class: cmd.class })
        : editor.isActive('orderedList', { class: null }) || editor.isActive('orderedList', { class: '' });
      // 同じ要素 + class なら disable
      if (isSame) {
        return true;
      }
      // 同じ要素だが class が違う場合 → enable
      if (editor.isActive('orderedList') || editor.isActive('bulletList')) {
        return false;
      }
      // それ以外は通常の can 判定
      return !editor.can().toggleOrderedList();
    },
    isActive: (editor) => editor.isActive('orderedList'),
  }),
};

export default numberedList;
