/* eslint-disable react/destructuring-assignment */
import React from 'react';
// import loadable from '@loadable/component';
import Iframe from 'gatsby-core-theme/src/components/atoms/iframe';
import LazyImage from 'gatsby-core-theme/src/hooks/lazy-image';
import { parseContentImageUrl } from 'gatsby-core-theme/src/helpers/strings';
import { parseCss } from 'gatsby-core-theme/src/helpers/css-parser';
import { generatePlaceholderString } from './generators.mjs';
import styles from '../components/molecules/content/content.module.scss';

export default (node, page, translations) => {
  if (node.name === 'iframe') {
    return <Iframe src={node.attribs.src} />;
  }

  if (node.name === 'img') {
    let stylesClass = null;
    const classes = node.attribs.class;
    if (classes?.includes('content-image--float-left')) {
      stylesClass = 'floatLeft';
    } else if (classes?.includes('content-image--float-right')) {
      stylesClass = 'floatRight';
    } else if (classes?.includes('content-image--align-center')) {
      stylesClass = 'alignCenter';
    } else if (classes?.includes('content-image--align-left')) {
      stylesClass = 'alignLeft';
    } else if (classes?.includes('content-image--align-right')) {
      stylesClass = 'alignRight';
    }
    const lazyProps = {
      src: parseContentImageUrl(node.attribs.src),
      width: node.attribs.width && node.attribs.width.replace('px', ''),
      height:
        node.attribs.height &&
        (node.attribs.height === 'auto' ? '298' : node.attribs.height.replace('px', '')),
      style: node.attribs.style ? parseCss(node.attribs.style) : null,
      alt: node.attribs.alt ? node.attribs.alt : '',
      className: styles[stylesClass],
    };

    return <LazyImage {...lazyProps} />;
  }

  if (node.name === 'p') {
    const hasChildImg = node?.children.find((child) => child?.name === 'img');

    if (hasChildImg) {
      hasChildImg.attribs.style = '';
      return hasChildImg;
    }
  }

  if (node.name === 'h1' || node.name === 'h2' || node.name === 'h3') {
    const data = {
      siteName: page?.siteInfo?.site_name,
      pageTitle: page?.title,
      name: page?.relation?.name,
    };
    // check if h2 is empty
    if (node?.children[0]?.data !== undefined)
      node.children[0].data = generatePlaceholderString(node.children[0].data, translations, data);
  }

  return null;
};
