/**
 * Applies attributes to image carousel modals.
 * @module ImageCarousel
 * @memberof Builtin.Attributes.Components.Modals
 */

import { getModuleByDisplayName } from '@vizality/webpack';
import { patch, unpatch } from '@vizality/patcher';
import { findInTree } from '@vizality/util/react';

export const labels = [ 'Components', 'Modals', 'ImageCarousel' ];

export default builtin => {
  const ModalCarousel = getModuleByDisplayName('componentDispatchSubscriber(ModalCarousel)');
  patch('vz-attributes-modal-image-carousel', ModalCarousel?.prototype, 'render', (_, res) => {
    try {
      const ogRef = res.ref;
      res.ref = elem => {
        const r = ogRef(elem);
        if (elem?._reactInternals) {
          const container = findInTree(elem._reactInternals?.return, el => el?.stateNode?.setAttribute, { walkable: [ 'return' ] });
          container?.stateNode?.parentElement?.setAttribute('vz-modal', 'image-carousel');
        }
        return r;
      };
    } catch (err) {
      return builtin.error(builtin._labels.concat(labels), err);
    }
  });
  return () => unpatch('vz-attributes-modal-image-carousel');
};
