(function (wp) {
  const { registerBlockType } = wp.blocks;
  const { Fragment } = wp.element;
  const { PanelBody, TextControl, TextareaControl, Button, ToggleControl } = wp.components;
  const blockEditor = wp.blockEditor || wp.editor;
  const InspectorControls = blockEditor ? blockEditor.InspectorControls : null;
  const PanelColorSettings =
    (blockEditor && blockEditor.PanelColorSettings) ||
    (wp.components && wp.components.PanelColorSettings) ||
    null;
  const useBlockProps =
    blockEditor && blockEditor.useBlockProps
      ? blockEditor.useBlockProps
      : function (props) {
          return props || {};
        };

  const defaultSections = [
    {
      title: "Shipping & Delivery",
      slug: "shipping",
      enabled: true,
      required: true,
      description: "",
      questions: [
        {
          question: "How long does shipping take?",
          answer: "Shipping typically takes 5-7 business days for domestic orders. International delivery times may vary.",
        },
        {
          question: "Do you ship internationally?",
          answer: "Yes. We ship to most countries—international transit times depend on the destination.",
        },
      ],
    },
    {
      title: "Returns & Exchanges",
      slug: "returns",
      enabled: true,
      required: false,
      description: "",
      questions: [
        {
          question: "What is your return policy?",
          answer: "You can return items in their original condition within 30 days of delivery for a refund or exchange.",
        },
        {
          question: "How do I initiate a return or exchange?",
          answer: "Use the return portal linked in your order confirmation to start a request.",
        },
      ],
    },
    {
      title: "Orders & Payments",
      slug: "orders",
      enabled: true,
      required: false,
      description: "",
      questions: [
        {
          question: "What payment methods do you accept?",
          answer: "We accept major credit cards, PayPal, and other secure payment options at checkout.",
        },
        {
          question: "How can I track my order?",
          answer: "After shipment you receive a tracking number via email.",
        },
      ],
    },
  ];

  const normalizeSections = (sections) => {
    if (!Array.isArray(sections) || sections.length === 0) {
      return defaultSections;
    }
      return sections.map((section, index) => {
        const base = defaultSections[index] || {};
        return {
          ...base,
          ...section,
          enabled: section.enabled === undefined ? true : section.enabled,
          required: section.required || base.required || false,
          description: section.description || base.description || "",
          questions: Array.isArray(section.questions) ? section.questions : base.questions || [],
        };
      });
    };

  const updateSectionField = (sections, sectionIndex, field, value) => {
    return sections.map((section, index) => {
      if (index !== sectionIndex) {
        return section;
      }
      return {
        ...section,
        [field]: value,
      };
    });
  };

  const updateQuestionField = (sections, sectionIndex, questionIndex, field, value) => {
    return sections.map((section, index) => {
      if (index !== sectionIndex) {
        return section;
      }
      const questions = Array.isArray(section.questions) ? section.questions : [];
      const updated = questions.map((question, qIndex) => {
        if (qIndex !== questionIndex) {
          return question;
        }
        return {
          ...question,
          [field]: value,
        };
      });
      return {
        ...section,
        questions: updated,
      };
    });
  };

  const addQuestion = (sections, sectionIndex) => {
    return sections.map((section, index) => {
      if (index !== sectionIndex) {
        return section;
      }
      const questions = Array.isArray(section.questions) ? section.questions : [];
      return {
        ...section,
        questions: [
          ...questions,
          {
            question: "Nueva pregunta",
            answer: "Nueva respuesta",
          },
        ],
      };
    });
  };

  const removeQuestion = (sections, sectionIndex, questionIndex) => {
    return sections.map((section, index) => {
      if (index !== sectionIndex) {
        return section;
      }
      const questions = Array.isArray(section.questions) ? section.questions : [];
      return {
        ...section,
        questions: questions.filter((_, qIndex) => qIndex !== questionIndex),
      };
    });
  };

  registerBlockType("fjord/faq-pills", {
    edit: (props) => {
      const { attributes, setAttributes, className } = props;
      const { sections: rawSections = [], backgroundColor, textColor, capsuleColor } = attributes;
      const sections = normalizeSections(rawSections);
      const blockProps = useBlockProps({
        className: [className, "fjord-faq-bars-preview"].filter(Boolean).join(" "),
        style: {
          backgroundColor: backgroundColor,
          color: textColor,
          padding: "24px",
          borderRadius: "20px",
          "--faq-capsule-bg": capsuleColor,
        },
      });

      const handleSectionChange = (index, field, value) => {
        setAttributes({ sections: updateSectionField(sections, index, field, value) });
      };

      const visibleSections = sections.filter((section) => section.required || section.enabled);

      return wp.element.createElement(
        Fragment,
        null,
        InspectorControls &&
          wp.element.createElement(
            InspectorControls,
            null,
            sections.map((section, index) =>
              wp.element.createElement(
                PanelBody,
                {
                  title: section.title || "Sección " + (index + 1),
                  initialOpen: index === 0,
                  key: "section-panel-" + index,
                },
                wp.element.createElement(TextControl, {
                  label: "Título",
                  value: section.title,
                  onChange: (value) => handleSectionChange(index, "title", value),
                }),
                wp.element.createElement(TextareaControl, {
                  label: "Descripción opcional",
                  value: section.description || "",
                  onChange: (value) => handleSectionChange(index, "description", value),
                }),
                section.required
                  ? wp.element.createElement(
                      "p",
                      { style: { fontSize: "12px", marginBottom: "8px", fontWeight: "600" } },
                      "Esta sección siempre se muestra."
                    )
                  : wp.element.createElement(ToggleControl, {
                      label: section.enabled ? "Sección activada" : "Sección desactivada",
                      checked: section.enabled,
                      onChange: (value) => setAttributes({ sections: updateSectionField(sections, index, "enabled", value) }),
                    }),
                wp.element.createElement(
                  "div",
                  { style: { marginTop: "12px" } },
                  (Array.isArray(section.questions) ? section.questions : []).map((question, qIndex) =>
                    wp.element.createElement(
                      "div",
                      {
                        key: "question-" + qIndex,
                        style: {
                          border: "1px solid rgba(0,0,0,0.1)",
                          borderRadius: "10px",
                          padding: "10px",
                          marginBottom: "8px",
                          background: "#fff",
                        },
                      },
                      wp.element.createElement(TextControl, {
                        label: "Pregunta",
                        value: question.question,
                        onChange: (value) =>
                          setAttributes({
                            sections: updateQuestionField(sections, index, qIndex, "question", value),
                          }),
                      }),
                      wp.element.createElement(TextareaControl, {
                        label: "Respuesta",
                        value: question.answer,
                        onChange: (value) =>
                          setAttributes({
                            sections: updateQuestionField(sections, index, qIndex, "answer", value),
                          }),
                      }),
                      wp.element.createElement(
                        Button,
                        {
                          variant: "tertiary",
                          onClick: () => setAttributes({ sections: removeQuestion(sections, index, qIndex) }),
                        },
                        "Eliminar pregunta"
                      )
                    )
                  ),
                  wp.element.createElement(
                    Button,
                    {
                      variant: "secondary",
                      onClick: () => setAttributes({ sections: addQuestion(sections, index) }),
                    },
                    "Agregar pregunta"
                  )
                )
              )
            ),
            PanelColorSettings &&
              wp.element.createElement(PanelColorSettings, {
                title: "Colores de la interfaz",
                colorSettings: [
                  {
                    label: "Color de fondo general",
                    value: backgroundColor,
                    onChange: (value) => setAttributes({ backgroundColor: value }),
                  },
                  {
                    label: "Color del texto global",
                    value: textColor,
                    onChange: (value) => setAttributes({ textColor: value }),
                  },
                  {
                    label: "Color de cápsulas",
                    value: capsuleColor,
                    onChange: (value) => setAttributes({ capsuleColor: value }),
                    clearable: true,
                  },
                ],
              })
          ),
        wp.element.createElement(
          "div",
          blockProps,
          visibleSections.map((section, idx) =>
            wp.element.createElement(
              "article",
              {
                key: section.slug ? `preview-${section.slug}` : `preview-section-${idx}`,
                className: "fjord-faq-bar-preview",
                style: {
                  marginBottom: "16px",
                  background: "#fff",
                  padding: "12px 16px",
                  borderRadius: "16px",
                },
              },
              wp.element.createElement(
                "header",
                { className: "fjord-faq-bar__header" },
                wp.element.createElement("span", null, section.title || "Sección " + (index + 1))
              ),
              section.description
                ? wp.element.createElement("p", { style: { margin: "8px 0" } }, section.description)
                : null,
              (Array.isArray(section.questions) ? section.questions : []).map((question, qIndex) =>
                wp.element.createElement(
                  "div",
                  { key: "preview-question-" + qIndex, style: { marginBottom: "8px" } },
                  wp.element.createElement("strong", null, question.question),
                  wp.element.createElement("p", null, question.answer)
                )
              )
            )
          )
        )
      );
    },
    save: () => null,
  });
})(window.wp);
