import React from "react";
import FsSection from "./FsSection";
import { parseFields } from "../helpers";

const FsSections = ({ fields, ...props }) => {
  const { watch } = props;
  return (
    <>
      {parseFields(fields).map(({ id, innerFields, section_heading, section_text, logic }) => {
        if (logic?.checks) {
          /**
           * logic is an object from Formstack, it controls whether a section will be hidden
           * @logicChecks array that contains an object { field, option }
           * @logicId id of the field that controls the logic
           * @currentValue current value of the field that controls the logic
           * @compareValues array out of the logic values called
           * E.g. "Product Issue 2 Section" using the "Number of Product Issues Field" as the logic controller
           * Section will show if @currentValue equals a value in the @compareValues array [5,4,3,2]
           * the section will hide if the @currentValue = 1
           */
          const logicChecks = logic.checks;
          const logicId = logicChecks[0]?.field;
          const currentValue = watch(`${logicId}`);
          const compareValues = logicChecks.map(({ option }) => option);

          if (compareValues.includes(currentValue)) {
            return (
              <FsSection
                id={id}
                key={id}
                fields={innerFields}
                heading={section_heading}
                text={section_text}
                {...props}
              />
            );
          }
          return null;
        }
        return (
          <FsSection id={id} key={id} fields={innerFields} heading={section_heading} text={section_text} {...props} />
        );
      })}
    </>
  );
};

export default FsSections;
