import React, { useContext } from 'react';

const { ModuleGroups } = window?.divi?.module ?? {};
const { moduleContext } = window?.divi?.contextLibrary ?? {};
const { getAttrValue } = window?.divi?.moduleUtils ?? {};
const { useSelect } = window?.vendor?.wp?.data ?? {};

/**
 * Customize the auto-generated Content settings so the "Gallery Media" select
 * is hidden while "Current Page" is enabled (it is ignored in that mode).
 *
 * Divi 5 does not support disabling a select field; the supported conditional
 * mechanism is a `visible` resolver function set on the field configuration
 * (this is the same approach core modules use for context-dependent fields).
 */
export const GallerySettingsContent = ({ groupConfiguration }) => {
  const { moduleId } = useContext(moduleContext);

  const currentPageAttr = useSelect(
    (select) => select('divi/edit-post').getModuleAttr(moduleId, 'galleryCurrentPage.innerContent'),
    [moduleId],
  );

  const fields = groupConfiguration?.contentGallery?.component?.props?.fields;

  // eslint-disable-next-line no-underscore-dangle
  window.__lknscfDbg = (window.__lknscfDbg || []).concat([{
    groups: Object.keys(groupConfiguration || {}),
    fieldKeys: fields ? Object.keys(fields) : null,
    attrNames: fields ? Object.values(fields).map((f) => f?.attrName) : null,
    attr: currentPageAttr,
  }]);

  if (fields) {
    const fieldId = Object.keys(fields).find(
      (key) => fields[key]?.attrName === 'galleryField.innerContent',
    );

    if (fieldId) {
      const visibleResolver = (context = {}) => {
        const value = getAttrValue({
          attr: currentPageAttr,
          baseBreakpoint: context.baseBreakpoint,
          breakpoint: context.breakpoint,
          breakpointNames: context.breakpointNames,
          state: context.state,
          defaultValue: 'off',
        });

        return value !== 'on';
      };

      fields[fieldId].visible = visibleResolver;
    }
  }

  return <ModuleGroups groups={groupConfiguration} />;
};
