(function (wp) {
  const { registerBlockType } = wp.blocks;
  const { InspectorControls, MediaUpload, MediaUploadCheck, useBlockProps } = wp.blockEditor;
  const { PanelBody, TextControl, Button, SelectControl } = wp.components;

  const NETWORK_OPTIONS = [
    { label: "None", value: "" },
    { label: "Instagram", value: "instagram" },
    { label: "LinkedIn", value: "linkedin" },
    { label: "Facebook", value: "facebook" },
    { label: "X (Twitter)", value: "x" },
    { label: "Website", value: "website" },
  ];

  const SOCIAL_SLOTS = 3;
  const MAX_MEMBERS = 12;
  const EMPTY_SOCIALS = Array.from({ length: SOCIAL_SLOTS }, () => ({ network: "", url: "" }));

  const createEmptyMember = () => ({
    name: "",
    role: "",
    imageUrl: "",
    imageAlt: "",
    socials: EMPTY_SOCIALS.map((item) => Object.assign({}, item)),
  });

  registerBlockType("fjord/about-team", {
    edit: (props) => {
      const { attributes, setAttributes } = props;
      const blockProps = useBlockProps({ className: "fjord-about-team" });
      const members = Array.isArray(attributes.members) ? attributes.members : [];

      const updateMember = (index, updates) => {
        const next = members.map((member, i) => {
          if (i !== index) {
            return member;
          }
          return Object.assign({}, member, updates);
        });
        setAttributes({ members: next });
      };

      const addMember = () => {
        if (members.length >= MAX_MEMBERS) {
          return;
        }
        setAttributes({ members: members.concat([createEmptyMember()]) });
      };

      const removeMember = (index) => {
        if (members.length <= 1) {
          return;
        }
        const next = members.filter((_, i) => i !== index);
        setAttributes({ members: next });
      };

      const updateSocial = (memberIndex, socialIndex, updates) => {
        const next = members.map((member, i) => {
          if (i !== memberIndex) {
            return member;
          }
          const socials = Array.isArray(member.socials) ? member.socials.slice() : [];
          while (socials.length < SOCIAL_SLOTS) {
            socials.push({ network: "", url: "" });
          }
          socials[socialIndex] = Object.assign({}, socials[socialIndex], updates);
          return Object.assign({}, member, { socials });
        });
        setAttributes({ members: next });
      };

      const memberPanels = members.map((member, index) => {
        const socials = Array.isArray(member.socials) ? member.socials.slice() : [];
        while (socials.length < SOCIAL_SLOTS) {
          socials.push({ network: "", url: "" });
        }

        return wp.element.createElement(
          PanelBody,
          { title: "Member " + (index + 1), initialOpen: index === 0 },
          wp.element.createElement(TextControl, {
            label: "Name",
            value: member.name || "",
            onChange: (value) => updateMember(index, { name: value }),
          }),
          wp.element.createElement(TextControl, {
            label: "Role",
            value: member.role || "",
            onChange: (value) => updateMember(index, { role: value }),
          }),
          wp.element.createElement(
            MediaUploadCheck,
            null,
            wp.element.createElement(MediaUpload, {
              onSelect: (media) => updateMember(index, { imageUrl: media?.url || "" }),
              allowedTypes: ["image"],
              value: member.imageUrl,
              render: ({ open }) =>
                wp.element.createElement(
                  Button,
                  { onClick: open, variant: "secondary" },
                  member.imageUrl ? "Change image" : "Select image"
                ),
            })
          ),
          member.imageUrl
            ? wp.element.createElement(
                "div",
                { style: { marginTop: "8px" } },
                wp.element.createElement("img", {
                  src: member.imageUrl,
                  style: { width: "100%", borderRadius: "6px" },
                  alt: "",
                })
              )
            : null,
          wp.element.createElement(TextControl, {
            label: "Image alt",
            value: member.imageAlt || "",
            onChange: (value) => updateMember(index, { imageAlt: value }),
          }),
          wp.element.createElement("p", { style: { marginTop: "12px", fontWeight: "600" } }, "Social links"),
          socials.map((social, socialIndex) => {
            return wp.element.createElement(
              "div",
              { key: "social-" + socialIndex, style: { marginBottom: "12px" } },
              wp.element.createElement(SelectControl, {
                label: "Network " + (socialIndex + 1),
                value: social.network || "",
                options: NETWORK_OPTIONS,
                onChange: (value) => updateSocial(index, socialIndex, { network: value }),
              }),
              wp.element.createElement(TextControl, {
                label: "URL",
                value: social.url || "",
                onChange: (value) => updateSocial(index, socialIndex, { url: value }),
                placeholder: "https://",
              })
            );
          }),
          wp.element.createElement(
            Button,
            {
              onClick: () => removeMember(index),
              variant: "secondary",
              isDestructive: true,
              disabled: members.length <= 1,
            },
            "Remove member"
          )
        );
      });

      return wp.element.createElement(
        wp.element.Fragment,
        null,
        wp.element.createElement(
          InspectorControls,
          null,
          wp.element.createElement(
            PanelBody,
            { title: "Team", initialOpen: true },
            wp.element.createElement(
              Button,
              { onClick: addMember, variant: "primary", disabled: members.length >= MAX_MEMBERS },
              "Add member"
            ),
            wp.element.createElement(
              "p",
              { style: { marginTop: "8px", color: "rgba(14,16,17,0.6)" } },
              "Members: " + members.length + " / " + MAX_MEMBERS
            )
          ),
          memberPanels
        ),
        wp.element.createElement(
          "div",
          blockProps,
          wp.element.createElement(
            "div",
            {
              style: {
                border: "1px dashed rgba(14,16,17,0.25)",
                borderRadius: "12px",
                padding: "24px",
                textAlign: "center",
                color: "rgba(14,16,17,0.6)",
                fontSize: "13px",
              },
            },
            "About team renders on the front-end."
          )
        )
      );
    },
    save: () => null,
  });
})(window.wp);
