import { Node, mergeAttributes } from '@tiptap/core';

export const CardNode = Node.create({
  name: 'card',

  group: 'block',

  content: 'block+',

  addAttributes() {
    return {
      type: {
        default: null,
        parseHTML: element => element.getAttribute('data-type'),
        renderHTML: attributes => {
          if (!attributes.type) {
            return {};
          }
          return {
            'data-type': attributes.type,
          };
        },
      },
      bg: {
        default: null,
        parseHTML: element => element.getAttribute('data-bg'),
        renderHTML: attributes => {
          if (!attributes.bg) {
            return {};
          }
          return {
            'data-bg': attributes.bg,
          };
        },
      },
    };
  },

  parseHTML() {
    return [
      {
        tag: 'div[data-card]',
      },
    ];
  },

  renderHTML({ HTMLAttributes }) {
    const { type, bg } = HTMLAttributes;
    
    let className = 'card-preview';
    if (type) {
      className += ` card-preview-${type}`;
    }

    const style: any = {};
    if (bg) {
      style.backgroundImage = `url(${bg})`;
      style.backgroundSize = 'cover';
      style.backgroundPosition = 'center';
    }

    return [
      'div',
      mergeAttributes(HTMLAttributes, {
        'data-card': '',
        class: className,
        style: Object.keys(style).length > 0 ? style : undefined,
      }),
      0,
    ];
  },

  addCommands() {
    return {
      setCard: (attributes) => ({ commands }) => {
        return commands.wrapIn(this.name, attributes);
      },
      unsetCard: () => ({ commands }) => {
        return commands.lift(this.name);
      },
    };
  },
});
