/**
 * Applies attributes to user profile modals.
 * @module User
 * @memberof Builtin.Attributes.Components.Modals
 */

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

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

export default builtin => {
  (async () => {
    const UserProfile = await waitUntil(() => getModule(m => m.default?.displayName === 'UserProfileModal'));
    patch('vz-attributes-modal-user', UserProfile, 'default', ([ props ], res) => {
      try {
        res.ref = elem => {
          if (elem?._reactInternals) {
            const container = findInTree(elem._reactInternals.return, el => el.stateNode?.setAttribute, { walkable: [ 'return' ] });
            container?.stateNode?.children[0]?.setAttribute('vz-user-id', props?.user?.id);
            container?.stateNode?.children[0]?.setAttribute('vz-guild-id', props?.guildId);
            container?.stateNode?.parentElement?.setAttribute('vz-modal', 'user');
          }
        };
      } catch (err) {
        return builtin.error(builtin._labels.concat(labels), err);
      }
    });
  })();
  return () => unpatch('vz-attributes-modal-user');
};
