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

  const slideConfig = [
    { key: "slide1", label: "Slide 1" },
    { key: "slide2", label: "Slide 2" },
    { key: "slide3", label: "Slide 3" },
    { key: "slide4", label: "Slide 4" },
    { key: "slide5", label: "Slide 5" },
  ];
  const defaultSlideOrder = ["slide2", "slide3", "slide1", "slide4", "slide5"];
  const getEnabledAttr = (key) => `${key}Enabled`;
  const getAttrKey = (key, suffix) => `${key}${suffix}`;
  const getButtonTextKey = (key) => `${key}ButtonText`;
  const getButtonUrlKey = (key) => `${key}ButtonUrl`;
  const getButtonBackgroundEnabledKey = (key) => `${key}ButtonBackgroundEnabled`;
  const getSlideHotspotAttrKey = (slideKey, index, suffix) =>
    `${slideKey}Hotspot${index}${suffix}`;
  const hotspotSlots = [
    { index: 1, label: "Hotspot 1", defaultX: 32, defaultY: 32 },
    { index: 2, label: "Hotspot 2", defaultX: 60, defaultY: 58 },
    { index: 3, label: "Hotspot 3", defaultX: 78, defaultY: 70 },
  ];
  const getNumericAttrValue = (value, fallback = 0) => {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : fallback;
  };

  const isSlideEnabled = (slide, attributes) => {
    const enabledAttr = getEnabledAttr(slide.key);
    const attrValue = attributes[enabledAttr];
    if (typeof attrValue === "boolean") {
      return attrValue;
    }
    return slide.key === "slide2" || slide.key === "slide3";
  };

  const getOrderedSlides = (attributes) => {
    const savedOrder =
      typeof attributes.slideOrder === "string"
        ? attributes.slideOrder.split(",").map((key) => key.trim())
        : [];
    const validOrder = savedOrder.filter((key) =>
      defaultSlideOrder.includes(key)
    );
    const missingSlides = defaultSlideOrder.filter(
      (key) => !validOrder.includes(key)
    );
    const orderedKeys = [...validOrder, ...missingSlides];
    return orderedKeys
      .map((key) => slideConfig.find((slide) => slide.key === key))
      .filter(Boolean);
  };

  const SlideHotspotPanel = ({ slideKey, slot, attributes, setAttributes }) => {
    const enabledKey = getSlideHotspotAttrKey(slideKey, slot.index, "Enabled");
    const imageKey = getSlideHotspotAttrKey(slideKey, slot.index, "Image");
    const textKey = getSlideHotspotAttrKey(slideKey, slot.index, "Text");
    const xKey = getSlideHotspotAttrKey(slideKey, slot.index, "X");
    const yKey = getSlideHotspotAttrKey(slideKey, slot.index, "Y");
    const backgroundKey = getSlideHotspotAttrKey(slideKey, slot.index, "Background");
    const textColorKey = getSlideHotspotAttrKey(slideKey, slot.index, "TextColor");

    const isEnabled =
      typeof attributes[enabledKey] === "boolean" ? attributes[enabledKey] : true;
    const xValue = getNumericAttrValue(attributes[xKey], slot.defaultX);
    const yValue = getNumericAttrValue(attributes[yKey], slot.defaultY);

    return wp.element.createElement(
      PanelBody,
      { title: slot.label, initialOpen: false },
      wp.element.createElement(ToggleControl, {
        label: isEnabled ? "Mostrar hotspot" : "Ocultar hotspot",
        checked: isEnabled,
        onChange: (value) => setAttributes({ [enabledKey]: value }),
      }),
      wp.element.createElement(
        MediaUploadCheck,
        null,
        wp.element.createElement(MediaUpload, {
          onSelect: (media) => setAttributes({ [imageKey]: media?.url || "" }),
          allowedTypes: ["image"],
          value: attributes[imageKey],
          render: ({ open }) =>
            wp.element.createElement(
              Button,
              { onClick: open, variant: "secondary" },
              attributes[imageKey] ? "Cambiar imagen" : "Seleccionar imagen"
            ),
        })
      ),
      attributes[imageKey]
        ? wp.element.createElement(
            "div",
            { style: { marginTop: "8px" } },
            wp.element.createElement("img", {
              src: attributes[imageKey],
              style: { width: "100%", borderRadius: "6px" },
              alt: "",
            })
          )
        : null,
      wp.element.createElement(TextareaControl, {
        label: "Texto del hotspot",
        value: attributes[textKey],
        onChange: (value) => setAttributes({ [textKey]: value }),
      }),
      wp.element.createElement(RangeControl, {
        label: "Posición X",
        value: xValue,
        min: 0,
        max: 100,
        step: 1,
        onChange: (value) => setAttributes({ [xKey]: value }),
      }),
      wp.element.createElement(RangeControl, {
        label: "Posición Y",
        value: yValue,
        min: 0,
        max: 100,
        step: 1,
        onChange: (value) => setAttributes({ [yKey]: value }),
      }),
      wp.element.createElement(TextControl, {
        label: "Color de fondo",
        type: "color",
        value: attributes[backgroundKey] || "#111111",
        onChange: (value) => setAttributes({ [backgroundKey]: value }),
      }),
      wp.element.createElement(
        Button,
        {
          isSmall: true,
          variant: "tertiary",
          onClick: () => setAttributes({ [backgroundKey]: "" }),
          style: { marginBottom: "6px" },
        },
        "Fondo por defecto"
      ),
      wp.element.createElement(TextControl, {
        label: "Color del texto",
        type: "color",
        value: attributes[textColorKey] || "#ffffff",
        onChange: (value) => setAttributes({ [textColorKey]: value }),
      }),
      wp.element.createElement(
        Button,
        {
          isSmall: true,
          variant: "tertiary",
          onClick: () => setAttributes({ [textColorKey]: "" }),
          style: { marginBottom: "6px" },
        },
        "Texto por defecto"
      )
    );
  };

  const SlidePanel = ({ slide, index, attributes, setAttributes }) => {
    const imageKey = getAttrKey(slide.key, "Image");
    const titleKey = getAttrKey(slide.key, "Title");
    const textKey = getAttrKey(slide.key, "Text");
    const buttonTextKey = getButtonTextKey(slide.key);
    const buttonUrlKey = getButtonUrlKey(slide.key);
    const cardBackgroundKey = getAttrKey(slide.key, "CardBackground");
    const cardTextColorKey = getAttrKey(slide.key, "CardTextColor");
    const buttonBackgroundKey = getAttrKey(slide.key, "ButtonBackground");
    const buttonTextColorKey = getAttrKey(slide.key, "ButtonTextColor");
    const buttonBackgroundEnabledKey = getButtonBackgroundEnabledKey(slide.key);
    const enabledKey = getEnabledAttr(slide.key);
    const hotspotsEnabledKey = `${slide.key}HotspotsEnabled`;
    const hotspotsEnabled = attributes[hotspotsEnabledKey] !== false;
    const buttonBackgroundEnabled = attributes[buttonBackgroundEnabledKey] !== false;

    const isEnabled = isSlideEnabled(slide, attributes, index);

    return wp.element.createElement(
      PanelBody,
      { title: slide.label, initialOpen: false },
      wp.element.createElement(ToggleControl, {
        label: isEnabled ? "Slide activado" : "Slide desactivado",
        checked: isEnabled,
        onChange: (value) => setAttributes({ [enabledKey]: value }),
      }),
      wp.element.createElement(
        MediaUploadCheck,
        null,
        wp.element.createElement(MediaUpload, {
          onSelect: (media) => setAttributes({ [imageKey]: media?.url || "" }),
          allowedTypes: ["image"],
          value: attributes[imageKey],
          render: ({ open }) =>
            wp.element.createElement(
              Button,
              { onClick: open, variant: "secondary" },
              attributes[imageKey] ? "Change image" : "Select image"
            ),
        })
      ),
      attributes[imageKey]
        ? wp.element.createElement(
            "div",
            { style: { marginTop: "8px" } },
            wp.element.createElement("img", {
              src: attributes[imageKey],
              style: { width: "100%", borderRadius: "6px" },
              alt: "",
            })
          )
        : null,
      wp.element.createElement(TextareaControl, {
        label: "Title",
        value: attributes[titleKey],
        onChange: (value) => setAttributes({ [titleKey]: value }),
      }),
      wp.element.createElement(TextareaControl, {
        label: "Text",
        value: attributes[textKey],
        onChange: (value) => setAttributes({ [textKey]: value }),
      }),
      wp.element.createElement(TextControl, {
        label: "Texto del botón",
        value: attributes[buttonTextKey],
        onChange: (value) => setAttributes({ [buttonTextKey]: value }),
      }),
      wp.element.createElement(TextControl, {
        label: "URL del botón",
        type: "url",
        value: attributes[buttonUrlKey],
        onChange: (value) => setAttributes({ [buttonUrlKey]: value }),
      }),
      wp.element.createElement(TextControl, {
        label: "Fondo del cuadro (card)",
        type: "color",
        value: attributes[cardBackgroundKey] || "#ffffff",
        onChange: (value) => setAttributes({ [cardBackgroundKey]: value }),
      }),
      wp.element.createElement(
        Button,
        {
          isSmall: true,
          variant: "tertiary",
          onClick: () => setAttributes({ [cardBackgroundKey]: "" }),
          style: { marginBottom: "6px" },
        },
        "Fondo por defecto"
      ),
      wp.element.createElement(TextControl, {
        label: "Color del texto del cuadro",
        type: "color",
        value: attributes[cardTextColorKey] || "#111111",
        onChange: (value) => setAttributes({ [cardTextColorKey]: value }),
      }),
      wp.element.createElement(
        Button,
        {
          isSmall: true,
          variant: "tertiary",
          onClick: () => setAttributes({ [cardTextColorKey]: "" }),
          style: { marginBottom: "6px" },
        },
        "Texto por defecto"
      ),
      wp.element.createElement(TextControl, {
        label: "Color del texto del botón",
        type: "color",
        value: attributes[buttonTextColorKey] || "#ffffff",
        onChange: (value) => setAttributes({ [buttonTextColorKey]: value }),
      }),
      wp.element.createElement(
        Button,
        {
          isSmall: true,
          variant: "tertiary",
          onClick: () => setAttributes({ [buttonTextColorKey]: "" }),
          style: { marginBottom: "6px" },
        },
        "Texto por defecto"
      ),
      wp.element.createElement(ToggleControl, {
        label: buttonBackgroundEnabled ? "Fondo del botón visible" : "Fondo del botón oculto",
        checked: buttonBackgroundEnabled,
        onChange: (value) => setAttributes({ [buttonBackgroundEnabledKey]: value }),
      }),
      buttonBackgroundEnabled
        ? wp.element.createElement(TextControl, {
            label: "Fondo del botón",
            type: "color",
            value: attributes[buttonBackgroundKey] || "#111111",
            onChange: (value) => setAttributes({ [buttonBackgroundKey]: value }),
          })
        : null,
      buttonBackgroundEnabled
        ? wp.element.createElement(
            Button,
            {
              isSmall: true,
              variant: "tertiary",
              onClick: () => setAttributes({ [buttonBackgroundKey]: "" }),
              style: { marginBottom: "6px" },
            },
            "Fondo por defecto"
          )
        : null,
      wp.element.createElement(
        "div",
        { style: { marginTop: "12px" } },
        wp.element.createElement(ToggleControl, {
          label: hotspotsEnabled ? "Hotspots visibles" : "Hotspots ocultos",
          checked: hotspotsEnabled,
          onChange: (value) => setAttributes({ [hotspotsEnabledKey]: value }),
        }),
        hotspotsEnabled
          ? hotspotSlots.map((slot) =>
              wp.element.createElement(SlideHotspotPanel, {
                key: slot.index,
                slideKey: slide.key,
                slot,
                attributes,
                setAttributes,
              })
            )
          : null
      )
    );
  };

  registerBlockType("fjord/hero", {
    edit: (props) => {
      const { attributes, setAttributes } = props;
      const blockProps = useBlockProps({
        className: "fjord-hero-block-editor",
      });
      const orderedSlides = getOrderedSlides(attributes);

      const activeSlides = orderedSlides.filter((slide) =>
        isSlideEnabled(slide, attributes)
      );
      const moveSlide = (fromKey, toKey, placeAfter = false) => {
        if (!fromKey || !toKey || fromKey === toKey) {
          return;
        }
        const currentOrder = orderedSlides.map((slide) => slide.key);
        const nextOrder = currentOrder.filter((key) => key !== fromKey);
        let toIndex = nextOrder.indexOf(toKey);
        if (toIndex === -1) {
          return;
        }
        if (placeAfter) {
          toIndex += 1;
        }
        nextOrder.splice(toIndex, 0, fromKey);
        setAttributes({ slideOrder: nextOrder.join(",") });
      };

      return wp.element.createElement(
        wp.element.Fragment,
        null,
        wp.element.createElement(
          InspectorControls,
          null,
        wp.element.createElement(
          PanelBody,
          { title: "Slider settings", initialOpen: true },
          wp.element.createElement(ToggleControl, {
            label: "Play automático",
            checked: attributes.autoplay,
            onChange: (value) => setAttributes({ autoplay: value }),
          }),
          wp.element.createElement(RangeControl, {
            label: "Velocidad (seg)",
            value: Math.max(
              2,
              Math.min(15, Math.round((attributes.autoplaySpeed || 7000) / 1000))
            ),
            min: 2,
            max: 15,
            step: 1,
            onChange: (value) => setAttributes({ autoplaySpeed: value * 1000 }),
          })
        ),
          wp.element.createElement(
            PanelBody,
            { title: "Orden de slides", initialOpen: true },
            wp.element.createElement(
              "p",
              { style: { marginTop: 0 } },
              "Arrastra los slides: el de mas arriba aparece primero."
            ),
            wp.element.createElement(
              "div",
              null,
              orderedSlides.map((slide, index) =>
                wp.element.createElement(
                  "div",
                  {
                    key: slide.key,
                    draggable: true,
                    onDragStart: (event) => {
                      event.dataTransfer.setData("text/plain", slide.key);
                      event.dataTransfer.effectAllowed = "move";
                    },
                    onDragOver: (event) => {
                      event.preventDefault();
                      event.dataTransfer.dropEffect = "move";
                    },
                    onDrop: (event) => {
                      event.preventDefault();
                      const bounds = event.currentTarget.getBoundingClientRect();
                      const placeAfter =
                        event.clientY > bounds.top + bounds.height / 2;
                      moveSlide(
                        event.dataTransfer.getData("text/plain"),
                        slide.key,
                        placeAfter
                      );
                    },
                    style: {
                      alignItems: "center",
                      background: "#fff",
                      border: "1px solid #dcdcde",
                      borderRadius: "4px",
                      cursor: "grab",
                      display: "flex",
                      gap: "8px",
                      justifyContent: "space-between",
                      marginBottom: "8px",
                      padding: "8px 10px",
                    },
                  },
                  wp.element.createElement(
                    "span",
                    null,
                    `${index + 1}. ${slide.label}`
                  ),
                  wp.element.createElement(
                    "span",
                    { style: { color: "#757575" } },
                    isSlideEnabled(slide, attributes) ? "Activo" : "Inactivo"
                  )
                )
              )
            )
          ),
          orderedSlides.map((slide, index) =>
            wp.element.createElement(SlidePanel, {
              key: slide.key,
              slide,
              index,
              attributes,
              setAttributes,
            })
          )
        ),
        wp.element.createElement(
          "div",
          blockProps,
          activeSlides.map((slide) =>
            wp.element.createElement(
              "div",
              {
                key: slide.key,
                style: {
                  border: "1px solid #e6e6e6",
                  borderRadius: "8px",
                  padding: "12px",
                  marginBottom: "12px",
                  background: "#fff",
                },
              },
              wp.element.createElement("strong", null, slide.label),
              wp.element.createElement(
                "div",
                { style: { marginTop: "6px", color: "#666" } },
                attributes[getAttrKey(slide.key, "Title")] || "Title"
              )
            )
          )
        )
      );
    },
    save: () => null,
  });
})(window.wp);
