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

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

export default bulletList;
